Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
The pyxform file utility functions.
"""
def _section_name(path_or_file_name):
directory, filename = os.path.split(path_or_file_name)
section_name, extension = os.path.splitext(filename)
return section_name
def load_file_to_dict(path):
"""
Takes a file path and loads it into a nested json dict
following the format in json_form_schema.json
The file may be a xls file or json file.
If it is xls it is converted using xls2json.
"""
if path.endswith(".json"):
name = _section_name(path)
<|code_end|>
. Use current file imports:
import glob
import os
from pyxform import utils
from pyxform.xls2json import SurveyReader
and context (classes, functions, or code) from other files:
# Path: pyxform/utils.py
# SEP = "_"
# TAG_START_CHAR = r"[a-zA-Z:_]"
# TAG_CHAR = r"[a-zA-Z:_0-9\-.]"
# XFORM_TAG_REGEXP = "%(start)s%(char)s*" % {"start": TAG_START_CHAR, "char": TAG_CHAR}
# INVALID_XFORM_TAG_REGEXP = r"[^a-zA-Z:_][^a-zA-Z:_0-9\-.]*"
# LAST_SAVED_INSTANCE_NAME = "__last-saved"
# BRACKETED_TAG_REGEX = re.compile(r"\${(last-saved#)?(.*?)}")
# LAST_SAVED_REGEX = re.compile(r"\${last-saved#(.*?)}")
# NSMAP = {
# "xmlns": "http://www.w3.org/2002/xforms",
# "xmlns:h": "http://www.w3.org/1999/xhtml",
# "xmlns:ev": "http://www.w3.org/2001/xml-events",
# "xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
# "xmlns:jr": "http://openrosa.org/javarosa",
# "xmlns:orx": "http://openrosa.org/xforms",
# "xmlns:odk": "http://www.opendatakit.org/xforms",
# }
# class DetachableElement(Element):
# class PatchedText(Text):
# def __init__(self, *args, **kwargs):
# def writexml(self, writer, indent="", addindent="", newl=""):
# def is_valid_xml_tag(tag):
# def node(*args, **kwargs):
# def get_pyobj_from_json(str_or_path):
# def flatten(li):
# def sheet_to_csv(workbook_path, csv_path, sheet_name):
# def xls_sheet_to_csv(workbook_path, csv_path, sheet_name):
# def xlsx_sheet_to_csv(workbook_path, csv_path, sheet_name):
# def has_external_choices(json_struct):
# def get_languages_with_bad_tags(languages):
# def default_is_dynamic(element_default, element_type=None):
# def has_dynamic_label(choice_list, multi_language):
# def levenshtein_distance(a: str, b: str) -> int:
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
. Output only the next line. | return name, utils.get_pyobj_from_json(path) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
The pyxform file utility functions.
"""
def _section_name(path_or_file_name):
directory, filename = os.path.split(path_or_file_name)
section_name, extension = os.path.splitext(filename)
return section_name
def load_file_to_dict(path):
"""
Takes a file path and loads it into a nested json dict
following the format in json_form_schema.json
The file may be a xls file or json file.
If it is xls it is converted using xls2json.
"""
if path.endswith(".json"):
name = _section_name(path)
return name, utils.get_pyobj_from_json(path)
else:
name = _section_name(path)
<|code_end|>
. Use current file imports:
(import glob
import os
from pyxform import utils
from pyxform.xls2json import SurveyReader)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/utils.py
# SEP = "_"
# TAG_START_CHAR = r"[a-zA-Z:_]"
# TAG_CHAR = r"[a-zA-Z:_0-9\-.]"
# XFORM_TAG_REGEXP = "%(start)s%(char)s*" % {"start": TAG_START_CHAR, "char": TAG_CHAR}
# INVALID_XFORM_TAG_REGEXP = r"[^a-zA-Z:_][^a-zA-Z:_0-9\-.]*"
# LAST_SAVED_INSTANCE_NAME = "__last-saved"
# BRACKETED_TAG_REGEX = re.compile(r"\${(last-saved#)?(.*?)}")
# LAST_SAVED_REGEX = re.compile(r"\${last-saved#(.*?)}")
# NSMAP = {
# "xmlns": "http://www.w3.org/2002/xforms",
# "xmlns:h": "http://www.w3.org/1999/xhtml",
# "xmlns:ev": "http://www.w3.org/2001/xml-events",
# "xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
# "xmlns:jr": "http://openrosa.org/javarosa",
# "xmlns:orx": "http://openrosa.org/xforms",
# "xmlns:odk": "http://www.opendatakit.org/xforms",
# }
# class DetachableElement(Element):
# class PatchedText(Text):
# def __init__(self, *args, **kwargs):
# def writexml(self, writer, indent="", addindent="", newl=""):
# def is_valid_xml_tag(tag):
# def node(*args, **kwargs):
# def get_pyobj_from_json(str_or_path):
# def flatten(li):
# def sheet_to_csv(workbook_path, csv_path, sheet_name):
# def xls_sheet_to_csv(workbook_path, csv_path, sheet_name):
# def xlsx_sheet_to_csv(workbook_path, csv_path, sheet_name):
# def has_external_choices(json_struct):
# def get_languages_with_bad_tags(languages):
# def default_is_dynamic(element_default, element_type=None):
# def has_dynamic_label(choice_list, multi_language):
# def levenshtein_distance(a: str, b: str) -> int:
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
. Output only the next line. | excel_reader = SurveyReader(path, name) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Section survey element module.
"""
class Section(SurveyElement):
def validate(self):
super(Section, self).validate()
for element in self.children:
element.validate()
self._validate_uniqueness_of_element_names()
# there's a stronger test of this when creating the xpath
# dictionary for a survey.
def _validate_uniqueness_of_element_names(self):
element_slugs = set()
for element in self.children:
elem_lower = element.name.lower()
if elem_lower in element_slugs:
<|code_end|>
, predict the immediate next line with the help of imports:
from pyxform.errors import PyXFormError
from pyxform.external_instance import ExternalInstance
from pyxform.question import SurveyElement
from pyxform.utils import node
and context (classes, functions, sometimes code) from other files:
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
#
# Path: pyxform/external_instance.py
# class ExternalInstance(SurveyElement):
# def xml_control(self):
# """
# No-op since there is no associated form control to place under <body/>.
#
# Exists here because there's a soft abstractmethod in SurveyElement.
# """
# pass
#
# Path: pyxform/question.py
# class Question(SurveyElement):
# class InputQuestion(Question):
# class TriggerQuestion(Question):
# class UploadQuestion(Question):
# class Option(SurveyElement):
# class MultipleChoiceQuestion(Question):
# class SelectOneQuestion(MultipleChoiceQuestion):
# class Tag(SurveyElement):
# class OsmUploadQuestion(UploadQuestion):
# class RangeQuestion(Question):
# def validate(self):
# def xml_instance(self, **kwargs):
# def xml_control(self):
# def nest_setvalues(self, xml_node):
# def build_xml(self):
# def build_xml(self):
# def build_xml(self):
# def _get_media_type(self):
# def build_xml(self):
# def xml_value(self):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_choice(self, **kwargs):
# def validate(self):
# def build_xml(self):
# def __init__(self, **kwargs):
# def __init__(self, **kwargs):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_tag(self, **kwargs):
# def build_xml(self):
# def build_xml(self):
#
# Path: pyxform/utils.py
# def node(*args, **kwargs):
# """
# args[0] -- a XML tag
# args[1:] -- an array of children to append to the newly created node
# or if a unicode arg is supplied it will be used to make a text node
# kwargs -- attributes
# returns a xml.dom.minidom.Element
# """
# blocked_attributes = ["tag"]
# tag = args[0] if len(args) > 0 else kwargs["tag"]
# args = args[1:]
# result = DetachableElement(tag)
# unicode_args = [u for u in args if type(u) == str]
# assert len(unicode_args) <= 1
# parsed_string = False
#
# # Convert the kwargs xml attribute dictionary to a xml.dom.minidom.Element. Sort the
# # attributes to guarantee a consistent order across Python versions.
# # See pyxform_test_case.reorder_attributes for details.
# for k, v in iter(sorted(kwargs.items())):
# if k in blocked_attributes:
# continue
# if k == "toParseString":
# if v is True and len(unicode_args) == 1:
# parsed_string = True
# # Add this header string so parseString can be used?
# s = (
# '<?xml version="1.0" ?><'
# + tag
# + ">"
# + unicode_args[0]
# + "</"
# + tag
# + ">"
# )
# parsed_node = parseString(s.encode("utf-8")).documentElement
# # Move node's children to the result Element
# # discarding node's root
# for child in parsed_node.childNodes:
# # No tests seem to involve moving elements with children.
# # Deep clone used anyway in case of unknown edge cases.
# result.appendChild(child.cloneNode(deep=True))
# else:
# result.setAttribute(k, v)
#
# if len(unicode_args) == 1 and not parsed_string:
# text_node = PatchedText()
# text_node.data = unicode_args[0]
# result.appendChild(text_node)
# for n in args:
# if type(n) == int or type(n) == float or type(n) == bytes:
# text_node = PatchedText()
# text_node.data = str(n)
# result.appendChild(text_node)
# elif type(n) is not str:
# result.appendChild(n)
# return result
. Output only the next line. | raise PyXFormError( |
Using the snippet: <|code_start|> for element in self.children:
elem_lower = element.name.lower()
if elem_lower in element_slugs:
raise PyXFormError(
"There are more than one survey elements named '%s' "
"(case-insensitive) in the section named '%s'."
% (elem_lower, self.name)
)
element_slugs.add(elem_lower)
def xml_instance(self, **kwargs):
"""
Creates an xml representation of the section
"""
append_template = kwargs.pop("append_template", False)
attributes = {}
attributes.update(kwargs)
attributes.update(self.get("instance", {}))
survey = self.get_root()
# Resolve field references in attributes
for key, value in attributes.items():
attributes[key] = survey.insert_xpaths(value, self)
result = node(self.name, **attributes)
for child in self.children:
repeating_template = None
if child.get("flat"):
for grandchild in child.xml_instance_array():
result.appendChild(grandchild)
<|code_end|>
, determine the next line of code. You have imports:
from pyxform.errors import PyXFormError
from pyxform.external_instance import ExternalInstance
from pyxform.question import SurveyElement
from pyxform.utils import node
and context (class names, function names, or code) available:
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
#
# Path: pyxform/external_instance.py
# class ExternalInstance(SurveyElement):
# def xml_control(self):
# """
# No-op since there is no associated form control to place under <body/>.
#
# Exists here because there's a soft abstractmethod in SurveyElement.
# """
# pass
#
# Path: pyxform/question.py
# class Question(SurveyElement):
# class InputQuestion(Question):
# class TriggerQuestion(Question):
# class UploadQuestion(Question):
# class Option(SurveyElement):
# class MultipleChoiceQuestion(Question):
# class SelectOneQuestion(MultipleChoiceQuestion):
# class Tag(SurveyElement):
# class OsmUploadQuestion(UploadQuestion):
# class RangeQuestion(Question):
# def validate(self):
# def xml_instance(self, **kwargs):
# def xml_control(self):
# def nest_setvalues(self, xml_node):
# def build_xml(self):
# def build_xml(self):
# def build_xml(self):
# def _get_media_type(self):
# def build_xml(self):
# def xml_value(self):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_choice(self, **kwargs):
# def validate(self):
# def build_xml(self):
# def __init__(self, **kwargs):
# def __init__(self, **kwargs):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_tag(self, **kwargs):
# def build_xml(self):
# def build_xml(self):
#
# Path: pyxform/utils.py
# def node(*args, **kwargs):
# """
# args[0] -- a XML tag
# args[1:] -- an array of children to append to the newly created node
# or if a unicode arg is supplied it will be used to make a text node
# kwargs -- attributes
# returns a xml.dom.minidom.Element
# """
# blocked_attributes = ["tag"]
# tag = args[0] if len(args) > 0 else kwargs["tag"]
# args = args[1:]
# result = DetachableElement(tag)
# unicode_args = [u for u in args if type(u) == str]
# assert len(unicode_args) <= 1
# parsed_string = False
#
# # Convert the kwargs xml attribute dictionary to a xml.dom.minidom.Element. Sort the
# # attributes to guarantee a consistent order across Python versions.
# # See pyxform_test_case.reorder_attributes for details.
# for k, v in iter(sorted(kwargs.items())):
# if k in blocked_attributes:
# continue
# if k == "toParseString":
# if v is True and len(unicode_args) == 1:
# parsed_string = True
# # Add this header string so parseString can be used?
# s = (
# '<?xml version="1.0" ?><'
# + tag
# + ">"
# + unicode_args[0]
# + "</"
# + tag
# + ">"
# )
# parsed_node = parseString(s.encode("utf-8")).documentElement
# # Move node's children to the result Element
# # discarding node's root
# for child in parsed_node.childNodes:
# # No tests seem to involve moving elements with children.
# # Deep clone used anyway in case of unknown edge cases.
# result.appendChild(child.cloneNode(deep=True))
# else:
# result.setAttribute(k, v)
#
# if len(unicode_args) == 1 and not parsed_string:
# text_node = PatchedText()
# text_node.data = unicode_args[0]
# result.appendChild(text_node)
# for n in args:
# if type(n) == int or type(n) == float or type(n) == bytes:
# text_node = PatchedText()
# text_node.data = str(n)
# result.appendChild(text_node)
# elif type(n) is not str:
# result.appendChild(n)
# return result
. Output only the next line. | elif isinstance(child, ExternalInstance): |
Using the snippet: <|code_start|> element.validate()
self._validate_uniqueness_of_element_names()
# there's a stronger test of this when creating the xpath
# dictionary for a survey.
def _validate_uniqueness_of_element_names(self):
element_slugs = set()
for element in self.children:
elem_lower = element.name.lower()
if elem_lower in element_slugs:
raise PyXFormError(
"There are more than one survey elements named '%s' "
"(case-insensitive) in the section named '%s'."
% (elem_lower, self.name)
)
element_slugs.add(elem_lower)
def xml_instance(self, **kwargs):
"""
Creates an xml representation of the section
"""
append_template = kwargs.pop("append_template", False)
attributes = {}
attributes.update(kwargs)
attributes.update(self.get("instance", {}))
survey = self.get_root()
# Resolve field references in attributes
for key, value in attributes.items():
attributes[key] = survey.insert_xpaths(value, self)
<|code_end|>
, determine the next line of code. You have imports:
from pyxform.errors import PyXFormError
from pyxform.external_instance import ExternalInstance
from pyxform.question import SurveyElement
from pyxform.utils import node
and context (class names, function names, or code) available:
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
#
# Path: pyxform/external_instance.py
# class ExternalInstance(SurveyElement):
# def xml_control(self):
# """
# No-op since there is no associated form control to place under <body/>.
#
# Exists here because there's a soft abstractmethod in SurveyElement.
# """
# pass
#
# Path: pyxform/question.py
# class Question(SurveyElement):
# class InputQuestion(Question):
# class TriggerQuestion(Question):
# class UploadQuestion(Question):
# class Option(SurveyElement):
# class MultipleChoiceQuestion(Question):
# class SelectOneQuestion(MultipleChoiceQuestion):
# class Tag(SurveyElement):
# class OsmUploadQuestion(UploadQuestion):
# class RangeQuestion(Question):
# def validate(self):
# def xml_instance(self, **kwargs):
# def xml_control(self):
# def nest_setvalues(self, xml_node):
# def build_xml(self):
# def build_xml(self):
# def build_xml(self):
# def _get_media_type(self):
# def build_xml(self):
# def xml_value(self):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_choice(self, **kwargs):
# def validate(self):
# def build_xml(self):
# def __init__(self, **kwargs):
# def __init__(self, **kwargs):
# def xml(self):
# def validate(self):
# def __init__(self, **kwargs):
# def add_tag(self, **kwargs):
# def build_xml(self):
# def build_xml(self):
#
# Path: pyxform/utils.py
# def node(*args, **kwargs):
# """
# args[0] -- a XML tag
# args[1:] -- an array of children to append to the newly created node
# or if a unicode arg is supplied it will be used to make a text node
# kwargs -- attributes
# returns a xml.dom.minidom.Element
# """
# blocked_attributes = ["tag"]
# tag = args[0] if len(args) > 0 else kwargs["tag"]
# args = args[1:]
# result = DetachableElement(tag)
# unicode_args = [u for u in args if type(u) == str]
# assert len(unicode_args) <= 1
# parsed_string = False
#
# # Convert the kwargs xml attribute dictionary to a xml.dom.minidom.Element. Sort the
# # attributes to guarantee a consistent order across Python versions.
# # See pyxform_test_case.reorder_attributes for details.
# for k, v in iter(sorted(kwargs.items())):
# if k in blocked_attributes:
# continue
# if k == "toParseString":
# if v is True and len(unicode_args) == 1:
# parsed_string = True
# # Add this header string so parseString can be used?
# s = (
# '<?xml version="1.0" ?><'
# + tag
# + ">"
# + unicode_args[0]
# + "</"
# + tag
# + ">"
# )
# parsed_node = parseString(s.encode("utf-8")).documentElement
# # Move node's children to the result Element
# # discarding node's root
# for child in parsed_node.childNodes:
# # No tests seem to involve moving elements with children.
# # Deep clone used anyway in case of unknown edge cases.
# result.appendChild(child.cloneNode(deep=True))
# else:
# result.setAttribute(k, v)
#
# if len(unicode_args) == 1 and not parsed_string:
# text_node = PatchedText()
# text_node.data = unicode_args[0]
# result.appendChild(text_node)
# for n in args:
# if type(n) == int or type(n) == float or type(n) == bytes:
# text_node = PatchedText()
# text_node.data = str(n)
# result.appendChild(text_node)
# elif type(n) is not str:
# result.appendChild(n)
# return result
. Output only the next line. | result = node(self.name, **attributes) |
Next line prediction: <|code_start|> + " Values must begin with a letter or underscore. Subsequent "
+ "characters can include letters, numbers, dashes, underscores, and periods."
)
def value_or_label_test(value: str) -> bool:
query = re.search(r"^[a-zA-Z_][a-zA-Z0-9\-_\.]*$", value)
if query is None:
return False
else:
return query.group(0) == value
def value_or_label_check(name: str, value: str, row_number: int) -> None:
"""
Check parameter values for invalid characters for use in a XPath expression.
For example for a value of "val*", ODK Validate will throw an error like that shown
below. This check looks for characters which seem to avoid the error.
>> Something broke the parser. See above for a hint.
org.javarosa.xpath.XPathException: XPath evaluation: Parse error in XPath path: [val*].
Bad node: org.javarosa.xpath.parser.ast.ASTNodeAbstractExpr@63e2203c
:param name: The name of the parameter value.
:param value: The parameter value to validate.
:param row_number: The survey sheet row number.
"""
if not value_or_label_test(value=value):
msg = value_or_label_format_msg(name=name, row_number=row_number)
<|code_end|>
. Use current file imports:
(import re
from pyxform.constants import ROW_FORMAT_STRING
from pyxform.errors import PyXFormError)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/constants.py
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
. Output only the next line. | raise PyXFormError(msg) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test xls2json_backends util functions.
"""
class BackendUtilsTests(TestCase):
def test_xls_to_csv(self):
specify_other_xls = utils.path_to_text_fixture("specify_other.xls")
<|code_end|>
using the current file's imports:
from unittest import TestCase
from pyxform.xls2json_backends import convert_file_to_csv_string
from tests import utils
and any relevant context from other files:
# Path: pyxform/xls2json_backends.py
# def convert_file_to_csv_string(path):
# """
# This will open a csv or xls file and return a CSV in the format:
# sheet_name1
# ,col1,col2
# ,r1c1,r1c2
# ,r2c1,r2c2
# sheet_name2
# ,col1,col2
# ,r1c1,r1c2
# ,r2c1,r2c2
#
# Currently, it processes csv files and xls files to ensure consistent
# csv delimiters, etc. for tests.
# """
# if path.endswith(".csv"):
# imported_sheets = csv_to_dict(path)
# else:
# imported_sheets = xls_to_dict(path)
# foo = StringIO(newline="")
# writer = csv.writer(foo, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
# for sheet_name, rows in imported_sheets.items():
# writer.writerow([sheet_name])
# out_keys = []
# out_rows = []
# for row in rows:
# out_row = []
# for key in row.keys():
# if key not in out_keys:
# out_keys.append(key)
# for out_key in out_keys:
# out_row.append(row.get(out_key, None))
# out_rows.append(out_row)
# writer.writerow([None] + out_keys)
# for out_row in out_rows:
# writer.writerow([None] + out_row)
# return foo.getvalue()
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | converted_xls = convert_file_to_csv_string(specify_other_xls) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test xls2json_backends util functions.
"""
class BackendUtilsTests(TestCase):
def test_xls_to_csv(self):
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pyxform.xls2json_backends import convert_file_to_csv_string
from tests import utils
and context (classes, functions, or code) from other files:
# Path: pyxform/xls2json_backends.py
# def convert_file_to_csv_string(path):
# """
# This will open a csv or xls file and return a CSV in the format:
# sheet_name1
# ,col1,col2
# ,r1c1,r1c2
# ,r2c1,r2c2
# sheet_name2
# ,col1,col2
# ,r1c1,r1c2
# ,r2c1,r2c2
#
# Currently, it processes csv files and xls files to ensure consistent
# csv delimiters, etc. for tests.
# """
# if path.endswith(".csv"):
# imported_sheets = csv_to_dict(path)
# else:
# imported_sheets = xls_to_dict(path)
# foo = StringIO(newline="")
# writer = csv.writer(foo, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
# for sheet_name, rows in imported_sheets.items():
# writer.writerow([sheet_name])
# out_keys = []
# out_rows = []
# for row in rows:
# out_row = []
# for key in row.keys():
# if key not in out_keys:
# out_keys.append(key)
# for out_key in out_keys:
# out_row.append(row.get(out_key, None))
# out_rows.append(out_row)
# writer.writerow([None] + out_keys)
# for out_row in out_rows:
# writer.writerow([None] + out_row)
# return foo.getvalue()
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | specify_other_xls = utils.path_to_text_fixture("specify_other.xls") |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Tests by file. Runs through a list of *.xls files, and expects that the output
for a *.xml with a matching prefix before the . is as expected. Possibly risky:
all tests in this file are defined according to matching files.
"""
class MainTest(TestCase):
def runTest(self):
files_to_test = ["instance_xmlns_test.xls"]
for file_to_test in files_to_test:
path_to_excel_file = utils.path_to_text_fixture(file_to_test)
# Get the xform output path:
directory, filename = os.path.split(path_to_excel_file)
root_filename, ext = os.path.splitext(filename)
path_to_output_xform = os.path.join(directory, root_filename + "_output.xml")
path_to_expected_xform = os.path.join(directory, root_filename + ".xml")
# Do the conversion:
<|code_end|>
, generate the next line using the imports in this file:
import codecs
import os
import sys
import xml.etree.ElementTree as ETree
import pyxform
from unittest import TestCase
from formencode.doctest_xml_compare import xml_compare
from pyxform import xls2json
from tests import utils
and context (functions, classes, or occasionally code) from other files:
# Path: pyxform/xls2json.py
# SMART_QUOTES = {"\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"'}
# _MSG_SUPPRESS_SPELLING = (
# " If you do not mean to include a sheet, to suppress this message, "
# "prefix the sheet name with an underscore. For example 'setting' "
# "becomes '_setting'."
# )
# def print_pyobj_to_json(pyobj, path=None):
# def merge_dicts(dict_a, dict_b, default_key="default"):
# def list_to_nested_dict(lst):
# def replace_smart_quotes_in_dict(_d):
# def dealias_and_group_headers(
# dict_array: "List[Dict]",
# header_aliases: "Dict",
# use_double_colons: bool,
# default_language: str = constants.DEFAULT_LANGUAGE_VALUE,
# ignore_case: bool = False,
# ):
# def dealias_types(dict_array):
# def clean_text_values(dict_array):
# def check_name_uniqueness(dict_array):
# def group_dictionaries_by_key(list_of_dicts, key, remove_key=True):
# def has_double_colon(workbook_dict) -> bool:
# def add_flat_annotations(prompt_list, parent_relevant="", name_prefix=""):
# def process_range_question_type(row):
# def process_image_default(default_value):
# def find_sheet_misspellings(key: str, keys: "KeysView") -> "Optional[str]":
# def workbook_to_json(
# workbook_dict,
# form_name=None,
# fallback_form_name=None,
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# warnings=None,
# ) -> "Dict[str, Any]":
# def parse_file_to_workbook_dict(path, file_object=None):
# def get_filename(path):
# def parse_file_to_json(
# path,
# default_name="data",
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# warnings=None,
# file_object=None,
# ):
# def organize_by_values(dict_list, key):
# def get_parameters(raw_parameters, allowed_parameters):
# def __init__(self, path_or_file):
# def to_json_dict(self):
# def print_json_to_file(self, filename=""):
# def __init__(self, path_or_file, default_name=None):
# def print_warning_log(self, warn_out_file):
# def __init__(self, path):
# def _setup_question_types_dictionary(self):
# def __init__(self, path):
# def _organize_renames(self):
# class SpreadsheetReader:
# class SurveyReader(SpreadsheetReader):
# class QuestionTypesReader(SpreadsheetReader):
# class VariableNameReader(SpreadsheetReader):
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | json_survey = xls2json.parse_file_to_json( |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Tests by file. Runs through a list of *.xls files, and expects that the output
for a *.xml with a matching prefix before the . is as expected. Possibly risky:
all tests in this file are defined according to matching files.
"""
class MainTest(TestCase):
def runTest(self):
files_to_test = ["instance_xmlns_test.xls"]
for file_to_test in files_to_test:
<|code_end|>
. Use current file imports:
(import codecs
import os
import sys
import xml.etree.ElementTree as ETree
import pyxform
from unittest import TestCase
from formencode.doctest_xml_compare import xml_compare
from pyxform import xls2json
from tests import utils)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/xls2json.py
# SMART_QUOTES = {"\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"'}
# _MSG_SUPPRESS_SPELLING = (
# " If you do not mean to include a sheet, to suppress this message, "
# "prefix the sheet name with an underscore. For example 'setting' "
# "becomes '_setting'."
# )
# def print_pyobj_to_json(pyobj, path=None):
# def merge_dicts(dict_a, dict_b, default_key="default"):
# def list_to_nested_dict(lst):
# def replace_smart_quotes_in_dict(_d):
# def dealias_and_group_headers(
# dict_array: "List[Dict]",
# header_aliases: "Dict",
# use_double_colons: bool,
# default_language: str = constants.DEFAULT_LANGUAGE_VALUE,
# ignore_case: bool = False,
# ):
# def dealias_types(dict_array):
# def clean_text_values(dict_array):
# def check_name_uniqueness(dict_array):
# def group_dictionaries_by_key(list_of_dicts, key, remove_key=True):
# def has_double_colon(workbook_dict) -> bool:
# def add_flat_annotations(prompt_list, parent_relevant="", name_prefix=""):
# def process_range_question_type(row):
# def process_image_default(default_value):
# def find_sheet_misspellings(key: str, keys: "KeysView") -> "Optional[str]":
# def workbook_to_json(
# workbook_dict,
# form_name=None,
# fallback_form_name=None,
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# warnings=None,
# ) -> "Dict[str, Any]":
# def parse_file_to_workbook_dict(path, file_object=None):
# def get_filename(path):
# def parse_file_to_json(
# path,
# default_name="data",
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# warnings=None,
# file_object=None,
# ):
# def organize_by_values(dict_list, key):
# def get_parameters(raw_parameters, allowed_parameters):
# def __init__(self, path_or_file):
# def to_json_dict(self):
# def print_json_to_file(self, filename=""):
# def __init__(self, path_or_file, default_name=None):
# def print_warning_log(self, warn_out_file):
# def __init__(self, path):
# def _setup_question_types_dictionary(self):
# def __init__(self, path):
# def _organize_renames(self):
# class SpreadsheetReader:
# class SurveyReader(SpreadsheetReader):
# class QuestionTypesReader(SpreadsheetReader):
# class VariableNameReader(SpreadsheetReader):
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | path_to_excel_file = utils.path_to_text_fixture(file_to_test) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Aliases for elements which could mean the same element in XForm but is represented
differently on the XLSForm.
"""
# Aliases:
# Ideally aliases should resolve to elements in the json form schema
# select, control and settings alias keys used for parsing,
# which is why self mapped keys are necessary.
control = {
<|code_end|>
. Write the next line using the current file imports:
from pyxform import constants
and context from other files:
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
, which may include functions, classes, or code. Output only the next line. | "group": constants.GROUP, |
Given the code snippet: <|code_start|> u"my_string": u"lor\xe9m ipsum",
},
u"children": [
{
u"name": u"your_name",
u"label": {u"english": u"What is your name?"},
u"type": u"text",
},
{
u"name": u"your_age",
u"label": {u"english": u"How many years old are you?"},
u"type": u"integer",
},
{
"children": [
{
"bind": {"jr:preload": "uid", "readonly": "true()"},
"name": "instanceID",
"type": "calculate",
}
],
"control": {"bodyless": True},
"name": "meta",
"type": "group",
},
],
}
self.assertEqual(survey_reader.to_json_dict(), expected_dict)
def test_settings(self):
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from pyxform.xls2json import SurveyReader
from tests import utils
and context (functions, classes, or occasionally code) from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | survey = create_survey_from_path(self.path) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test settings sheet syntax.
"""
class SettingsTests(TestCase):
maxDiff = None
def setUp(self):
self.path = utils.path_to_text_fixture("settings.xls")
def test_survey_reader(self):
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from pyxform.xls2json import SurveyReader
from tests import utils
and context from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
, which may include functions, classes, or code. Output only the next line. | survey_reader = SurveyReader(self.path, default_name="settings") |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Test settings sheet syntax.
"""
class SettingsTests(TestCase):
maxDiff = None
def setUp(self):
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from pyxform.builder import create_survey_from_path
from pyxform.xls2json import SurveyReader
from tests import utils)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | self.path = utils.path_to_text_fixture("settings.xls") |
Based on the snippet: <|code_start|> # e.g. ("jr:constraintMsg", "Try again")
for bind_type, bind_cell in cell_content.items():
process_cell(typ=bind_type, cell=bind_cell)
else:
process_cell(typ=column_type, cell=cell_content)
missing = defaultdict(list)
for lang, lang_trans in translations_seen.items():
for seen_tran in translation_columns_seen:
if seen_tran not in lang_trans:
missing[lang].append(seen_tran)
return missing
def missing_translations_check(
survey_sheet: "SheetData",
choices_sheet: "SheetData",
warnings: "List[str]",
):
"""
Add a warning if there are missing translation columns in the survey or choices data.
:param survey_sheet: The survey sheet data.
:param choices_sheet: The choices sheet data.
:param warnings: The warnings list, which may be empty.
:return: The warnings list, possibly with a new message, otherwise unchanged.
"""
survey_missing_trans = find_missing_translations(
sheet_data=survey_sheet,
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import defaultdict
from typing import TYPE_CHECKING
from pyxform import aliases, constants
from pyxform.errors import PyXFormError
from typing import Dict, List, Optional, Sequence, Union
and context (classes, functions, sometimes code) from other files:
# Path: pyxform/aliases.py
# TRANSLATABLE_SURVEY_COLUMNS = {
# constants.LABEL: constants.LABEL,
# # Per ODK Spec, could include "short" once pyxform supports it.
# constants.HINT: constants.HINT,
# "guidance_hint": "guidance_hint",
# "image": survey_header["image"],
# # Per ODK Spec, could include "big-image" once pyxform supports it.
# "audio": survey_header["audio"],
# "video": survey_header["video"],
# "jr:constraintMsg": "constraint_message",
# "jr:requiredMsg": "required_message",
# }
# TRANSLATABLE_CHOICES_COLUMNS = {
# "label": constants.LABEL,
# "image": "media::image",
# "audio": "media::audio",
# "video": "media::video",
# }
#
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
. Output only the next line. | translatable_columns=aliases.TRANSLATABLE_SURVEY_COLUMNS, |
Given the following code snippet before the placeholder: <|code_start|>) -> "Optional[str]":
"""
Format the missing translations data into a warning message.
:param _in: A dict structured as Dict[survey|choices: Dict[language: (columns)]].
In other words, for the survey or choices sheet, a dict of the language(s) and
column names for which there are missing translations.
:return: The warning message, or None if there were no missing columns.
"""
def get_sheet_msg(name, sheet):
if sheet is not None:
langs = sorted(sheet.keys())
if 0 < len(langs):
lang_msgs = []
for lang in langs:
cols = sheet[lang]
if isinstance(cols, str):
msg = f"Expected a sequence of columns, got a string for {lang}."
PyXFormError(msg)
if 1 == len(cols):
msg = f"Language '{lang}' is missing the {name} {cols[0]} column."
lang_msgs.append(msg)
if 1 < len(cols):
c = ", ".join(sorted(cols))
msg = f"Language '{lang}' is missing the {name} columns {c}."
lang_msgs.append(msg)
return "\n".join(lang_msgs)
return None
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from typing import TYPE_CHECKING
from pyxform import aliases, constants
from pyxform.errors import PyXFormError
from typing import Dict, List, Optional, Sequence, Union
and context including class names, function names, and sometimes code from other files:
# Path: pyxform/aliases.py
# TRANSLATABLE_SURVEY_COLUMNS = {
# constants.LABEL: constants.LABEL,
# # Per ODK Spec, could include "short" once pyxform supports it.
# constants.HINT: constants.HINT,
# "guidance_hint": "guidance_hint",
# "image": survey_header["image"],
# # Per ODK Spec, could include "big-image" once pyxform supports it.
# "audio": survey_header["audio"],
# "video": survey_header["video"],
# "jr:constraintMsg": "constraint_message",
# "jr:requiredMsg": "required_message",
# }
# TRANSLATABLE_CHOICES_COLUMNS = {
# "label": constants.LABEL,
# "image": "media::image",
# "audio": "media::audio",
# "video": "media::video",
# }
#
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
. Output only the next line. | survey = get_sheet_msg(name=constants.SURVEY, sheet=_in.get(constants.SURVEY)) |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
SheetData = List[Dict[str, Union[str, Dict]]]
def format_missing_translations_msg(
_in: "Dict[str, Dict[str, Sequence]]",
) -> "Optional[str]":
"""
Format the missing translations data into a warning message.
:param _in: A dict structured as Dict[survey|choices: Dict[language: (columns)]].
In other words, for the survey or choices sheet, a dict of the language(s) and
column names for which there are missing translations.
:return: The warning message, or None if there were no missing columns.
"""
def get_sheet_msg(name, sheet):
if sheet is not None:
langs = sorted(sheet.keys())
if 0 < len(langs):
lang_msgs = []
for lang in langs:
cols = sheet[lang]
if isinstance(cols, str):
msg = f"Expected a sequence of columns, got a string for {lang}."
<|code_end|>
with the help of current file imports:
from collections import defaultdict
from typing import TYPE_CHECKING
from pyxform import aliases, constants
from pyxform.errors import PyXFormError
from typing import Dict, List, Optional, Sequence, Union
and context from other files:
# Path: pyxform/aliases.py
# TRANSLATABLE_SURVEY_COLUMNS = {
# constants.LABEL: constants.LABEL,
# # Per ODK Spec, could include "short" once pyxform supports it.
# constants.HINT: constants.HINT,
# "guidance_hint": "guidance_hint",
# "image": survey_header["image"],
# # Per ODK Spec, could include "big-image" once pyxform supports it.
# "audio": survey_header["audio"],
# "video": survey_header["video"],
# "jr:constraintMsg": "constraint_message",
# "jr:requiredMsg": "required_message",
# }
# TRANSLATABLE_CHOICES_COLUMNS = {
# "label": constants.LABEL,
# "image": "media::image",
# "audio": "media::audio",
# "video": "media::video",
# }
#
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
, which may contain function names, class names, or code. Output only the next line. | PyXFormError(msg) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
XForm survey question type mapping dictionary module.
"""
def generate_new_dict():
"""
This is just here incase there is ever any need to generate the question
type dictionary from all.xls again.
It shouldn't be called as part of any application.
"""
path_to_question_types = "/pyxform/question_types/all.xls"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyxform.xls2json import QuestionTypesReader, print_pyobj_to_json
and context:
# Path: pyxform/xls2json.py
# class QuestionTypesReader(SpreadsheetReader):
# """
# Class for reading spreadsheet file that specifies the available
# question types.
# @see question_type_dictionary
# """
#
# def __init__(self, path):
# super(QuestionTypesReader, self).__init__(path)
# self._setup_question_types_dictionary()
#
# def _setup_question_types_dictionary(self):
# use_double_colons = has_double_colon(self._dict)
# types_sheet = "question types"
# self._dict = self._dict[types_sheet]
# self._dict = dealias_and_group_headers(
# dict_array=self._dict,
# header_aliases={},
# use_double_colons=use_double_colons,
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# )
# self._dict = organize_by_values(self._dict, "name")
#
# def print_pyobj_to_json(pyobj, path=None):
# """
# dump a python nested array/dict structure to the specified file
# or stdout if no file is specified
# """
# if path:
# fp = codecs.open(path, mode="w", encoding="utf-8")
# json.dump(pyobj, fp=fp, ensure_ascii=False, indent=4)
# fp.close()
# else:
# sys.stdout.write(json.dumps(pyobj, ensure_ascii=False, indent=4))
which might include code, classes, or functions. Output only the next line. | json_dict = QuestionTypesReader(path_to_question_types).to_json_dict() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
XForm survey question type mapping dictionary module.
"""
def generate_new_dict():
"""
This is just here incase there is ever any need to generate the question
type dictionary from all.xls again.
It shouldn't be called as part of any application.
"""
path_to_question_types = "/pyxform/question_types/all.xls"
json_dict = QuestionTypesReader(path_to_question_types).to_json_dict()
<|code_end|>
, generate the next line using the imports in this file:
from pyxform.xls2json import QuestionTypesReader, print_pyobj_to_json
and context (functions, classes, or occasionally code) from other files:
# Path: pyxform/xls2json.py
# class QuestionTypesReader(SpreadsheetReader):
# """
# Class for reading spreadsheet file that specifies the available
# question types.
# @see question_type_dictionary
# """
#
# def __init__(self, path):
# super(QuestionTypesReader, self).__init__(path)
# self._setup_question_types_dictionary()
#
# def _setup_question_types_dictionary(self):
# use_double_colons = has_double_colon(self._dict)
# types_sheet = "question types"
# self._dict = self._dict[types_sheet]
# self._dict = dealias_and_group_headers(
# dict_array=self._dict,
# header_aliases={},
# use_double_colons=use_double_colons,
# default_language=constants.DEFAULT_LANGUAGE_VALUE,
# )
# self._dict = organize_by_values(self._dict, "name")
#
# def print_pyobj_to_json(pyobj, path=None):
# """
# dump a python nested array/dict structure to the specified file
# or stdout if no file is specified
# """
# if path:
# fp = codecs.open(path, mode="w", encoding="utf-8")
# json.dump(pyobj, fp=fp, ensure_ascii=False, indent=4)
# fp.close()
# else:
# sys.stdout.write(json.dumps(pyobj, ensure_ascii=False, indent=4))
. Output only the next line. | print_pyobj_to_json(json_dict, "new_question_type_dict.json") |
Next line prediction: <|code_start|> "label": {"English": "What's your father's phone number?"},
},
{
"name": "age",
"type": "integer",
"label": {"English": "How old is your father?"},
},
],
},
{
"children": [
{
"bind": {"jr:preload": "uid", "readonly": "true()"},
"name": "instanceID",
"type": "calculate",
}
],
"control": {"bodyless": True},
"name": "meta",
"type": "group",
},
],
}
self.maxDiff = None
self.assertEqual(x_results, expected_dict)
def test_equality_of_to_dict(self):
x = SurveyReader(utils.path_to_text_fixture("group.xls"), default_name="group")
x_results = x.to_json_dict()
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from pyxform.builder import create_survey_element_from_dict
from pyxform.xls2json import SurveyReader
from tests import utils)
and context including class names, function names, or small code snippets from other files:
# Path: pyxform/builder.py
# def create_survey_element_from_dict(self, d):
# """
# Convert from a nested python dictionary/array structure (a json dict I
# call it because it corresponds directly with a json object)
# to a survey object
# """
# if "add_none_option" in d:
# self._add_none_option = d["add_none_option"]
# if d["type"] in self.SECTION_CLASSES:
# section = self._create_section_from_dict(d)
#
# if d["type"] == "survey":
# section.setvalues_by_triggering_ref = self.setvalues_by_triggering_ref
#
# return section
# elif d["type"] == "loop":
# return self._create_loop_from_dict(d)
# elif d["type"] == "include":
# section_name = d["name"]
# if section_name not in self._sections:
# raise PyXFormError(
# "This section has not been included.",
# section_name,
# self._sections.keys(),
# )
# d = self._sections[section_name]
# full_survey = self.create_survey_element_from_dict(d)
# return full_survey.children
# elif d["type"] in ["xml-external", "csv-external"]:
# return ExternalInstance(**d)
# else:
# self._save_trigger_as_setvalue_and_remove_calculate(d)
#
# return self._create_question_from_dict(
# d, copy_json_dict(QUESTION_TYPE_DICT), self._add_none_option
# )
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | survey = create_survey_element_from_dict(x_results) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Testing simple cases for Xls2Json
"""
class GroupTests(TestCase):
def test_json(self):
<|code_end|>
, determine the next line of code. You have imports:
from unittest import TestCase
from pyxform.builder import create_survey_element_from_dict
from pyxform.xls2json import SurveyReader
from tests import utils
and context (class names, function names, or code) available:
# Path: pyxform/builder.py
# def create_survey_element_from_dict(self, d):
# """
# Convert from a nested python dictionary/array structure (a json dict I
# call it because it corresponds directly with a json object)
# to a survey object
# """
# if "add_none_option" in d:
# self._add_none_option = d["add_none_option"]
# if d["type"] in self.SECTION_CLASSES:
# section = self._create_section_from_dict(d)
#
# if d["type"] == "survey":
# section.setvalues_by_triggering_ref = self.setvalues_by_triggering_ref
#
# return section
# elif d["type"] == "loop":
# return self._create_loop_from_dict(d)
# elif d["type"] == "include":
# section_name = d["name"]
# if section_name not in self._sections:
# raise PyXFormError(
# "This section has not been included.",
# section_name,
# self._sections.keys(),
# )
# d = self._sections[section_name]
# full_survey = self.create_survey_element_from_dict(d)
# return full_survey.children
# elif d["type"] in ["xml-external", "csv-external"]:
# return ExternalInstance(**d)
# else:
# self._save_trigger_as_setvalue_and_remove_calculate(d)
#
# return self._create_question_from_dict(
# d, copy_json_dict(QUESTION_TYPE_DICT), self._add_none_option
# )
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | x = SurveyReader(utils.path_to_text_fixture("group.xls"), default_name="group") |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Testing simple cases for Xls2Json
"""
class GroupTests(TestCase):
def test_json(self):
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_element_from_dict
from pyxform.xls2json import SurveyReader
from tests import utils
and context (classes, functions, or code) from other files:
# Path: pyxform/builder.py
# def create_survey_element_from_dict(self, d):
# """
# Convert from a nested python dictionary/array structure (a json dict I
# call it because it corresponds directly with a json object)
# to a survey object
# """
# if "add_none_option" in d:
# self._add_none_option = d["add_none_option"]
# if d["type"] in self.SECTION_CLASSES:
# section = self._create_section_from_dict(d)
#
# if d["type"] == "survey":
# section.setvalues_by_triggering_ref = self.setvalues_by_triggering_ref
#
# return section
# elif d["type"] == "loop":
# return self._create_loop_from_dict(d)
# elif d["type"] == "include":
# section_name = d["name"]
# if section_name not in self._sections:
# raise PyXFormError(
# "This section has not been included.",
# section_name,
# self._sections.keys(),
# )
# d = self._sections[section_name]
# full_survey = self.create_survey_element_from_dict(d)
# return full_survey.children
# elif d["type"] in ["xml-external", "csv-external"]:
# return ExternalInstance(**d)
# else:
# self._save_trigger_as_setvalue_and_remove_calculate(d)
#
# return self._create_question_from_dict(
# d, copy_json_dict(QUESTION_TYPE_DICT), self._add_none_option
# )
#
# Path: pyxform/xls2json.py
# class SurveyReader(SpreadsheetReader):
# """
# SurveyReader is a wrapper for the parse_file_to_json function.
# It allows us to use the old interface where a SpreadsheetReader
# based object is created then a to_json_dict function is called on it.
# """
#
# def __init__(self, path_or_file, default_name=None):
# if isinstance(path_or_file, str):
# self._file_object = None
# path = path_or_file
# else:
# self._file_object = path_or_file
# path = path_or_file.name
#
# self._warnings = []
# self._dict = parse_file_to_json(
# path,
# default_name=default_name,
# warnings=self._warnings,
# file_object=self._file_object,
# )
# self._path = path
#
# def print_warning_log(self, warn_out_file):
# # Open file to print warning log to.
# warn_out = open(warn_out_file, "w")
# warn_out.write("\n".join(self._warnings))
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | x = SurveyReader(utils.path_to_text_fixture("group.xls"), default_name="group") |
Using the snippet: <|code_start|> writer = csv.writer(f, quoting=csv.QUOTE_ALL)
mask = [v and len(v.strip()) > 0 for v in sheet.row_values(0)]
for row_idx in range(sheet.nrows):
csv_data = []
try:
for v, m in zip(sheet.row(row_idx), mask):
if m:
value = v.value
value_type = v.ctype
data = xls_value_to_unicode(value, value_type, wb.datemode)
# clean the values of leading and trailing whitespaces
data = data.strip()
csv_data.append(data)
except TypeError:
continue
writer.writerow(csv_data)
return True
def xlsx_sheet_to_csv(workbook_path, csv_path, sheet_name):
wb = openpyxl.open(workbook_path)
try:
sheet = wb.get_sheet_by_name(sheet_name)
except KeyError:
return False
if sheet.max_row < 2:
return False
with open(csv_path, "w", newline="") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
<|code_end|>
, determine the next line of code. You have imports:
import codecs
import copy
import csv
import json
import os
import re
import openpyxl
import xlrd
from json.decoder import JSONDecodeError
from xml.dom.minidom import Element, Text, parseString
from pyxform.xls2json_backends import is_empty, xls_value_to_unicode, xlsx_value_to_str
and context (class names, function names, or code) available:
# Path: pyxform/xls2json_backends.py
# def is_empty(value):
# if value is None:
# return True
# elif isinstance(value, str) and value.strip() == "":
# return True
# else:
# return False
#
# def xls_value_to_unicode(value, value_type, datemode):
# """
# Take a xls formatted value and try to make a unicode string
# representation.
# """
# if value_type == xlrd.XL_CELL_BOOLEAN:
# return "TRUE" if value else "FALSE"
# elif value_type == xlrd.XL_CELL_NUMBER:
# # Try to display as an int if possible.
# int_value = int(value)
# if int_value == value:
# return str(int_value)
# else:
# return str(value)
# elif value_type is xlrd.XL_CELL_DATE:
# # Warn that it is better to single quote as a string.
# # error_location = cellFormatString % (ss_row_idx, ss_col_idx)
# # raise Exception(
# # "Cannot handle excel formatted date at " + error_location)
# datetime_or_time_only = xlrd.xldate_as_tuple(value, datemode)
# if datetime_or_time_only[:3] == (0, 0, 0):
# # must be time only
# return str(datetime.time(*datetime_or_time_only[3:]))
# return str(datetime.datetime(*datetime_or_time_only))
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
#
# def xlsx_value_to_str(value):
# """
# Take a xls formatted value and try to make a string representation.
# """
# if value is True:
# return "TRUE"
# elif value is False:
# return "FALSE"
# elif isinstance(value, float) and value.is_integer():
# # Try to display as an int if possible.
# return str(int(value))
# elif isinstance(value, (int, datetime.datetime, datetime.time)):
# return str(value)
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
. Output only the next line. | mask = [not is_empty(cell.value) for cell in sheet[1]] |
Given the code snippet: <|code_start|> for subli in li:
for it in subli:
yield it
def sheet_to_csv(workbook_path, csv_path, sheet_name):
if workbook_path.endswith(".xls"):
return xls_sheet_to_csv(workbook_path, csv_path, sheet_name)
else:
return xlsx_sheet_to_csv(workbook_path, csv_path, sheet_name)
def xls_sheet_to_csv(workbook_path, csv_path, sheet_name):
wb = xlrd.open_workbook(workbook_path)
try:
sheet = wb.sheet_by_name(sheet_name)
except xlrd.biffh.XLRDError:
return False
if not sheet or sheet.nrows < 2:
return False
with open(csv_path, "w", newline="") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
mask = [v and len(v.strip()) > 0 for v in sheet.row_values(0)]
for row_idx in range(sheet.nrows):
csv_data = []
try:
for v, m in zip(sheet.row(row_idx), mask):
if m:
value = v.value
value_type = v.ctype
<|code_end|>
, generate the next line using the imports in this file:
import codecs
import copy
import csv
import json
import os
import re
import openpyxl
import xlrd
from json.decoder import JSONDecodeError
from xml.dom.minidom import Element, Text, parseString
from pyxform.xls2json_backends import is_empty, xls_value_to_unicode, xlsx_value_to_str
and context (functions, classes, or occasionally code) from other files:
# Path: pyxform/xls2json_backends.py
# def is_empty(value):
# if value is None:
# return True
# elif isinstance(value, str) and value.strip() == "":
# return True
# else:
# return False
#
# def xls_value_to_unicode(value, value_type, datemode):
# """
# Take a xls formatted value and try to make a unicode string
# representation.
# """
# if value_type == xlrd.XL_CELL_BOOLEAN:
# return "TRUE" if value else "FALSE"
# elif value_type == xlrd.XL_CELL_NUMBER:
# # Try to display as an int if possible.
# int_value = int(value)
# if int_value == value:
# return str(int_value)
# else:
# return str(value)
# elif value_type is xlrd.XL_CELL_DATE:
# # Warn that it is better to single quote as a string.
# # error_location = cellFormatString % (ss_row_idx, ss_col_idx)
# # raise Exception(
# # "Cannot handle excel formatted date at " + error_location)
# datetime_or_time_only = xlrd.xldate_as_tuple(value, datemode)
# if datetime_or_time_only[:3] == (0, 0, 0):
# # must be time only
# return str(datetime.time(*datetime_or_time_only[3:]))
# return str(datetime.datetime(*datetime_or_time_only))
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
#
# def xlsx_value_to_str(value):
# """
# Take a xls formatted value and try to make a string representation.
# """
# if value is True:
# return "TRUE"
# elif value is False:
# return "FALSE"
# elif isinstance(value, float) and value.is_integer():
# # Try to display as an int if possible.
# return str(int(value))
# elif isinstance(value, (int, datetime.datetime, datetime.time)):
# return str(value)
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
. Output only the next line. | data = xls_value_to_unicode(value, value_type, wb.datemode) |
Predict the next line after this snippet: <|code_start|> if m:
value = v.value
value_type = v.ctype
data = xls_value_to_unicode(value, value_type, wb.datemode)
# clean the values of leading and trailing whitespaces
data = data.strip()
csv_data.append(data)
except TypeError:
continue
writer.writerow(csv_data)
return True
def xlsx_sheet_to_csv(workbook_path, csv_path, sheet_name):
wb = openpyxl.open(workbook_path)
try:
sheet = wb.get_sheet_by_name(sheet_name)
except KeyError:
return False
if sheet.max_row < 2:
return False
with open(csv_path, "w", newline="") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
mask = [not is_empty(cell.value) for cell in sheet[1]]
for row in sheet.rows:
csv_data = []
try:
for v, m in zip(row, mask):
if m:
<|code_end|>
using the current file's imports:
import codecs
import copy
import csv
import json
import os
import re
import openpyxl
import xlrd
from json.decoder import JSONDecodeError
from xml.dom.minidom import Element, Text, parseString
from pyxform.xls2json_backends import is_empty, xls_value_to_unicode, xlsx_value_to_str
and any relevant context from other files:
# Path: pyxform/xls2json_backends.py
# def is_empty(value):
# if value is None:
# return True
# elif isinstance(value, str) and value.strip() == "":
# return True
# else:
# return False
#
# def xls_value_to_unicode(value, value_type, datemode):
# """
# Take a xls formatted value and try to make a unicode string
# representation.
# """
# if value_type == xlrd.XL_CELL_BOOLEAN:
# return "TRUE" if value else "FALSE"
# elif value_type == xlrd.XL_CELL_NUMBER:
# # Try to display as an int if possible.
# int_value = int(value)
# if int_value == value:
# return str(int_value)
# else:
# return str(value)
# elif value_type is xlrd.XL_CELL_DATE:
# # Warn that it is better to single quote as a string.
# # error_location = cellFormatString % (ss_row_idx, ss_col_idx)
# # raise Exception(
# # "Cannot handle excel formatted date at " + error_location)
# datetime_or_time_only = xlrd.xldate_as_tuple(value, datemode)
# if datetime_or_time_only[:3] == (0, 0, 0):
# # must be time only
# return str(datetime.time(*datetime_or_time_only[3:]))
# return str(datetime.datetime(*datetime_or_time_only))
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
#
# def xlsx_value_to_str(value):
# """
# Take a xls formatted value and try to make a string representation.
# """
# if value is True:
# return "TRUE"
# elif value is False:
# return "FALSE"
# elif isinstance(value, float) and value.is_integer():
# # Try to display as an int if possible.
# return str(int(value))
# elif isinstance(value, (int, datetime.datetime, datetime.time)):
# return str(value)
# else:
# # ensure unicode and replace nbsp spaces with normal ones
# # to avoid this issue:
# # https://github.com/modilabs/pyxform/issues/83
# return str(value).replace(chr(160), " ")
. Output only the next line. | data = xlsx_value_to_str(v.value) |
Continue the code snippet: <|code_start|>
def decode_stream(stream):
"""
Decode a stream, e.g. stdout or stderr.
On Windows, stderr may be latin-1; in which case utf-8 decode will fail.
If both utf-8 and latin-1 decoding fail then raise all as IOError.
If the above validate jar call fails, add make sure that the java path
is set, e.g. PATH=C:\\Program Files (x86)\\Java\\jre1.8.0_71\\bin
"""
try:
return stream.decode("utf-8")
except UnicodeDecodeError as ude:
try:
return stream.decode("latin-1")
except BaseException as be:
msg = "Failed to decode validate stderr as utf-8 or latin-1."
raise IOError(msg, ude, be)
def request_get(url):
"""
Get the response content from URL.
"""
try:
r = Request(url)
r.add_header("Accept", "application/json")
with closing(urlopen(r)) as u:
content = u.read()
if len(content) == 0:
<|code_end|>
. Use current file imports:
import collections
import io
import logging
import os
import signal
import subprocess
import tempfile
import threading
import time
from contextlib import closing
from subprocess import PIPE, Popen
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from pyxform.errors import PyXFormError
and context (classes, functions, or code) from other files:
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
. Output only the next line. | raise PyXFormError("Empty response from URL: '{u}'.".format(u=url)) |
Continue the code snippet: <|code_start|>Test xls2xform module.
"""
# The Django application xls2xform uses the function
# pyxform.create_survey. We have a test here to make sure no one
# breaks that function.
try:
except ImportError:
class XLS2XFormTests(TestCase):
survey_package = {
"id_string": "test_2011_08_29b",
"name_of_main_section": "gps",
"sections": {
"gps": {
"children": [{"name": "location", "type": "gps"}],
"name": "gps",
"type": "survey",
}
},
"title": "test",
}
survey = pyxform.create_survey(**survey_package)
def test_create_parser_without_args(self):
"""Should exit when no args provided."""
with self.assertRaises(SystemExit):
<|code_end|>
. Use current file imports:
import argparse
import logging
import pyxform
import mock
from unittest import TestCase
from pyxform.xls2xform import (
_create_parser,
_validator_args_logic,
get_xml_path,
main_cli,
)
from tests.utils import path_to_text_fixture
from unittest import mock
and context (classes, functions, or code) from other files:
# Path: pyxform/xls2xform.py
# def _create_parser():
# """
# Parse command line arguments.
# """
# parser = argparse.ArgumentParser()
# parser.add_argument(
# "path_to_XLSForm",
# help="Path to the Excel XLSX file with the XLSForm definition.",
# )
# parser.add_argument("output_path", help="Path to save the output to.", nargs="?")
# parser.add_argument(
# "--json",
# action="store_true",
# help="Capture everything and report in JSON format.",
# )
# parser.add_argument(
# "--skip_validate",
# action="store_false",
# default=True,
# help="Do not run any external validators on the output XForm XML. "
# "Without this flag, ODK Validate is run by default for backwards "
# "compatibility. Internal pyxform checks cannot be skipped.",
# )
# parser.add_argument(
# "--odk_validate",
# action="store_true",
# default=False,
# help="Run the ODK Validate XForm external validator.",
# )
# parser.add_argument(
# "--enketo_validate",
# action="store_true",
# default=False,
# help="Run the Enketo Validate XForm external validator.",
# )
# parser.add_argument(
# "--pretty_print",
# action="store_true",
# default=False,
# help="Print XML forms with collapsed whitespace instead of pretty-printed.",
# )
# return parser
#
# def _validator_args_logic(args):
# """
# Implements logic for how validator arguments work in combination.
#
# As per: https://github.com/XLSForm/pyxform/pull/167#issuecomment-353382008
#
# **backwards-compatible**
# `xls2xform.py myform --skip_validate`: no validators
# `xls2xform.py myform`: ODK only
#
# **new**
# `xls2xform.py myform --enketo_validate`: Enketo only
# `xls2xform.py myform --odk_validate`: ODK only
# `xls2xform.py myform --enketo_validate --odk_validate`: both
# `xls2xform.py myform --enketo_validate --odk_validate --skip_validate`: no validators
# """
# if not args.skip_validate:
# args.odk_validate = False
# args.enketo_validate = False
# elif args.skip_validate and not (args.odk_validate or args.enketo_validate):
# args.odk_validate = True
# args.enketo_validate = False
# return args
#
# def get_xml_path(path):
# """
# Returns the xform file path
#
# Generates an output path for the xform file from the given
# xlsx input file path.
# """
# return splitext(path)[0] + ".xml"
#
# def main_cli():
# parser = _create_parser()
# raw_args = parser.parse_args()
# args = _validator_args_logic(args=raw_args)
#
# # auto generate an output path if one was not given
# if args.output_path is None:
# args.output_path = get_xml_path(args.path_to_XLSForm)
#
# if args.json:
# # Store everything in a list just in case the user wants to output
# # as a JSON encoded string.
# response = {"code": None, "message": None, "warnings": []}
#
# try:
# response["warnings"] = xls2xform_convert(
# xlsform_path=args.path_to_XLSForm,
# xform_path=args.output_path,
# validate=args.odk_validate,
# pretty_print=args.pretty_print,
# enketo=args.enketo_validate,
# )
#
# response["code"] = 100
# response["message"] = "Ok!"
#
# if response["warnings"]:
# response["code"] = 101
# response["message"] = "Ok with warnings."
#
# except Exception as e:
# # Catch the exception by default.
# response["code"] = 999
# response["message"] = str(e)
#
# logger.info(json.dumps(response))
# else:
# try:
# warnings = xls2xform_convert(
# xlsform_path=args.path_to_XLSForm,
# xform_path=args.output_path,
# validate=args.odk_validate,
# pretty_print=args.pretty_print,
# enketo=args.enketo_validate,
# )
# except EnvironmentError as e:
# # Do not crash if 'java' not installed
# logger.error(e)
# except ODKValidateError as e:
# # Remove output file if there is an error
# os.remove(args.output_path)
# logger.error(e)
# else:
# if len(warnings) > 0:
# logger.warning("Warnings:")
# for w in warnings:
# logger.warning(w)
# logger.info("Conversion complete!")
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# return os.path.join(example_xls.PATH, filename)
. Output only the next line. | _create_parser().parse_args([]) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test tutorial XLSForm.
"""
class TutorialTests(TestCase):
def test_create_from_path(self):
path = utils.path_to_text_fixture("tutorial.xls")
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from tests import utils
and context (classes, functions, or code) from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | create_survey_from_path(path) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test tutorial XLSForm.
"""
class TutorialTests(TestCase):
def test_create_from_path(self):
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from tests import utils
and context from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
, which may contain function names, class names, or code. Output only the next line. | path = utils.path_to_text_fixture("tutorial.xls") |
Predict the next line for this snippet: <|code_start|> try:
row_dict[key] = xls_value_to_unicode(
value, value_type, workbook.datemode
)
except XLDateAmbiguous:
raise PyXFormError(
XL_DATE_AMBIGOUS_MSG % (sheet.name, column_header, row)
)
# Taking this condition out so I can get accurate row numbers.
# TODO: Do the same for csvs
# if row_dict != {}:
result.append(row_dict)
return result, _list_to_dict_list(column_header_list)
def xls_value_from_sheet(sheet, row, column):
value = sheet.cell_value(row, column)
value_type = sheet.cell_type(row, column)
if value is not None and value != "":
try:
return xls_value_to_unicode(value, value_type, workbook.datemode)
except XLDateAmbiguous:
raise PyXFormError(XL_DATE_AMBIGOUS_MSG % (sheet.name, column, row))
else:
raise PyXFormError("Empty Value")
result = OrderedDict()
for sheet in workbook.sheets():
# Note that the sheet exists but do no further processing here.
result[sheet.name] = []
# Do not process sheets that have nothing to do with XLSForm.
<|code_end|>
with the help of current file imports:
import csv
import datetime
import re
import openpyxl
import xlrd
from collections import OrderedDict
from functools import reduce
from io import StringIO
from zipfile import BadZipFile
from xlrd import XLRDError
from xlrd.xldate import XLDateAmbiguous
from pyxform import constants
from pyxform.errors import PyXFormError
and context from other files:
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
, which may contain function names, class names, or code. Output only the next line. | if sheet.name not in constants.SUPPORTED_SHEET_NAMES: |
Predict the next line after this snippet: <|code_start|>
def _list_to_dict_list(list_items):
"""
Takes a list and creates a dict with the list values as keys.
Returns a list of the created dict or an empty list
"""
if list_items:
k = OrderedDict()
for item in list_items:
k["%s" % item] = ""
return [k]
return []
def xls_to_dict(path_or_file):
"""
Return a Python dictionary with a key for each worksheet
name. For each sheet there is a list of dictionaries, each
dictionary corresponds to a single row in the worksheet. A
dictionary has keys taken from the column headers and values
equal to the cell value for that row and column.
All the keys and leaf elements are unicode text.
"""
try:
if isinstance(path_or_file, str):
workbook = xlrd.open_workbook(filename=path_or_file)
else:
workbook = xlrd.open_workbook(file_contents=path_or_file.read())
except XLRDError as error:
<|code_end|>
using the current file's imports:
import csv
import datetime
import re
import openpyxl
import xlrd
from collections import OrderedDict
from functools import reduce
from io import StringIO
from zipfile import BadZipFile
from xlrd import XLRDError
from xlrd.xldate import XLDateAmbiguous
from pyxform import constants
from pyxform.errors import PyXFormError
and any relevant context from other files:
# Path: pyxform/constants.py
# TYPE = "type"
# TITLE = "title"
# NAME = "name"
# ID_STRING = "id_string"
# SMS_KEYWORD = "sms_keyword"
# SMS_FIELD = "sms_field"
# SMS_OPTION = "sms_option"
# SMS_SEPARATOR = "sms_separator"
# SMS_ALLOW_MEDIA = "sms_allow_media"
# SMS_DATE_FORMAT = "sms_date_format"
# SMS_DATETIME_FORMAT = "sms_datetime_format"
# SMS_RESPONSE = "sms_response"
# COMPACT_PREFIX = "prefix"
# COMPACT_DELIMITER = "delimiter"
# COMPACT_TAG = "compact_tag"
# VERSION = "version"
# PUBLIC_KEY = "public_key"
# SUBMISSION_URL = "submission_url"
# AUTO_SEND = "auto_send"
# AUTO_DELETE = "auto_delete"
# DEFAULT_LANGUAGE_KEY = "default_language"
# DEFAULT_LANGUAGE_VALUE = "default"
# LABEL = "label"
# HINT = "hint"
# STYLE = "style"
# ATTRIBUTE = "attribute"
# ALLOW_CHOICE_DUPLICATES = "allow_choice_duplicates"
# BIND = (
# "bind" # TODO: What should I do with the nested types? (readonly and relevant) # noqa
# )
# MEDIA = "media"
# CONTROL = "control"
# APPEARANCE = "appearance"
# LOOP = "loop"
# COLUMNS = "columns"
# REPEAT = "repeat"
# GROUP = "group"
# CHILDREN = "children"
# SELECT_ONE = "select one"
# SELECT_ALL_THAT_APPLY = "select all that apply"
# RANK = "rank"
# CHOICES = "choices"
# LIST_NAME = "list name"
# CASCADING_SELECT = "cascading_select"
# TABLE_LIST = "table-list" # hyphenated because it goes in appearance, and convention for appearance column is dashes # noqa
# FIELD_LIST = "field-list"
# SURVEY = "survey"
# SETTINGS = "settings"
# EXTERNAL_CHOICES = "external_choices"
# OSM = "osm"
# OSM_TYPE = "binary"
# NAMESPACES = "namespaces"
# SUPPORTED_SHEET_NAMES = [
# SURVEY,
# CHOICES,
# SETTINGS,
# EXTERNAL_CHOICES,
# OSM,
# ]
# XLS_EXTENSIONS = [".xls"]
# XLSX_EXTENSIONS = [".xlsx", ".xlsm"]
# SUPPORTED_FILE_EXTENSIONS = XLS_EXTENSIONS + XLSX_EXTENSIONS
# LOCATION_PRIORITY = "location-priority"
# LOCATION_MIN_INTERVAL = "location-min-interval"
# LOCATION_MAX_AGE = "location-max-age"
# TRACK_CHANGES = "track-changes"
# IDENTIFY_USER = "identify-user"
# TRACK_CHANGES_REASONS = "track-changes-reasons"
# EXTERNAL_INSTANCES = ["calculate", "constraint", "readonly", "required", "relevant"]
# CURRENT_XFORMS_VERSION = "1.0.0"
# DEPRECATED_DEVICE_ID_METADATA_FIELDS = ["subscriberid", "simserial"]
# AUDIO_QUALITY_VOICE_ONLY = "voice-only"
# AUDIO_QUALITY_LOW = "low"
# AUDIO_QUALITY_NORMAL = "normal"
# AUDIO_QUALITY_EXTERNAL = "external"
# EXTERNAL_CHOICES_ITEMSET_REF_LABEL = "label"
# EXTERNAL_CHOICES_ITEMSET_REF_VALUE = "name"
# ROW_FORMAT_STRING: str = "[row : %s]"
#
# Path: pyxform/errors.py
# class PyXFormError(Exception):
# """Common base class for pyxform exceptions."""
#
# pass
. Output only the next line. | raise PyXFormError("Error reading .xls file: %s" % error) |
Here is a snippet: <|code_start|> return {"node_name": self._name, "id": self._id, "children": children}
def to_xml(self):
"""
A horrible way to do this, but it works (until we need the attributes
pumped out in order, etc)
"""
open_str = """<?xml version='1.0' ?><%s id="%s">""" % (self._name, self._id)
close_str = """</%s>""" % self._name
vals = ""
for k, v in self._answers.items():
vals += "<%s>%s</%s>" % (k, str(v), k)
output = open_str + vals + close_str
return output
def answers(self):
"""
This returns "_answers", which is a dict with the key-value
responses for this given instance. This could be pumped to xml
or returned as a dict for maximum convenience (i.e. testing.)
"""
return self._answers
def import_from_xml(self, xml_string_or_filename):
if os.path.isfile(xml_string_or_filename):
xml_str = open(xml_string_or_filename).read()
else:
xml_str = xml_string_or_filename
<|code_end|>
. Write the next line using the current file imports:
from pyxform.xform_instance_parser import parse_xform_instance
import os.path
and context from other files:
# Path: pyxform/xform_instance_parser.py
# def parse_xform_instance(xml_str):
# parser = XFormInstanceParser(xml_str)
# return parser.get_flat_dict_with_attributes()
, which may include functions, classes, or code. Output only the next line. | key_val_dict = parse_xform_instance(xml_str) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test multiple XLSForm can be generated successfully.
"""
class DumpAndLoadTests(TestCase):
def setUp(self):
self.excel_files = [
"gps.xls",
# "include.xls",
"specify_other.xls",
"group.xls",
"loop.xls",
"text_and_integer.xls",
# todo: this is looking for json that is created (and
# deleted) by another test, is should just add that json
# to the directory.
# "include_json.xls",
"simple_loop.xls",
"yes_or_no_question.xls",
]
self.surveys = {}
self.this_directory = os.path.dirname(__file__)
for filename in self.excel_files:
path = utils.path_to_text_fixture(filename)
<|code_end|>
. Use current file imports:
import os
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from tests import utils
and context (classes, functions, or code) from other files:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
. Output only the next line. | self.surveys[filename] = create_survey_from_path(path) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Test multiple XLSForm can be generated successfully.
"""
class DumpAndLoadTests(TestCase):
def setUp(self):
self.excel_files = [
"gps.xls",
# "include.xls",
"specify_other.xls",
"group.xls",
"loop.xls",
"text_and_integer.xls",
# todo: this is looking for json that is created (and
# deleted) by another test, is should just add that json
# to the directory.
# "include_json.xls",
"simple_loop.xls",
"yes_or_no_question.xls",
]
self.surveys = {}
self.this_directory = os.path.dirname(__file__)
for filename in self.excel_files:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from unittest import TestCase
from pyxform.builder import create_survey_from_path
from tests import utils
and context:
# Path: pyxform/builder.py
# def create_survey_from_path(path, include_directory=False):
# """
# include_directory -- Switch to indicate that all the survey forms in the
# same directory as the specified file should be read
# so they can be included through include types.
# @see: create_survey
# """
# directory, file_name = os.path.split(path)
# if include_directory:
# main_section_name = file_utils._section_name(file_name)
# sections = file_utils.collect_compatible_files_in_directory(directory)
# else:
# main_section_name, section = file_utils.load_file_to_dict(path)
# sections = {main_section_name: section}
# pkg = {"name_of_main_section": main_section_name, "sections": sections}
#
# return create_survey(**pkg)
#
# Path: tests/utils.py
# def path_to_text_fixture(filename):
# def build_survey(filename):
# def create_survey_from_fixture(fixture_name, filetype="xls", include_directory=False):
# def prep_class_config(cls, test_dir="tests"):
# def prep_for_xml_contains(text: str) -> "Tuple[str]":
# def get_temp_file():
# def get_temp_dir():
which might include code, classes, or functions. Output only the next line. | path = utils.path_to_text_fixture(filename) |
Based on the snippet: <|code_start|>################################################################################
#
# This program is part of the HPMon Zenpack for Zenoss.
# Copyright (C) 2008-2012 Egor Puzanov.
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
################################################################################
__doc__="""info.py
Representation of Data Source.
$Id: info.py,v 1.2 2012/10/27 18:02:46 egor Exp $"""
__version__ = "$Revision: 1.2 $"[11:-2]
class cpqIdeControllerInfo(ComponentInfo):
<|code_end|>
, predict the immediate next line with the help of imports:
from zope.interface import implements
from Products.Zuul.infos import ProxyProperty
from Products.Zuul.infos.component import ComponentInfo
from Products.Zuul.decorators import info
from ZenPacks.community.HPMon import interfaces
and context (classes, functions, sometimes code) from other files:
# Path: ZenPacks/community/HPMon/interfaces.py
# class IcpqIdeControllerInfo(IComponentInfo):
# class IcpqScsiCntlrInfo(IcpqIdeControllerInfo):
# class IcpqDaCntlrInfo(IcpqIdeControllerInfo):
# class IcpqFcTapeCntlrInfo(IcpqIdeControllerInfo):
# class IcpqFcaCntlrInfo(IcpqIdeControllerInfo):
# class IcpqFcaHostCntlrInfo(IcpqIdeControllerInfo):
# class IcpqNicIfPhysAdapterInfo(IComponentInfo):
# class IcpqSm2CntlrInfo(IComponentInfo):
. Output only the next line. | implements(interfaces.IcpqIdeControllerInfo) |
Here is a snippet: <|code_start|># For python3
def _equals_bytes(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
def _equals_str(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
def equals(a, b):
if isinstance(a, str):
return _equals_str(a, b)
else:
return _equals_bytes(a, b)
def hmac_sha256(k, m):
"""
Compute the key and the message with HMAC SHA5256
"""
<|code_end|>
. Write the next line using the current file imports:
from .openssl import OpenSSL
and context from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
, which may include functions, classes, or code. Output only the next line. | key = OpenSSL.malloc(k, len(k)) |
Continue the code snippet: <|code_start|>"""
Utility functions for tests.
"""
def mknode(id=None, ip=None, port=None, intid=None):
"""
Make a node. Created a random id if not specified.
"""
if intid is not None:
id = pack('>l', intid)
id = id or hashlib.sha1(str(random.getrandbits(255))).digest()
<|code_end|>
. Use current file imports:
import random
import hashlib
from struct import pack
from subspace.node import Node
from subspace.routing import RoutingTable
and context (classes, functions, or code) from other files:
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# Path: subspace/routing.py
# class RoutingTable(object):
# def __init__(self, protocol, ksize, node):
# """
# @param node: The node that represents this server. It won't
# be added to the routing table, but will be needed later to
# determine which buckets to split or not.
# """
# self.node = node
# self.protocol = protocol
# self.ksize = ksize
# self.flush()
#
# def flush(self):
# self.buckets = [KBucket(0, 2 ** 256, self.ksize)]
#
# def splitBucket(self, index):
# one, two = self.buckets[index].split()
# self.buckets[index] = one
# self.buckets.insert(index + 1, two)
#
# def getLonelyBuckets(self):
# """
# Get all of the buckets that haven't been updated in over
# an hour.
# """
# return [b for b in self.buckets if b.lastUpdated < (time.time() - 3600)]
#
# def removeContact(self, node):
# index = self.getBucketFor(node)
# self.buckets[index].removeNode(node)
#
# def isNewNode(self, node):
# index = self.getBucketFor(node)
# return self.buckets[index].isNewNode(node)
#
# def addContact(self, node):
# index = self.getBucketFor(node)
# bucket = self.buckets[index]
#
# # this will succeed unless the bucket is full
# if bucket.addNode(node):
# return
#
# # Per section 4.2 of paper, split if the bucket has the node in its range
# # or if the depth is not congruent to 0 mod 5
# if bucket.hasInRange(self.node) or bucket.depth() % 5 != 0:
# self.splitBucket(index)
# self.addContact(node)
# else:
# self.protocol.callPing(bucket.head())
#
# def getBucketFor(self, node):
# """
# Get the index of the bucket that the given node would fall into.
# """
# for index, bucket in enumerate(self.buckets):
# if node.long_id < bucket.range[1]:
# return index
#
# def findNeighbors(self, node, k=None, exclude=None):
# k = k or self.ksize
# nodes = []
# for neighbor in TableTraverser(self, node):
# if neighbor.id != node.id and (exclude is None or not neighbor.sameHomeAs(exclude)):
# heapq.heappush(nodes, (node.distanceTo(neighbor), neighbor))
# if len(nodes) == k:
# break
#
# return map(operator.itemgetter(1), heapq.nsmallest(k, nodes))
. Output only the next line. | return Node(id, ip, port) |
Given the following code snippet before the placeholder: <|code_start|>"""
Utility functions for tests.
"""
def mknode(id=None, ip=None, port=None, intid=None):
"""
Make a node. Created a random id if not specified.
"""
if intid is not None:
id = pack('>l', intid)
id = id or hashlib.sha1(str(random.getrandbits(255))).digest()
return Node(id, ip, port)
class FakeProtocol(object):
def __init__(self, sourceID, ksize=20):
<|code_end|>
, predict the next line using imports from the current file:
import random
import hashlib
from struct import pack
from subspace.node import Node
from subspace.routing import RoutingTable
and context including class names, function names, and sometimes code from other files:
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# Path: subspace/routing.py
# class RoutingTable(object):
# def __init__(self, protocol, ksize, node):
# """
# @param node: The node that represents this server. It won't
# be added to the routing table, but will be needed later to
# determine which buckets to split or not.
# """
# self.node = node
# self.protocol = protocol
# self.ksize = ksize
# self.flush()
#
# def flush(self):
# self.buckets = [KBucket(0, 2 ** 256, self.ksize)]
#
# def splitBucket(self, index):
# one, two = self.buckets[index].split()
# self.buckets[index] = one
# self.buckets.insert(index + 1, two)
#
# def getLonelyBuckets(self):
# """
# Get all of the buckets that haven't been updated in over
# an hour.
# """
# return [b for b in self.buckets if b.lastUpdated < (time.time() - 3600)]
#
# def removeContact(self, node):
# index = self.getBucketFor(node)
# self.buckets[index].removeNode(node)
#
# def isNewNode(self, node):
# index = self.getBucketFor(node)
# return self.buckets[index].isNewNode(node)
#
# def addContact(self, node):
# index = self.getBucketFor(node)
# bucket = self.buckets[index]
#
# # this will succeed unless the bucket is full
# if bucket.addNode(node):
# return
#
# # Per section 4.2 of paper, split if the bucket has the node in its range
# # or if the depth is not congruent to 0 mod 5
# if bucket.hasInRange(self.node) or bucket.depth() % 5 != 0:
# self.splitBucket(index)
# self.addContact(node)
# else:
# self.protocol.callPing(bucket.head())
#
# def getBucketFor(self, node):
# """
# Get the index of the bucket that the given node would fall into.
# """
# for index, bucket in enumerate(self.buckets):
# if node.long_id < bucket.range[1]:
# return index
#
# def findNeighbors(self, node, k=None, exclude=None):
# k = k or self.ksize
# nodes = []
# for neighbor in TableTraverser(self, node):
# if neighbor.id != node.id and (exclude is None or not neighbor.sameHomeAs(exclude)):
# heapq.heappush(nodes, (node.distanceTo(neighbor), neighbor))
# if len(nodes) == k:
# break
#
# return map(operator.itemgetter(1), heapq.nsmallest(k, nodes))
. Output only the next line. | self.router = RoutingTable(self, ksize, Node(sourceID)) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
class Cipher:
"""
Symmetric encryption
import pyelliptic
iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
ciphertext = ctx.update('test1')
ciphertext += ctx.update('test2')
ciphertext += ctx.final()
ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
print ctx2.ciphering(ciphertext)
"""
def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
"""
do == 1 => Encrypt; do == 0 => Decrypt
"""
<|code_end|>
, generate the next line using the imports in this file:
from .openssl import OpenSSL
and context (functions, classes, or occasionally code) from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
. Output only the next line. | self.cipher = OpenSSL.get_cipher(ciphername) |
Predict the next line for this snippet: <|code_start|> self.nearest.push(peers)
def _find(self, rpcmethod):
"""
Get either a value or list of nodes.
Args:
rpcmethod: The protocol's callfindValue or callFindNode.
The process:
1. calls find_* to current ALPHA nearest not already queried nodes,
adding results to current nearest list of k nodes.
2. current nearest list needs to keep track of who has been queried already
sort by nearest, keep KSIZE
3. if list is same as last time, next call should be to everyone not
yet queried
4. repeat, unless nearest list has all been queried, then ur done
"""
self.log.info("crawling with nearest: %s" % str(tuple(self.nearest)))
count = self.alpha
if self.nearest.getIDs() == self.lastIDsCrawled:
self.log.info("last iteration same as current - checking all in list now")
count = len(self.nearest)
self.lastIDsCrawled = self.nearest.getIDs()
ds = {}
for peer in self.nearest.getUncontacted()[:count]:
ds[peer.id] = rpcmethod(peer, self.node)
self.nearest.markContacted(peer)
<|code_end|>
with the help of current file imports:
from collections import Counter
from subspace.log import Logger
from subspace.utils import deferredDict
from subspace.node import Node, NodeHeap
and context from other files:
# Path: subspace/utils.py
# def deferredDict(d):
# """
# Just like a :class:`defer.DeferredList` but instead accepts and returns a :class:`dict`.
#
# Args:
# d: A :class:`dict` whose values are all :class:`defer.Deferred` objects.
#
# Returns:
# :class:`defer.DeferredList` whose callback will be given a dictionary whose
# keys are the same as the parameter :obj:`d` and whose values are the results
# of each individual deferred call.
# """
# if len(d) == 0:
# return defer.succeed({})
#
# def handle(results, names):
# rvalue = {}
# for index in range(len(results)):
# rvalue[names[index]] = results[index][1]
# return rvalue
#
# dl = defer.DeferredList(d.values())
# return dl.addCallback(handle, d.keys())
#
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
, which may contain function names, class names, or code. Output only the next line. | return deferredDict(ds).addCallback(self._nodesFound) |
Next line prediction: <|code_start|>class RPCFindResponse(object):
def __init__(self, response):
"""
A wrapper for the result of a RPC find.
Args:
response: This will be a tuple of (<response received>, <value>)
where <value> will be a list of tuples if not found or
a dictionary of {'value': v} where v is the value desired
"""
self.response = response
def happened(self):
"""
Did the other host actually respond?
"""
return self.response[0]
def hasValue(self):
return isinstance(self.response[1], dict)
def getValue(self):
return self.response[1]['value']
def getNodeList(self):
"""
Get the node list in the response. If there's no value, this should
be set.
"""
nodelist = self.response[1] or []
<|code_end|>
. Use current file imports:
(from collections import Counter
from subspace.log import Logger
from subspace.utils import deferredDict
from subspace.node import Node, NodeHeap)
and context including class names, function names, or small code snippets from other files:
# Path: subspace/utils.py
# def deferredDict(d):
# """
# Just like a :class:`defer.DeferredList` but instead accepts and returns a :class:`dict`.
#
# Args:
# d: A :class:`dict` whose values are all :class:`defer.Deferred` objects.
#
# Returns:
# :class:`defer.DeferredList` whose callback will be given a dictionary whose
# keys are the same as the parameter :obj:`d` and whose values are the results
# of each individual deferred call.
# """
# if len(d) == 0:
# return defer.succeed({})
#
# def handle(results, names):
# rvalue = {}
# for index in range(len(results)):
# rvalue[names[index]] = results[index][1]
# return rvalue
#
# dl = defer.DeferredList(d.values())
# return dl.addCallback(handle, d.keys())
#
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
. Output only the next line. | return [Node(*nodeple) for nodeple in nodelist] |
Predict the next line for this snippet: <|code_start|>
class SpiderCrawl(object):
"""
Crawl the network and look for given 160-bit keys.
"""
def __init__(self, protocol, node, peers, ksize, alpha):
"""
Create a new C{SpiderCrawl}er.
Args:
protocol: A :class:`~kademlia.protocol.KademliaProtocol` instance.
node: A :class:`~kademlia.node.Node` representing the key we're looking for
peers: A list of :class:`~kademlia.node.Node` instances that provide the entry point for the network
ksize: The value for k based on the paper
alpha: The value for alpha based on the paper
"""
self.protocol = protocol
self.ksize = ksize
self.alpha = alpha
self.node = node
<|code_end|>
with the help of current file imports:
from collections import Counter
from subspace.log import Logger
from subspace.utils import deferredDict
from subspace.node import Node, NodeHeap
and context from other files:
# Path: subspace/utils.py
# def deferredDict(d):
# """
# Just like a :class:`defer.DeferredList` but instead accepts and returns a :class:`dict`.
#
# Args:
# d: A :class:`dict` whose values are all :class:`defer.Deferred` objects.
#
# Returns:
# :class:`defer.DeferredList` whose callback will be given a dictionary whose
# keys are the same as the parameter :obj:`d` and whose values are the results
# of each individual deferred call.
# """
# if len(d) == 0:
# return defer.succeed({})
#
# def handle(results, names):
# rvalue = {}
# for index in range(len(results)):
# rvalue[names[index]] = results[index][1]
# return rvalue
#
# dl = defer.DeferredList(d.values())
# return dl.addCallback(handle, d.keys())
#
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
, which may contain function names, class names, or code. Output only the next line. | self.nearest = NodeHeap(self.node, self.ksize) |
Next line prediction: <|code_start|>
class NodeTest(unittest.TestCase):
def test_longID(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
<|code_end|>
. Use current file imports:
(import random
import hashlib
from twisted.trial import unittest
from subspace.node import Node, NodeHeap
from subspace.tests.utils import mknode)
and context including class names, function names, or small code snippets from other files:
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
#
# Path: subspace/tests/utils.py
# def mknode(id=None, ip=None, port=None, intid=None):
# """
# Make a node. Created a random id if not specified.
# """
# if intid is not None:
# id = pack('>l', intid)
# id = id or hashlib.sha1(str(random.getrandbits(255))).digest()
# return Node(id, ip, port)
. Output only the next line. | n = Node(rid) |
Continue the code snippet: <|code_start|>
class NodeTest(unittest.TestCase):
def test_longID(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
n = Node(rid)
self.assertEqual(n.long_id, long(rid.encode('hex'), 16))
def test_distanceCalculation(self):
ridone = hashlib.sha1(str(random.getrandbits(255)))
ridtwo = hashlib.sha1(str(random.getrandbits(255)))
shouldbe = long(ridone.hexdigest(), 16) ^ long(ridtwo.hexdigest(), 16)
none = Node(ridone.digest())
ntwo = Node(ridtwo.digest())
self.assertEqual(none.distanceTo(ntwo), shouldbe)
class NodeHeapTest(unittest.TestCase):
def test_maxSize(self):
<|code_end|>
. Use current file imports:
import random
import hashlib
from twisted.trial import unittest
from subspace.node import Node, NodeHeap
from subspace.tests.utils import mknode
and context (classes, functions, or code) from other files:
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
#
# Path: subspace/tests/utils.py
# def mknode(id=None, ip=None, port=None, intid=None):
# """
# Make a node. Created a random id if not specified.
# """
# if intid is not None:
# id = pack('>l', intid)
# id = id or hashlib.sha1(str(random.getrandbits(255))).digest()
# return Node(id, ip, port)
. Output only the next line. | n = NodeHeap(mknode(intid=0), 3) |
Continue the code snippet: <|code_start|>
class NodeTest(unittest.TestCase):
def test_longID(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
n = Node(rid)
self.assertEqual(n.long_id, long(rid.encode('hex'), 16))
def test_distanceCalculation(self):
ridone = hashlib.sha1(str(random.getrandbits(255)))
ridtwo = hashlib.sha1(str(random.getrandbits(255)))
shouldbe = long(ridone.hexdigest(), 16) ^ long(ridtwo.hexdigest(), 16)
none = Node(ridone.digest())
ntwo = Node(ridtwo.digest())
self.assertEqual(none.distanceTo(ntwo), shouldbe)
class NodeHeapTest(unittest.TestCase):
def test_maxSize(self):
<|code_end|>
. Use current file imports:
import random
import hashlib
from twisted.trial import unittest
from subspace.node import Node, NodeHeap
from subspace.tests.utils import mknode
and context (classes, functions, or code) from other files:
# Path: subspace/node.py
# class Node:
# def __init__(self, id, ip=None, port=None):
# self.id = id
# self.ip = ip
# self.port = port
# self.long_id = long(id.encode('hex'), 16)
#
# def sameHomeAs(self, node):
# return self.ip == node.ip and self.port == node.port
#
# def distanceTo(self, node):
# """
# Get the distance between this node and another.
# """
# return self.long_id ^ node.long_id
#
# def __iter__(self):
# """
# Enables use of Node as a tuple - i.e., tuple(node) works.
# """
# return iter([self.id, self.ip, self.port])
#
# def __repr__(self):
# return repr([self.long_id, self.ip, self.port])
#
# def __str__(self):
# return "%s:%s" % (self.ip, str(self.port))
#
# class NodeHeap(object):
# """
# A heap of nodes ordered by distance to a given node.
# """
# def __init__(self, node, maxsize):
# """
# Constructor.
#
# @param node: The node to measure all distnaces from.
# @param maxsize: The maximum size that this heap can grow to.
# """
# self.node = node
# self.heap = []
# self.contacted = set()
# self.maxsize = maxsize
#
# def remove(self, peerIDs):
# """
# Remove a list of peer ids from this heap. Note that while this
# heap retains a constant visible size (based on the iterator), it's
# actual size may be quite a bit larger than what's exposed. Therefore,
# removal of nodes may not change the visible size as previously added
# nodes suddenly become visible.
# """
# peerIDs = set(peerIDs)
# if len(peerIDs) == 0:
# return
# nheap = []
# for distance, node in self.heap:
# if node.id not in peerIDs:
# heapq.heappush(nheap, (distance, node))
# self.heap = nheap
#
# def getNodeById(self, id):
# for _, node in self.heap:
# if node.id == id:
# return node
# return None
#
# def allBeenContacted(self):
# return len(self.getUncontacted()) == 0
#
# def getIDs(self):
# return [n.id for n in self]
#
# def markContacted(self, node):
# self.contacted.add(node.id)
#
# def popleft(self):
# if len(self) > 0:
# return heapq.heappop(self.heap)[1]
# return None
#
# def push(self, nodes):
# """
# Push nodes onto heap.
#
# @param nodes: This can be a single item or a C{list}.
# """
# if not isinstance(nodes, list):
# nodes = [nodes]
#
# for node in nodes:
# if node.id not in [n.id for n in self]:
# distance = self.node.distanceTo(node)
# heapq.heappush(self.heap, (distance, node))
#
# def __len__(self):
# return min(len(self.heap), self.maxsize)
#
# def __iter__(self):
# nodes = heapq.nsmallest(self.maxsize, self.heap)
# return iter(map(itemgetter(1), nodes))
#
# def getUncontacted(self):
# return [n for n in self if n.id not in self.contacted]
#
# Path: subspace/tests/utils.py
# def mknode(id=None, ip=None, port=None, intid=None):
# """
# Make a node. Created a random id if not specified.
# """
# if intid is not None:
# id = pack('>l', intid)
# id = id or hashlib.sha1(str(random.getrandbits(255))).digest()
# return Node(id, ip, port)
. Output only the next line. | n = NodeHeap(mknode(intid=0), 3) |
Continue the code snippet: <|code_start|>
class UtilsTest(unittest.TestCase):
def test_digest(self):
d = hashlib.sha1('1').digest()
self.assertEqual(d, digest(1))
d = hashlib.sha1('another').digest()
self.assertEqual(d, digest('another'))
def test_sharedPrefix(self):
args = ['prefix', 'prefixasdf', 'prefix', 'prefixxxx']
<|code_end|>
. Use current file imports:
import hashlib
from twisted.trial import unittest
from subspace.utils import digest, sharedPrefix, OrderedSet
and context (classes, functions, or code) from other files:
# Path: subspace/utils.py
# def digest(s):
# if not isinstance(s, str):
# s = str(s)
# return hashlib.sha1(s).digest()
#
# def sharedPrefix(args):
# """
# Find the shared prefix between the strings.
#
# For instance:
#
# sharedPrefix(['blahblah', 'blahwhat'])
#
# returns 'blah'.
# """
# i = 0
# while i < min(map(len, args)):
# if len(set(map(operator.itemgetter(i), args))) != 1:
# break
# i += 1
# return args[0][:i]
#
# class OrderedSet(list):
# """
# Acts like a list in all ways, except in the behavior of the :meth:`push` method.
# """
#
# def push(self, thing):
# """
# 1. If the item exists in the list, it's removed
# 2. The item is pushed to the end of the list
# """
# if thing in self:
# self.remove(thing)
# self.append(thing)
. Output only the next line. | self.assertEqual(sharedPrefix(args), 'prefix') |
Predict the next line for this snippet: <|code_start|>
class UtilsTest(unittest.TestCase):
def test_digest(self):
d = hashlib.sha1('1').digest()
self.assertEqual(d, digest(1))
d = hashlib.sha1('another').digest()
self.assertEqual(d, digest('another'))
def test_sharedPrefix(self):
args = ['prefix', 'prefixasdf', 'prefix', 'prefixxxx']
self.assertEqual(sharedPrefix(args), 'prefix')
args = ['p', 'prefixasdf', 'prefix', 'prefixxxx']
self.assertEqual(sharedPrefix(args), 'p')
args = ['one', 'two']
self.assertEqual(sharedPrefix(args), '')
args = ['hi']
self.assertEqual(sharedPrefix(args), 'hi')
class OrderedSetTest(unittest.TestCase):
def test_order(self):
<|code_end|>
with the help of current file imports:
import hashlib
from twisted.trial import unittest
from subspace.utils import digest, sharedPrefix, OrderedSet
and context from other files:
# Path: subspace/utils.py
# def digest(s):
# if not isinstance(s, str):
# s = str(s)
# return hashlib.sha1(s).digest()
#
# def sharedPrefix(args):
# """
# Find the shared prefix between the strings.
#
# For instance:
#
# sharedPrefix(['blahblah', 'blahwhat'])
#
# returns 'blah'.
# """
# i = 0
# while i < min(map(len, args)):
# if len(set(map(operator.itemgetter(i), args))) != 1:
# break
# i += 1
# return args[0][:i]
#
# class OrderedSet(list):
# """
# Acts like a list in all ways, except in the behavior of the :meth:`push` method.
# """
#
# def push(self, thing):
# """
# 1. If the item exists in the list, it's removed
# 2. The item is pushed to the end of the list
# """
# if thing in self:
# self.remove(thing)
# self.append(thing)
, which may contain function names, class names, or code. Output only the next line. | o = OrderedSet() |
Next line prediction: <|code_start|>
alice = pyelliptic.ECC() # default curve: sect283r1
bob = pyelliptic.ECC(curve='sect571r1')
ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey())
print bob.decrypt(ciphertext)
signature = bob.sign("Hello Alice")
# alice's job :
print pyelliptic.ECC(
pubkey=bob.get_pubkey()).verify(signature, "Hello Alice")
# ERROR !!!
try:
key = alice.get_ecdh_key(bob.get_pubkey())
except: print("For ECDH key agreement,\
the keys must be defined on the same curve !")
alice = pyelliptic.ECC(curve='sect571r1')
print alice.get_ecdh_key(bob.get_pubkey()).encode('hex')
print bob.get_ecdh_key(alice.get_pubkey()).encode('hex')
"""
def __init__(self, pubkey=None, privkey=None, pubkey_x=None,
pubkey_y=None, raw_privkey=None, curve='sect283r1'):
"""
For a normal and High level use, specifie pubkey,
privkey (if you need) and the curve
"""
if type(curve) == str:
<|code_end|>
. Use current file imports:
(from hashlib import sha512
from .openssl import OpenSSL
from .cipher import Cipher
from .hash import hmac_sha256, equals
from struct import pack, unpack)
and context including class names, function names, or small code snippets from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
#
# Path: subspace/pyelliptic/cipher.py
# class Cipher:
# """
# Symmetric encryption
#
# import pyelliptic
# iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
# ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
# ciphertext = ctx.update('test1')
# ciphertext += ctx.update('test2')
# ciphertext += ctx.final()
#
# ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
# print ctx2.ciphering(ciphertext)
# """
# def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
# """
# do == 1 => Encrypt; do == 0 => Decrypt
# """
# self.cipher = OpenSSL.get_cipher(ciphername)
# self.ctx = OpenSSL.EVP_CIPHER_CTX_new()
# if do == 1 or do == 0:
# k = OpenSSL.malloc(key, len(key))
# IV = OpenSSL.malloc(iv, len(iv))
# OpenSSL.EVP_CipherInit_ex(
# self.ctx, self.cipher.get_pointer(), 0, k, IV, do)
# else:
# raise Exception("RTFM ...")
#
# @staticmethod
# def get_all_cipher():
# """
# static method, returns all ciphers available
# """
# return OpenSSL.cipher_algo.keys()
#
# @staticmethod
# def get_blocksize(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return cipher.get_blocksize()
#
# @staticmethod
# def gen_IV(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return OpenSSL.rand(cipher.get_blocksize())
#
# def update(self, input):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize())
# inp = OpenSSL.malloc(input, len(input))
# if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i), inp, len(input)) == 0:
# raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...")
# return buffer.raw[0:i.value]
#
# def final(self):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize())
# if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i))) == 0:
# raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...")
# return buffer.raw[0:i.value]
#
# def ciphering(self, input):
# """
# Do update and final in one method
# """
# buff = self.update(input)
# return buff + self.final()
#
# def __del__(self):
# OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx)
# OpenSSL.EVP_CIPHER_CTX_free(self.ctx)
#
# Path: subspace/pyelliptic/hash.py
# def hmac_sha256(k, m):
# """
# Compute the key and the message with HMAC SHA5256
# """
# key = OpenSSL.malloc(k, len(k))
# d = OpenSSL.malloc(m, len(m))
# md = OpenSSL.malloc(0, 32)
# i = OpenSSL.pointer(OpenSSL.c_int(0))
# OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i)
# return md.raw
#
# def equals(a, b):
# if isinstance(a, str):
# return _equals_str(a, b)
# else:
# return _equals_bytes(a, b)
. Output only the next line. | self.curve = OpenSSL.get_curve(curve) |
Next line prediction: <|code_start|> else:
return True # Good
return False
finally:
OpenSSL.EC_KEY_free(key)
OpenSSL.BN_free(pub_key_x)
OpenSSL.BN_free(pub_key_y)
OpenSSL.EC_POINT_free(pub_key)
OpenSSL.EVP_MD_CTX_destroy(md_ctx)
@staticmethod
def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'):
"""
Encrypt data with ECIES method using the public key of the recipient.
"""
curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey)
return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve,
ephemcurve=ephemcurve, ciphername=ciphername)
@staticmethod
def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1',
ephemcurve=None, ciphername='aes-256-cbc'):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
<|code_end|>
. Use current file imports:
(from hashlib import sha512
from .openssl import OpenSSL
from .cipher import Cipher
from .hash import hmac_sha256, equals
from struct import pack, unpack)
and context including class names, function names, or small code snippets from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
#
# Path: subspace/pyelliptic/cipher.py
# class Cipher:
# """
# Symmetric encryption
#
# import pyelliptic
# iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
# ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
# ciphertext = ctx.update('test1')
# ciphertext += ctx.update('test2')
# ciphertext += ctx.final()
#
# ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
# print ctx2.ciphering(ciphertext)
# """
# def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
# """
# do == 1 => Encrypt; do == 0 => Decrypt
# """
# self.cipher = OpenSSL.get_cipher(ciphername)
# self.ctx = OpenSSL.EVP_CIPHER_CTX_new()
# if do == 1 or do == 0:
# k = OpenSSL.malloc(key, len(key))
# IV = OpenSSL.malloc(iv, len(iv))
# OpenSSL.EVP_CipherInit_ex(
# self.ctx, self.cipher.get_pointer(), 0, k, IV, do)
# else:
# raise Exception("RTFM ...")
#
# @staticmethod
# def get_all_cipher():
# """
# static method, returns all ciphers available
# """
# return OpenSSL.cipher_algo.keys()
#
# @staticmethod
# def get_blocksize(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return cipher.get_blocksize()
#
# @staticmethod
# def gen_IV(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return OpenSSL.rand(cipher.get_blocksize())
#
# def update(self, input):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize())
# inp = OpenSSL.malloc(input, len(input))
# if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i), inp, len(input)) == 0:
# raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...")
# return buffer.raw[0:i.value]
#
# def final(self):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize())
# if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i))) == 0:
# raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...")
# return buffer.raw[0:i.value]
#
# def ciphering(self, input):
# """
# Do update and final in one method
# """
# buff = self.update(input)
# return buff + self.final()
#
# def __del__(self):
# OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx)
# OpenSSL.EVP_CIPHER_CTX_free(self.ctx)
#
# Path: subspace/pyelliptic/hash.py
# def hmac_sha256(k, m):
# """
# Compute the key and the message with HMAC SHA5256
# """
# key = OpenSSL.malloc(k, len(k))
# d = OpenSSL.malloc(m, len(m))
# md = OpenSSL.malloc(0, 32)
# i = OpenSSL.pointer(OpenSSL.c_int(0))
# OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i)
# return md.raw
#
# def equals(a, b):
# if isinstance(a, str):
# return _equals_str(a, b)
# else:
# return _equals_bytes(a, b)
. Output only the next line. | ctx = Cipher(key_e, iv, 1, ciphername) |
Here is a snippet: <|code_start|> return False
finally:
OpenSSL.EC_KEY_free(key)
OpenSSL.BN_free(pub_key_x)
OpenSSL.BN_free(pub_key_y)
OpenSSL.EC_POINT_free(pub_key)
OpenSSL.EVP_MD_CTX_destroy(md_ctx)
@staticmethod
def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'):
"""
Encrypt data with ECIES method using the public key of the recipient.
"""
curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey)
return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve,
ephemcurve=ephemcurve, ciphername=ciphername)
@staticmethod
def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1',
ephemcurve=None, ciphername='aes-256-cbc'):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
ctx = Cipher(key_e, iv, 1, ciphername)
ciphertext = iv + ephem.pubkey_x + ephem.pubkey_y + ctx.ciphering(data)
<|code_end|>
. Write the next line using the current file imports:
from hashlib import sha512
from .openssl import OpenSSL
from .cipher import Cipher
from .hash import hmac_sha256, equals
from struct import pack, unpack
and context from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
#
# Path: subspace/pyelliptic/cipher.py
# class Cipher:
# """
# Symmetric encryption
#
# import pyelliptic
# iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
# ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
# ciphertext = ctx.update('test1')
# ciphertext += ctx.update('test2')
# ciphertext += ctx.final()
#
# ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
# print ctx2.ciphering(ciphertext)
# """
# def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
# """
# do == 1 => Encrypt; do == 0 => Decrypt
# """
# self.cipher = OpenSSL.get_cipher(ciphername)
# self.ctx = OpenSSL.EVP_CIPHER_CTX_new()
# if do == 1 or do == 0:
# k = OpenSSL.malloc(key, len(key))
# IV = OpenSSL.malloc(iv, len(iv))
# OpenSSL.EVP_CipherInit_ex(
# self.ctx, self.cipher.get_pointer(), 0, k, IV, do)
# else:
# raise Exception("RTFM ...")
#
# @staticmethod
# def get_all_cipher():
# """
# static method, returns all ciphers available
# """
# return OpenSSL.cipher_algo.keys()
#
# @staticmethod
# def get_blocksize(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return cipher.get_blocksize()
#
# @staticmethod
# def gen_IV(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return OpenSSL.rand(cipher.get_blocksize())
#
# def update(self, input):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize())
# inp = OpenSSL.malloc(input, len(input))
# if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i), inp, len(input)) == 0:
# raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...")
# return buffer.raw[0:i.value]
#
# def final(self):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize())
# if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i))) == 0:
# raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...")
# return buffer.raw[0:i.value]
#
# def ciphering(self, input):
# """
# Do update and final in one method
# """
# buff = self.update(input)
# return buff + self.final()
#
# def __del__(self):
# OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx)
# OpenSSL.EVP_CIPHER_CTX_free(self.ctx)
#
# Path: subspace/pyelliptic/hash.py
# def hmac_sha256(k, m):
# """
# Compute the key and the message with HMAC SHA5256
# """
# key = OpenSSL.malloc(k, len(k))
# d = OpenSSL.malloc(m, len(m))
# md = OpenSSL.malloc(0, 32)
# i = OpenSSL.pointer(OpenSSL.c_int(0))
# OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i)
# return md.raw
#
# def equals(a, b):
# if isinstance(a, str):
# return _equals_str(a, b)
# else:
# return _equals_bytes(a, b)
, which may include functions, classes, or code. Output only the next line. | mac = hmac_sha256(key_m, ciphertext) |
Given the code snippet: <|code_start|>
@staticmethod
def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1',
ephemcurve=None, ciphername='aes-256-cbc'):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
ctx = Cipher(key_e, iv, 1, ciphername)
ciphertext = iv + ephem.pubkey_x + ephem.pubkey_y + ctx.ciphering(data)
mac = hmac_sha256(key_m, ciphertext)
return ciphertext + mac
def decrypt(self, data, ciphername='aes-256-cbc'):
"""
Decrypt data with ECIES method using the local private key
"""
blocksize = OpenSSL.get_cipher(ciphername).get_blocksize()
iv = data[:blocksize]
i = blocksize
curve, pubkey_x, pubkey_y, i2 = ECC._decode_keys(data[i:])
i += i2
ciphertext = data[i:len(data)-32]
i += len(ciphertext)
mac = data[i:]
key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
<|code_end|>
, generate the next line using the imports in this file:
from hashlib import sha512
from .openssl import OpenSSL
from .cipher import Cipher
from .hash import hmac_sha256, equals
from struct import pack, unpack
and context (functions, classes, or occasionally code) from other files:
# Path: subspace/pyelliptic/openssl.py
# class CipherName:
# class _OpenSSL:
# def __init__(self, name, pointer, blocksize):
# def __str__(self):
# def get_pointer(self):
# def get_name(self):
# def get_blocksize(self):
# def __init__(self, library):
# def _set_ciphers(self):
# def _set_curves(self):
# def BN_num_bytes(self, x):
# def get_cipher(self, name):
# def get_curve(self, name):
# def get_curve_by_id(self, id):
# def rand(self, size):
# def malloc(self, data, size):
#
# Path: subspace/pyelliptic/cipher.py
# class Cipher:
# """
# Symmetric encryption
#
# import pyelliptic
# iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
# ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
# ciphertext = ctx.update('test1')
# ciphertext += ctx.update('test2')
# ciphertext += ctx.final()
#
# ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
# print ctx2.ciphering(ciphertext)
# """
# def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
# """
# do == 1 => Encrypt; do == 0 => Decrypt
# """
# self.cipher = OpenSSL.get_cipher(ciphername)
# self.ctx = OpenSSL.EVP_CIPHER_CTX_new()
# if do == 1 or do == 0:
# k = OpenSSL.malloc(key, len(key))
# IV = OpenSSL.malloc(iv, len(iv))
# OpenSSL.EVP_CipherInit_ex(
# self.ctx, self.cipher.get_pointer(), 0, k, IV, do)
# else:
# raise Exception("RTFM ...")
#
# @staticmethod
# def get_all_cipher():
# """
# static method, returns all ciphers available
# """
# return OpenSSL.cipher_algo.keys()
#
# @staticmethod
# def get_blocksize(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return cipher.get_blocksize()
#
# @staticmethod
# def gen_IV(ciphername):
# cipher = OpenSSL.get_cipher(ciphername)
# return OpenSSL.rand(cipher.get_blocksize())
#
# def update(self, input):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize())
# inp = OpenSSL.malloc(input, len(input))
# if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i), inp, len(input)) == 0:
# raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...")
# return buffer.raw[0:i.value]
#
# def final(self):
# i = OpenSSL.c_int(0)
# buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize())
# if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer),
# OpenSSL.byref(i))) == 0:
# raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...")
# return buffer.raw[0:i.value]
#
# def ciphering(self, input):
# """
# Do update and final in one method
# """
# buff = self.update(input)
# return buff + self.final()
#
# def __del__(self):
# OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx)
# OpenSSL.EVP_CIPHER_CTX_free(self.ctx)
#
# Path: subspace/pyelliptic/hash.py
# def hmac_sha256(k, m):
# """
# Compute the key and the message with HMAC SHA5256
# """
# key = OpenSSL.malloc(k, len(k))
# d = OpenSSL.malloc(m, len(m))
# md = OpenSSL.malloc(0, 32)
# i = OpenSSL.pointer(OpenSSL.c_int(0))
# OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i)
# return md.raw
#
# def equals(a, b):
# if isinstance(a, str):
# return _equals_str(a, b)
# else:
# return _equals_bytes(a, b)
. Output only the next line. | if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac): |
Next line prediction: <|code_start|>
class KBucket(object):
def __init__(self, rangeLower, rangeUpper, ksize):
self.range = (rangeLower, rangeUpper)
self.nodes = OrderedDict()
<|code_end|>
. Use current file imports:
(import heapq
import time
import operator
from collections import OrderedDict
from subspace.utils import OrderedSet, sharedPrefix)
and context including class names, function names, or small code snippets from other files:
# Path: subspace/utils.py
# class OrderedSet(list):
# """
# Acts like a list in all ways, except in the behavior of the :meth:`push` method.
# """
#
# def push(self, thing):
# """
# 1. If the item exists in the list, it's removed
# 2. The item is pushed to the end of the list
# """
# if thing in self:
# self.remove(thing)
# self.append(thing)
#
# def sharedPrefix(args):
# """
# Find the shared prefix between the strings.
#
# For instance:
#
# sharedPrefix(['blahblah', 'blahwhat'])
#
# returns 'blah'.
# """
# i = 0
# while i < min(map(len, args)):
# if len(set(map(operator.itemgetter(i), args))) != 1:
# break
# i += 1
# return args[0][:i]
. Output only the next line. | self.replacementNodes = OrderedSet() |
Given the following code snippet before the placeholder: <|code_start|> del self.nodes[node.id]
if len(self.replacementNodes) > 0:
newnode = self.replacementNodes.pop()
self.nodes[newnode.id] = newnode
def hasInRange(self, node):
return self.range[0] <= node.long_id <= self.range[1]
def isNewNode(self, node):
return node.id not in self.nodes
def addNode(self, node):
"""
Add a C{Node} to the C{KBucket}. Return True if successful,
False if the bucket is full.
If the bucket is full, keep track of node in a replacement list,
per section 4.1 of the paper.
"""
if node.id in self.nodes:
del self.nodes[node.id]
self.nodes[node.id] = node
elif len(self) < self.ksize:
self.nodes[node.id] = node
else:
self.replacementNodes.push(node)
return False
return True
def depth(self):
<|code_end|>
, predict the next line using imports from the current file:
import heapq
import time
import operator
from collections import OrderedDict
from subspace.utils import OrderedSet, sharedPrefix
and context including class names, function names, and sometimes code from other files:
# Path: subspace/utils.py
# class OrderedSet(list):
# """
# Acts like a list in all ways, except in the behavior of the :meth:`push` method.
# """
#
# def push(self, thing):
# """
# 1. If the item exists in the list, it's removed
# 2. The item is pushed to the end of the list
# """
# if thing in self:
# self.remove(thing)
# self.append(thing)
#
# def sharedPrefix(args):
# """
# Find the shared prefix between the strings.
#
# For instance:
#
# sharedPrefix(['blahblah', 'blahwhat'])
#
# returns 'blah'.
# """
# i = 0
# while i < min(map(len, args)):
# if len(set(map(operator.itemgetter(i), args))) != 1:
# break
# i += 1
# return args[0][:i]
. Output only the next line. | sp = sharedPrefix([n.id for n in self.nodes.values()]) |
Given snippet: <|code_start|>
class IAMDatasource(DatasourcePlugin[str, IAMEntry], metaclass=Singleton):
_arn_to_id: Dict[str, str] = {}
def __init__(self, config: Optional[RepokidConfig] = None):
super().__init__(config=config)
def _fetch_account(self, account_number: str) -> Dict[str, IAMEntry]:
logger.info("getting role data for account %s", account_number)
conn = copy.deepcopy(self.config.get("connection_iam", {}))
conn["account_number"] = account_number
auth_details = get_account_authorization_details(filter="Role", **conn)
auth_details_by_id = {item["Arn"]: item for item in auth_details}
self._arn_to_id.update({item["Arn"]: item["RoleId"] for item in auth_details})
# convert policies list to dictionary to maintain consistency with old call which returned a dict
for _, data in auth_details_by_id.items():
data["RolePolicyList"] = {
item["PolicyName"]: item["PolicyDocument"]
for item in data["RolePolicyList"]
}
return auth_details_by_id
def _fetch(self, arn: str) -> IAMEntry:
logger.info("getting role data for role %s", arn)
conn = copy.deepcopy(self.config["connection_iam"])
conn["account_number"] = arn.split(":")[4]
role = {"RoleName": arn.split("/")[-1]}
role_info: IAMEntry = get_role(role, flags=FLAGS.INLINE_POLICIES, **conn)
self._arn_to_id[arn] = role_info["RoleId"]
if not role_info:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import logging
from typing import Dict
from typing import Iterable
from typing import Optional
from cloudaux.aws.iam import get_account_authorization_details
from cloudaux.orchestration.aws.iam.role import FLAGS
from cloudaux.orchestration.aws.iam.role import get_role
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import IAMEntry
from repokid.types import RepokidConfig
and context:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
which might include code, classes, or functions. Output only the next line. | raise NotFoundError |
Given the code snippet: <|code_start|># Copyright 2021 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
logger = logging.getLogger("repokid")
class IAMDatasource(DatasourcePlugin[str, IAMEntry], metaclass=Singleton):
_arn_to_id: Dict[str, str] = {}
<|code_end|>
, generate the next line using the imports in this file:
import copy
import logging
from typing import Dict
from typing import Iterable
from typing import Optional
from cloudaux.aws.iam import get_account_authorization_details
from cloudaux.orchestration.aws.iam.role import FLAGS
from cloudaux.orchestration.aws.iam.role import get_role
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import IAMEntry
from repokid.types import RepokidConfig
and context (functions, classes, or occasionally code) from other files:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
. Output only the next line. | def __init__(self, config: Optional[RepokidConfig] = None): |
Using the snippet: <|code_start|>
def test_iam_get():
ds = IAMDatasource()
arn = "pretend_arn"
expected = {"a": "b"}
ds._data = {arn: expected}
result = ds.get(arn)
assert result == expected
@patch("repokid.datasource.iam.IAMDatasource._fetch")
def test_iam_get_fallback_not_found(mock_fetch):
<|code_end|>
, determine the next line of code. You have imports:
from unittest.mock import patch
from repokid.datasource.iam import IAMDatasource
from repokid.exceptions import NotFoundError
import pytest
and context (class names, function names, or code) available:
# Path: repokid/datasource/iam.py
# class IAMDatasource(DatasourcePlugin[str, IAMEntry], metaclass=Singleton):
# _arn_to_id: Dict[str, str] = {}
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
#
# def _fetch_account(self, account_number: str) -> Dict[str, IAMEntry]:
# logger.info("getting role data for account %s", account_number)
# conn = copy.deepcopy(self.config.get("connection_iam", {}))
# conn["account_number"] = account_number
# auth_details = get_account_authorization_details(filter="Role", **conn)
# auth_details_by_id = {item["Arn"]: item for item in auth_details}
# self._arn_to_id.update({item["Arn"]: item["RoleId"] for item in auth_details})
# # convert policies list to dictionary to maintain consistency with old call which returned a dict
# for _, data in auth_details_by_id.items():
# data["RolePolicyList"] = {
# item["PolicyName"]: item["PolicyDocument"]
# for item in data["RolePolicyList"]
# }
# return auth_details_by_id
#
# def _fetch(self, arn: str) -> IAMEntry:
# logger.info("getting role data for role %s", arn)
# conn = copy.deepcopy(self.config["connection_iam"])
# conn["account_number"] = arn.split(":")[4]
# role = {"RoleName": arn.split("/")[-1]}
# role_info: IAMEntry = get_role(role, flags=FLAGS.INLINE_POLICIES, **conn)
# self._arn_to_id[arn] = role_info["RoleId"]
# if not role_info:
# raise NotFoundError
# self._data[arn] = role_info
# return role_info
#
# def get(self, arn: str) -> IAMEntry:
# result = self._data.get(arn)
# if not result:
# return self._fetch(arn)
# return result
#
# def get_id_for_arn(self, arn: str) -> Optional[str]:
# return self._arn_to_id.get(arn)
#
# def _get_ids_for_account(self, account_number: str) -> Iterable[str]:
# ids_for_account = [
# k for k, v in self.items() if v["Arn"].split(":")[4] == account_number
# ]
# return ids_for_account
#
# def seed(self, account_number: str) -> Iterable[str]:
# if account_number in self._seeded:
# return self._get_ids_for_account(account_number)
# fetched_data = self._fetch_account(account_number)
# new_keys = fetched_data.keys()
# self._data.update(fetched_data)
# self._seeded.append(account_number)
# return new_keys
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
. Output only the next line. | mock_fetch.side_effect = NotFoundError |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger("repokid")
class AccessAdvisorDatasource(
DatasourcePlugin[str, AccessAdvisorEntry], metaclass=Singleton
):
def __init__(self, config: Optional[RepokidConfig] = None):
super().__init__(config=config)
def _fetch(
self, account_number: str = "", arn: str = ""
) -> Dict[str, AccessAdvisorEntry]:
"""
Make a request to the Aardvark server to get all data about a given account or ARN.
We'll request in groups of PAGE_SIZE and check the current count to see if we're done. Keep requesting as long
as the total count (reported by the API) is greater than the number of pages we've received times the page size.
As we go, keeping building the dict and return it when done.
Args:
account_number (string): Used to form the phrase query for Aardvark
arn (string)
Returns:
dict: Aardvark data is a dict with the role ARN as the key and a list of services as value
"""
api_location = self.config.get("aardvark_api_location")
if not api_location:
<|code_end|>
using the current file's imports:
import logging
import requests
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import AardvarkError
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import AardvarkResponse
from repokid.types import AccessAdvisorEntry
from repokid.types import RepokidConfig
and any relevant context from other files:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class AardvarkError(Exception):
# pass
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
. Output only the next line. | raise AardvarkError("aardvark not configured") |
Here is a snippet: <|code_start|> r_aardvark = requests.post(api_location, params=params, json=payload)
except requests.exceptions.RequestException as e:
logger.exception("unable to get Aardvark data: {}".format(e))
raise AardvarkError("unable to get aardvark data")
else:
if r_aardvark.status_code != 200:
logger.exception("unable to get Aardvark data")
raise AardvarkError("unable to get aardvark data")
response_data.update(r_aardvark.json())
# don't want these in our Aardvark data
response_data.pop("count")
response_data.pop("page")
response_data.pop("total")
if PAGE_SIZE * page_num < r_aardvark.json().get("total"):
page_num += 1
else:
break
return response_data
def get(self, arn: str) -> AccessAdvisorEntry:
result = self._data.get(arn)
if result:
return result
# Try to get data from Aardvark
result = self._fetch(arn=arn).get(arn)
if result:
self._data[arn] = result
return result
<|code_end|>
. Write the next line using the current file imports:
import logging
import requests
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import AardvarkError
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import AardvarkResponse
from repokid.types import AccessAdvisorEntry
from repokid.types import RepokidConfig
and context from other files:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class AardvarkError(Exception):
# pass
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
, which may include functions, classes, or code. Output only the next line. | raise NotFoundError |
Given the code snippet: <|code_start|>
logger = logging.getLogger("repokid")
class AccessAdvisorDatasource(
DatasourcePlugin[str, AccessAdvisorEntry], metaclass=Singleton
):
def __init__(self, config: Optional[RepokidConfig] = None):
super().__init__(config=config)
def _fetch(
self, account_number: str = "", arn: str = ""
) -> Dict[str, AccessAdvisorEntry]:
"""
Make a request to the Aardvark server to get all data about a given account or ARN.
We'll request in groups of PAGE_SIZE and check the current count to see if we're done. Keep requesting as long
as the total count (reported by the API) is greater than the number of pages we've received times the page size.
As we go, keeping building the dict and return it when done.
Args:
account_number (string): Used to form the phrase query for Aardvark
arn (string)
Returns:
dict: Aardvark data is a dict with the role ARN as the key and a list of services as value
"""
api_location = self.config.get("aardvark_api_location")
if not api_location:
raise AardvarkError("aardvark not configured")
<|code_end|>
, generate the next line using the imports in this file:
import logging
import requests
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import AardvarkError
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import AardvarkResponse
from repokid.types import AccessAdvisorEntry
from repokid.types import RepokidConfig
and context (functions, classes, or occasionally code) from other files:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class AardvarkError(Exception):
# pass
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
. Output only the next line. | response_data: AardvarkResponse = {} |
Predict the next line after this snippet: <|code_start|># Copyright 2021 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
logger = logging.getLogger("repokid")
class AccessAdvisorDatasource(
DatasourcePlugin[str, AccessAdvisorEntry], metaclass=Singleton
):
<|code_end|>
using the current file's imports:
import logging
import requests
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from repokid.datasource.plugin import DatasourcePlugin
from repokid.exceptions import AardvarkError
from repokid.exceptions import NotFoundError
from repokid.plugin import Singleton
from repokid.types import AardvarkResponse
from repokid.types import AccessAdvisorEntry
from repokid.types import RepokidConfig
and any relevant context from other files:
# Path: repokid/datasource/plugin.py
# class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
# """A dict-like container that can be used to retrieve and store data"""
#
# _data: Dict[KT, VT]
# _seeded: List[str]
#
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
# self._data = {}
# self._seeded = []
#
# def __getitem__(self, name: KT) -> VT:
# return self._data[name]
#
# def __iter__(self) -> Iterator[VT]:
# return iter(cast(Iterable[VT], self._data))
#
# def keys(self) -> Iterable[KT]:
# return self._data.keys()
#
# def items(self) -> ItemsView[KT, VT]:
# return self._data.items()
#
# def values(self) -> ValuesView[VT]:
# return self._data.values()
#
# def get(self, identifier: KT) -> VT:
# raise NotImplementedError
#
# def seed(self, identifier: KT) -> Iterable[KT]:
# raise NotImplementedError
#
# def reset(self) -> None:
# logger.debug("resetting %s", type(self).__name__)
# self._data = {}
# self._seeded = []
#
# Path: repokid/exceptions.py
# class AardvarkError(Exception):
# pass
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
#
# Path: repokid/plugin.py
# class Singleton(M_A):
# _instances: Dict[str, Singleton] = {}
#
# def __call__(cls, *args: Any, **kwargs: Any) -> Singleton:
# if cls.__name__ not in cls._instances:
# cls._instances[cls.__name__] = super(Singleton, cls).__call__(
# *args, **kwargs
# )
# return cls._instances[cls.__name__]
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
. Output only the next line. | def __init__(self, config: Optional[RepokidConfig] = None): |
Given snippet: <|code_start|> bool
"""
exported_no_whitespace = json.dumps(policies, separators=(",", ":"))
if len(exported_no_whitespace) > MAX_AWS_POLICY_SIZE:
return True
return False
def delete_policy(
name: str, role_name: str, account_number: str, conn: Dict[str, Any]
) -> None:
"""Deletes the specified IAM Role inline policy.
Args:
name (string)
role (Role object)
account_number (string)
conn (dict)
Returns:
error (string) or None
"""
LOGGER.info(
"Deleting policy with name {} from {} in account {}".format(
name, role_name, account_number
)
)
try:
delete_role_policy(RoleName=role_name, PolicyName=name, **conn)
except botocore.exceptions.ClientError as e:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import json
import logging
import re
import botocore
from typing import Any
from typing import Dict
from cloudaux.aws.iam import delete_role_policy
from cloudaux.aws.iam import put_role_policy
from cloudaux.aws.sts import boto3_cached_conn
from mypy_boto3_iam.client import IAMClient
from repokid.exceptions import IAMError
and context:
# Path: repokid/exceptions.py
# class IAMError(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | raise IAMError( |
Here is a snippet: <|code_start|># Copyright 2021 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
logger = logging.getLogger("repokid")
class DatasourcePlugin(RepokidPlugin, Generic[KT, VT]):
"""A dict-like container that can be used to retrieve and store data"""
_data: Dict[KT, VT]
_seeded: List[str]
<|code_end|>
. Write the next line using the current file imports:
import logging
from typing import Dict
from typing import Generic
from typing import ItemsView
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import ValuesView
from typing import cast
from repokid.plugin import RepokidPlugin
from repokid.types import KT
from repokid.types import VT
from repokid.types import RepokidConfig
and context from other files:
# Path: repokid/plugin.py
# class RepokidPlugin:
# def __init__(self, config: Optional[RepokidConfig] = None):
# if config:
# self.config = config
# else:
# self.config = CONFIG
#
# Path: repokid/types.py
# KT = TypeVar("KT")
#
# Path: repokid/types.py
# VT = TypeVar("VT")
#
# Path: repokid/types.py
# KT = TypeVar("KT")
# VT = TypeVar("VT")
, which may include functions, classes, or code. Output only the next line. | def __init__(self, config: Optional[RepokidConfig] = None): |
Given the following code snippet before the placeholder: <|code_start|>
def test_access_advisor_get():
ds = AccessAdvisorDatasource()
arn = "pretend_arn"
expected = [{"a": "b"}]
ds._data = {arn: expected}
result = ds.get(arn)
assert result == expected
@patch("repokid.datasource.access_advisor.AccessAdvisorDatasource._fetch")
def test_access_advisor_get_fallback(mock_fetch):
ds = AccessAdvisorDatasource()
arn = "pretend_arn"
expected = [{"a": "b"}]
mock_fetch.return_value = {arn: expected}
result = ds.get(arn)
mock_fetch.assert_called_once()
assert mock_fetch.call_args[1]["arn"] == arn
assert result == expected
# make sure fetched data gets cached
assert arn in ds._data
assert ds._data[arn] == expected
@patch("repokid.datasource.access_advisor.AccessAdvisorDatasource._fetch")
def test_access_advisor_get_fallback_not_found(mock_fetch):
ds = AccessAdvisorDatasource()
arn = "pretend_arn"
mock_fetch.return_value = {}
<|code_end|>
, predict the next line using imports from the current file:
from unittest.mock import patch
from repokid.datasource.access_advisor import AccessAdvisorDatasource
from repokid.exceptions import NotFoundError
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: repokid/datasource/access_advisor.py
# class AccessAdvisorDatasource(
# DatasourcePlugin[str, AccessAdvisorEntry], metaclass=Singleton
# ):
# def __init__(self, config: Optional[RepokidConfig] = None):
# super().__init__(config=config)
#
# def _fetch(
# self, account_number: str = "", arn: str = ""
# ) -> Dict[str, AccessAdvisorEntry]:
# """
# Make a request to the Aardvark server to get all data about a given account or ARN.
# We'll request in groups of PAGE_SIZE and check the current count to see if we're done. Keep requesting as long
# as the total count (reported by the API) is greater than the number of pages we've received times the page size.
# As we go, keeping building the dict and return it when done.
#
# Args:
# account_number (string): Used to form the phrase query for Aardvark
# arn (string)
#
# Returns:
# dict: Aardvark data is a dict with the role ARN as the key and a list of services as value
# """
# api_location = self.config.get("aardvark_api_location")
# if not api_location:
# raise AardvarkError("aardvark not configured")
#
# response_data: AardvarkResponse = {}
#
# PAGE_SIZE = 1000
# page_num = 1
#
# payload: Dict[str, Any]
# if account_number:
# payload = {"phrase": account_number}
# elif arn:
# payload = {"arn": [arn]}
# else:
# return {}
# while True:
# params = {"count": PAGE_SIZE, "page": page_num}
# try:
# r_aardvark = requests.post(api_location, params=params, json=payload)
# except requests.exceptions.RequestException as e:
# logger.exception("unable to get Aardvark data: {}".format(e))
# raise AardvarkError("unable to get aardvark data")
# else:
# if r_aardvark.status_code != 200:
# logger.exception("unable to get Aardvark data")
# raise AardvarkError("unable to get aardvark data")
#
# response_data.update(r_aardvark.json())
# # don't want these in our Aardvark data
# response_data.pop("count")
# response_data.pop("page")
# response_data.pop("total")
# if PAGE_SIZE * page_num < r_aardvark.json().get("total"):
# page_num += 1
# else:
# break
# return response_data
#
# def get(self, arn: str) -> AccessAdvisorEntry:
# result = self._data.get(arn)
# if result:
# return result
#
# # Try to get data from Aardvark
# result = self._fetch(arn=arn).get(arn)
# if result:
# self._data[arn] = result
# return result
# raise NotFoundError
#
# def _get_arns_for_account(self, account_number: str) -> Iterable[str]:
# return filter(lambda x: x.split(":")[4] == account_number, self.keys())
#
# def seed(self, account_number: str) -> Iterable[str]:
# if account_number not in self._seeded:
# aa_data = self._fetch(account_number=account_number)
# self._data.update(aa_data)
# self._seeded.append(account_number)
# return aa_data.keys()
# else:
# return self._get_arns_for_account(account_number)
#
# Path: repokid/exceptions.py
# class NotFoundError(Exception):
# pass
. Output only the next line. | with pytest.raises(NotFoundError): |
Predict the next line for this snippet: <|code_start|>
v1_api = Api(api_name='v1')
v1_api.register(EventResource())
v1_api.register(InstanceResource())
<|code_end|>
with the help of current file imports:
from django.conf.urls.defaults import include, patterns, url
from tastypie.api import Api
from wprevents.events.api import EventResource, InstanceResource, SpaceResource, FunctionalAreaResource
and context from other files:
# Path: wprevents/events/api.py
# class EventResource(CustomResource):
# class Meta:
# queryset = Event.objects.all()
# fields = ['id', 'title', 'slug', 'start', 'end', 'city', 'country', 'description']
# filtering = {
# "title": ('startswith',),
# }
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['json', 'csv', 'ical'])
#
# def dehydrate(self, bundle):
# if bundle.obj.space:
# bundle.data['space'] = bundle.obj.space.name
# bundle.data['functional_areas'] = ','.join(bundle.obj.area_names)
#
# return bundle
#
# class InstanceResource(CustomResource):
# class Meta:
# queryset = Instance.objects.all()
# fields = ['id', 'start', 'end']
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv', 'ical'])
#
# def dehydrate(self, bundle):
# if bundle.obj.event:
# bundle.data['event_id'] = bundle.obj.event.id
# bundle.data['title'] = bundle.obj.event.title
# bundle.data['slug'] = bundle.obj.event.slug
# bundle.data['description'] = bundle.obj.event.description
# bundle.data['functional_areas'] = ','.join(bundle.obj.event.area_names)
# if bundle.obj.event.space:
# bundle.data['space'] = bundle.obj.event.space.name
#
# return bundle
#
# class SpaceResource(CustomResource):
# class Meta:
# queryset = Space.objects.all()
# fields = ['name', 'address', 'address2', 'city', 'country', 'lat', 'lon', 'photo_url']
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv'])
#
# class FunctionalAreaResource(CustomResource):
# class Meta:
# queryset = FunctionalArea.objects.all()
# fields = ['name', 'slug', 'color']
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv'])
, which may contain function names, class names, or code. Output only the next line. | v1_api.register(SpaceResource()) |
Based on the snippet: <|code_start|>
v1_api = Api(api_name='v1')
v1_api.register(EventResource())
v1_api.register(InstanceResource())
v1_api.register(SpaceResource())
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls.defaults import include, patterns, url
from tastypie.api import Api
from wprevents.events.api import EventResource, InstanceResource, SpaceResource, FunctionalAreaResource
and context (classes, functions, sometimes code) from other files:
# Path: wprevents/events/api.py
# class EventResource(CustomResource):
# class Meta:
# queryset = Event.objects.all()
# fields = ['id', 'title', 'slug', 'start', 'end', 'city', 'country', 'description']
# filtering = {
# "title": ('startswith',),
# }
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['json', 'csv', 'ical'])
#
# def dehydrate(self, bundle):
# if bundle.obj.space:
# bundle.data['space'] = bundle.obj.space.name
# bundle.data['functional_areas'] = ','.join(bundle.obj.area_names)
#
# return bundle
#
# class InstanceResource(CustomResource):
# class Meta:
# queryset = Instance.objects.all()
# fields = ['id', 'start', 'end']
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv', 'ical'])
#
# def dehydrate(self, bundle):
# if bundle.obj.event:
# bundle.data['event_id'] = bundle.obj.event.id
# bundle.data['title'] = bundle.obj.event.title
# bundle.data['slug'] = bundle.obj.event.slug
# bundle.data['description'] = bundle.obj.event.description
# bundle.data['functional_areas'] = ','.join(bundle.obj.event.area_names)
# if bundle.obj.event.space:
# bundle.data['space'] = bundle.obj.event.space.name
#
# return bundle
#
# class SpaceResource(CustomResource):
# class Meta:
# queryset = Space.objects.all()
# fields = ['name', 'address', 'address2', 'city', 'country', 'lat', 'lon', 'photo_url']
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv'])
#
# class FunctionalAreaResource(CustomResource):
# class Meta:
# queryset = FunctionalArea.objects.all()
# fields = ['name', 'slug', 'color']
#
# allowed_methods = ['get']
# include_resource_uri = False
# include_absolute_url = False
#
# serializer = CustomSerializer(formats=['csv'])
. Output only the next line. | v1_api.register(FunctionalAreaResource()) |
Using the snippet: <|code_start|> return rdd.map(otsu)
elif method == 'duel':
return rdd.map(duel)
elif method == 'phansalkar':
block_size = args[0]
return rdd.map(phansalkar)
else:
raise "Bad Threshold Method", method
def peak_filter(rdd, smooth_size):
def func(frame):
frame = frame.astype(bool)
binary = remove_small_objects(frame, smooth_size)
#binary = ndi.binary_fill_holes(binary)
#opened = binary_opening(frame, disk(smooth_size))
#opened = opened & frame
return binary
return rdd.map(func)
def watershed(rdd, min_radius):
def func(dframe):
frame, binary = dframe[0], dframe[1]
#binary = remove_small_objects(binary, min_radius, connectivity=2)
distance = ndimage.distance_transform_edt(binary)
local_maxi = peak_local_max(distance, min_distance=2*min_radius, indices=False, labels=frame)
markers = ndimage.label(local_maxi)[0]
labeled = watershed(-distance, markers, mask=binary)
return labeled
return rdd.map(func)
<|code_end|>
, determine the next line of code. You have imports:
from MEHI.utils.tool import exeTime, bar, log
from skimage.filters import threshold_otsu, threshold_adaptive
from MEHI.udf._phansalkar import phansalkar as _phansalkar
from skimage.morphology import disk, binary_opening, remove_small_objects
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from skimage.measure import regionprops
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from MEHI.udf._moment import moment
from scipy import ndimage as ndi
import numpy as np
import scipy.ndimage as ndi
import scipy.ndimage as ndi
import pandas as pd
import scipy.cluster.hierarchy as hier
import pandas as pd
and context (class names, function names, or code) available:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def bar(level):
# '''
# Usage:
# - this will show a progress bar
# - e.g. bar('info')(msg, i, 100)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg, i, end):
# if i <= end:
# sys.stdout.write('[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] ('+ str(i)+'/' + str(end) + ') '+ msg + '\r')
# sys.stdout.flush()
# if i == end:
# print
# return wraper
# else:
# def wraper(msg, i, end):
# pass
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | @exeTime
|
Using the snippet: <|code_start|>
def peak_filter(rdd, smooth_size):
def func(frame):
frame = frame.astype(bool)
binary = remove_small_objects(frame, smooth_size)
#binary = ndi.binary_fill_holes(binary)
#opened = binary_opening(frame, disk(smooth_size))
#opened = opened & frame
return binary
return rdd.map(func)
def watershed(rdd, min_radius):
def func(dframe):
frame, binary = dframe[0], dframe[1]
#binary = remove_small_objects(binary, min_radius, connectivity=2)
distance = ndimage.distance_transform_edt(binary)
local_maxi = peak_local_max(distance, min_distance=2*min_radius, indices=False, labels=frame)
markers = ndimage.label(local_maxi)[0]
labeled = watershed(-distance, markers, mask=binary)
return labeled
return rdd.map(func)
@exeTime
def properties(labeled_stack, image_stack, min_radius, max_radius):
prop = []
columns = ('x', 'y', 'z', 'intensitysum', 'size', 'tag')
indices = []
end = len(labeled_stack)
for z, frame in enumerate(labeled_stack):
msg = " get the properties of the %d-th" % (z+1)
<|code_end|>
, determine the next line of code. You have imports:
from MEHI.utils.tool import exeTime, bar, log
from skimage.filters import threshold_otsu, threshold_adaptive
from MEHI.udf._phansalkar import phansalkar as _phansalkar
from skimage.morphology import disk, binary_opening, remove_small_objects
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from skimage.measure import regionprops
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from MEHI.udf._moment import moment
from scipy import ndimage as ndi
import numpy as np
import scipy.ndimage as ndi
import scipy.ndimage as ndi
import pandas as pd
import scipy.cluster.hierarchy as hier
import pandas as pd
and context (class names, function names, or code) available:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def bar(level):
# '''
# Usage:
# - this will show a progress bar
# - e.g. bar('info')(msg, i, 100)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg, i, end):
# if i <= end:
# sys.stdout.write('[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] ('+ str(i)+'/' + str(end) + ') '+ msg + '\r')
# sys.stdout.flush()
# if i == end:
# print
# return wraper
# else:
# def wraper(msg, i, end):
# pass
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | bar("info")(msg,z+1,end)
|
Using the snippet: <|code_start|>@exeTime
def properties(labeled_stack, image_stack, min_radius, max_radius):
prop = []
columns = ('x', 'y', 'z', 'intensitysum', 'size', 'tag')
indices = []
end = len(labeled_stack)
for z, frame in enumerate(labeled_stack):
msg = " get the properties of the %d-th" % (z+1)
bar("info")(msg,z+1,end)
f_prop = regionprops(frame.astype(np.int),
intensity_image = image_stack[z])
for d in f_prop:
radius = (d.area / np.pi)**0.5
if(min_radius < radius < max_radius):
prop.append([d.weighted_centroid[0],
d.weighted_centroid[1],
z,d.mean_intensity*d.area,
radius,
d.label])
indices.append(d.label)
if not len(indices):
all_props = pd.DataFrame([], index=[])
indices = pd.Index(indices, name='label')
prop = pd.DataFrame(prop, index=indices, columns=columns)
prop['intensitysum'] /= prop['intensitysum'].sum()
return prop
@exeTime
def clustering(prop, threshold):
<|code_end|>
, determine the next line of code. You have imports:
from MEHI.utils.tool import exeTime, bar, log
from skimage.filters import threshold_otsu, threshold_adaptive
from MEHI.udf._phansalkar import phansalkar as _phansalkar
from skimage.morphology import disk, binary_opening, remove_small_objects
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from skimage.measure import regionprops
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from skimage.feature import peak_local_max
from MEHI.udf._moment import moment
from scipy import ndimage as ndi
import numpy as np
import scipy.ndimage as ndi
import scipy.ndimage as ndi
import pandas as pd
import scipy.cluster.hierarchy as hier
import pandas as pd
and context (class names, function names, or code) available:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def bar(level):
# '''
# Usage:
# - this will show a progress bar
# - e.g. bar('info')(msg, i, 100)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg, i, end):
# if i <= end:
# sys.stdout.write('[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] ('+ str(i)+'/' + str(end) + ') '+ msg + '\r')
# sys.stdout.flush()
# if i == end:
# print
# return wraper
# else:
# def wraper(msg, i, end):
# pass
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | log("info")("clustering start...")
|
Given the following code snippet before the placeholder: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 20:08:44
# FileName : test_p_fusion.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side/'
R_pwd = os.path.abspath('.') + '/test_data/R_side/'
class PySparkTestFusionCase(PySparkTestCase):
def setUp(self):
super(PySparkTestFusionCase, self).setUp()
<|code_end|>
, predict the next line using imports from the current file:
from MEHI.paralleled.fusion import *
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
import numpy as np
import os
and context including class names, function names, and sometimes code from other files:
# Path: MEHI/paralleled/IO.py
# @exeTime
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# n = len(names)
# def func(name):
# img_pwd = os.path.join(pwd, name)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# return img
# rdd_file = sc.parallelize(names)
# return np.squeeze(np.array(rdd_file.map(func).collect()))
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(self.sc, L_pwd) |
Given the code snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/CNN_data'
s = time.time()
log('info')('load tiff ...')
sub = IO.load_tiff(sc, pwd+'/train_n.tif')
log('info')('tiff load over ...')
rdd = sc.parallelize(sub)
#log('info')('subtract_Background ...')
#rdd = prep.subtract_Background(rdd, size=15)
#rdd = prep.invert(rdd)
#rdd = prep.subtract_Background(rdd, size=12)
#sub = np.array(rdd.collect())
#IO.save_tiff(sub, pwd+'/train_n.tif')
log('info')('preprocess ...')
#rdd = prep.saturation(rdd, 0.01)
<|code_end|>
, generate the next line using the imports in this file:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context (functions, classes, or occasionally code) from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | rdd = prep.intensity_normalization(rdd, 8) |
Continue the code snippet: <|code_start|>################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/CNN_data'
s = time.time()
log('info')('load tiff ...')
sub = IO.load_tiff(sc, pwd+'/train_n.tif')
log('info')('tiff load over ...')
rdd = sc.parallelize(sub)
#log('info')('subtract_Background ...')
#rdd = prep.subtract_Background(rdd, size=15)
#rdd = prep.invert(rdd)
#rdd = prep.subtract_Background(rdd, size=12)
#sub = np.array(rdd.collect())
#IO.save_tiff(sub, pwd+'/train_n.tif')
log('info')('preprocess ...')
#rdd = prep.saturation(rdd, 0.01)
rdd = prep.intensity_normalization(rdd, 8)
rdd = prep.smooth(rdd, 4)
log('info')('preprocess over ...')
log('info')('threshold start ...')
<|code_end|>
. Use current file imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context (classes, functions, or code) from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | rdd = seg.threshold(rdd,'otsu') |
Here is a snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/CNN_data'
s = time.time()
log('info')('load tiff ...')
<|code_end|>
. Write the next line using the current file imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
, which may include functions, classes, or code. Output only the next line. | sub = IO.load_tiff(sc, pwd+'/train_n.tif') |
Given the following code snippet before the placeholder: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/CNN_data'
s = time.time()
<|code_end|>
, predict the next line using imports from the current file:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context including class names, function names, and sometimes code from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | log('info')('load tiff ...') |
Based on the snippet: <|code_start|> return binary
def otsu(frame):
threshold = threshold_otsu(frame)
binary = frame > threshold
return binary
def duel(frame):
threshold = threshold_otsu(frame)
binary1 = frame > threshold
frame = frame - binary1 * frame
threshold = threshold_otsu(frame)
binary2 = frame > threshold
binary = binary1 & binary2
return binary
if method=='adaptive':
block_size = args[0]
return np.array(map(adaptive, img_stack))
elif method == 'otsu':
return np.array(map(otsu, img_stack))
elif method == 'duel':
return np.array(map(duel, img_stack))
else:
raise "Bad Threshold Method", method
def peak_filter(image_stack, smooth_size):
def func(frame):
opened = binary_opening(frame, disk(smooth_size))
opened = opened & frame
return opened
return np.array(map(func, img_stack))
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.utils.tool import exeTime
from skimage.filters import threshold_otsu, threshold_adaptive
from skimage.morphology import disk, binary_opening
from skimage.feature import peak_local_max
from skimage.morphology import watershed, remove_small_objects
from scipy import ndimage
from MEHI.udf._moment import moment
from scipy import ndimage as ndi
import numpy as np
import scipy.ndimage as ndi
import pandas as pd
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
. Output only the next line. | @exeTime |
Using the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 18:56:05
# FileName : test_p_registration.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class PySparkTestRegistrationCase(PySparkTestCase):
def setUp(self):
super(PySparkTestRegistrationCase, self).setUp()
self.L_imgs = load_tiff(self.sc, L_pwd)
self.R_imgs = load_tiff(self.sc, R_pwd)
self.imgA = self.L_imgs[0]
<|code_end|>
, determine the next line of code. You have imports:
from MEHI.paralleled.registration import *
from MEHI.serial.preprocess import flip
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
from nose.tools import assert_equals
import numpy as np
import os
and context (class names, function names, or code) available:
# Path: MEHI/serial/preprocess.py
# @exeTime
# def flip(img_stack):
# def func(frame):
# return frame[:,::-1]
# return np.array(map(func, img_stack))
#
# Path: MEHI/paralleled/IO.py
# @exeTime
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# n = len(names)
# def func(name):
# img_pwd = os.path.join(pwd, name)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# return img
# rdd_file = sc.parallelize(names)
# return np.squeeze(np.array(rdd_file.map(func).collect()))
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.imgB = flip(self.R_imgs)[0] |
Continue the code snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 18:56:05
# FileName : test_p_registration.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class PySparkTestRegistrationCase(PySparkTestCase):
def setUp(self):
super(PySparkTestRegistrationCase, self).setUp()
<|code_end|>
. Use current file imports:
from MEHI.paralleled.registration import *
from MEHI.serial.preprocess import flip
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
from nose.tools import assert_equals
import numpy as np
import os
and context (classes, functions, or code) from other files:
# Path: MEHI/serial/preprocess.py
# @exeTime
# def flip(img_stack):
# def func(frame):
# return frame[:,::-1]
# return np.array(map(func, img_stack))
#
# Path: MEHI/paralleled/IO.py
# @exeTime
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# n = len(names)
# def func(name):
# img_pwd = os.path.join(pwd, name)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# return img
# rdd_file = sc.parallelize(names)
# return np.squeeze(np.array(rdd_file.map(func).collect()))
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(self.sc, L_pwd) |
Continue the code snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 19:02:34
# FileName : test_registration.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class LocalTestRegistrationCase(LocalTestCase):
def setUp(self):
super(LocalTestRegistrationCase, self).setUp()
self.L_imgs = load_tiff(L_pwd)
self.R_imgs = load_tiff(R_pwd)
self.imgA = self.L_imgs[0]
<|code_end|>
. Use current file imports:
from MEHI.serial.registration import *
from MEHI.serial.preprocess import flip
from MEHI.serial.IO import load_tiff
from test_utils import LocalTestCase
from nose.tools import assert_equals
import numpy as np
import os
and context (classes, functions, or code) from other files:
# Path: MEHI/serial/preprocess.py
# @exeTime
# def flip(img_stack):
# def func(frame):
# return frame[:,::-1]
# return np.array(map(func, img_stack))
#
# Path: MEHI/serial/IO.py
# @exeTime
# def load_tiff(pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# for z,imgname in enumerate(names):
# msg = "reading %d-th frame" % (z+1)
# end = len(names)
# bar('info')(msg, z+1, end)
# img_pwd = os.path.join(pwd, imgname)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# img_stack.append(img)
# return np.array(img_stack)
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.imgB = flip(self.R_imgs)[0] |
Based on the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 19:02:34
# FileName : test_registration.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class LocalTestRegistrationCase(LocalTestCase):
def setUp(self):
super(LocalTestRegistrationCase, self).setUp()
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.serial.registration import *
from MEHI.serial.preprocess import flip
from MEHI.serial.IO import load_tiff
from test_utils import LocalTestCase
from nose.tools import assert_equals
import numpy as np
import os
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/serial/preprocess.py
# @exeTime
# def flip(img_stack):
# def func(frame):
# return frame[:,::-1]
# return np.array(map(func, img_stack))
#
# Path: MEHI/serial/IO.py
# @exeTime
# def load_tiff(pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# for z,imgname in enumerate(names):
# msg = "reading %d-th frame" % (z+1)
# end = len(names)
# bar('info')(msg, z+1, end)
# img_pwd = os.path.join(pwd, imgname)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# img_stack.append(img)
# return np.array(img_stack)
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(L_pwd) |
Using the snippet: <|code_start|> tx, ty, sita, sx, sy, hx, hy= tuple(vec)
A = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
B = np.array([[math.cos(sita), -math.sin(sita), 0], [math.sin(sita), math.cos(sita), 0], [0, 0, 1]])
C = np.array([[sx, 0, 0], [0, sy, 0], [0, 0, 1]])
D = np.array([[1, hx, 0], [0, 1, 0], [0, 0, 1]])
E = np.array([[1, 0, 0], [hy, 1 , 0], [0, 0, 1]])
F = np.dot(np.dot(A,B),C)
return np.dot(np.dot(F,D),E)
def _update(vec, imgA, imgB):
H = _generate_H(imgA, imgB)
_H = H.copy()
_X, _Y = imgA.shape
U = _get_trans(vec)
for i in range(_X):
for j in range(_Y):
p = np.array([i,j,1])
q = np.dot(U, p)
p = (p[0],p[1])
q = (q[0],q[1])
_PV_interpolation(_H, p, q, imgA, imgB)
return _mutual_info(_H)
def _trans(frame, vec):
frame = frame.copy(order='C')
ret = np.zeros_like(frame)
U = _get_trans(vec)
trans(frame, U, ret)
return ret
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import math
import scipy.optimize as sciop
import scipy.optimize as sciop
from MEHI.utils.tool import exeTime
from MEHI.udf._trans import trans
from MEHI.udf._update import update
from skimage.feature import register_translation
from scipy.ndimage import fourier_shift
and context (class names, function names, or code) available:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
. Output only the next line. | @exeTime
|
Predict the next line for this snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 18:56:01
# FileName : test_p_preprocess.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side/'
R_pwd = os.path.abspath('.') + '/test_data/R_side/'
class PySparkTestPreprocessCase(PySparkTestCase):
def setUp(self):
super(PySparkTestPreprocessCase, self).setUp()
<|code_end|>
with the help of current file imports:
from MEHI.paralleled.preprocess import *
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
import numpy as np
import os
and context from other files:
# Path: MEHI/paralleled/IO.py
# @exeTime
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# n = len(names)
# def func(name):
# img_pwd = os.path.join(pwd, name)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# return img
# rdd_file = sc.parallelize(names)
# return np.squeeze(np.array(rdd_file.map(func).collect()))
# else:
# return tiff.imread(pwd)
, which may contain function names, class names, or code. Output only the next line. | self.L_imgs = load_tiff(self.sc, L_pwd) |
Based on the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
log('info')('load tiff ...')
sub_img = IO.load_tiff(pwd+'/sub_dev/')
log('info')('tiff load over ...')
rdd = sc.parallelize(sub_img)
log('info')('preprocess ...')
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | rdd = prep.saturation(rdd, 0.01) |
Using the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
log('info')('load tiff ...')
sub_img = IO.load_tiff(pwd+'/sub_dev/')
log('info')('tiff load over ...')
rdd = sc.parallelize(sub_img)
log('info')('preprocess ...')
rdd = prep.saturation(rdd, 0.01)
rdd = prep.intensity_normalization(rdd)
#rdd = prep.smooth(rdd, 4)
log('info')('preprocess over ...')
log('info')('threshold start ...')
<|code_end|>
, determine the next line of code. You have imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context (class names, function names, or code) available:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | rdd = seg.threshold(rdd, 'phansalkar', 20) |
Based on the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
log('info')('load tiff ...')
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | sub_img = IO.load_tiff(pwd+'/sub_dev/') |
Here is a snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
<|code_end|>
. Write the next line using the current file imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
, which may include functions, classes, or code. Output only the next line. | log('info')('load tiff ...') |
Predict the next line after this snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/30 15:15:42
# FileName : test_p_segmentation.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class PySparkTestSegmentationCase(PySparkTestCase):
def setUp(self):
super(PySparkTestSegmentationCase, self).setUp()
<|code_end|>
using the current file's imports:
from MEHI.paralleled.segmentation import *
from MEHI.paralleled.IO import load_tiff
from test_utils import PySparkTestCase
from nose.tools import assert_equals
import numpy as np
import os
and any relevant context from other files:
# Path: MEHI/paralleled/IO.py
# @exeTime
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# n = len(names)
# def func(name):
# img_pwd = os.path.join(pwd, name)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# return img
# rdd_file = sc.parallelize(names)
# return np.squeeze(np.array(rdd_file.map(func).collect()))
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(self.sc, L_pwd) |
Here is a snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
log('info')('load tiff ...')
<|code_end|>
. Write the next line using the current file imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and context from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
, which may include functions, classes, or code. Output only the next line. | sub_img = IO.load_tiff(pwd+'/sub_dev/') |
Predict the next line after this snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/31 16:54:41
# FileName : seg.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[64]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
<|code_end|>
using the current file's imports:
from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.serial import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time
and any relevant context from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/serial/IO.py
# def load_tiff(pwd, start_index=None, end_index=None):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
# def load_mha(fn):
# def _cast2int (l):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | log('info')('load tiff ...') |
Based on the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 15:38:36
# FileName : test_fusion.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side/'
R_pwd = os.path.abspath('.') + '/test_data/R_side/'
class LocalTestFusionCase(LocalTestCase):
def setUp(self):
super(LocalTestFusionCase, self).setUp()
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.serial.fusion import *
from MEHI.serial.IO import load_tiff
from test_utils import LocalTestCase
import numpy as np
import os,sys
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/serial/IO.py
# @exeTime
# def load_tiff(pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# for z,imgname in enumerate(names):
# msg = "reading %d-th frame" % (z+1)
# end = len(names)
# bar('info')(msg, z+1, end)
# img_pwd = os.path.join(pwd, imgname)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# img_stack.append(img)
# return np.array(img_stack)
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(L_pwd) |
Predict the next line after this snippet: <|code_start|> - change the circle to pie
Args:
- size: the smooth size
'''
def func(frame):
return mor.black_tophat(frame, mor.disk(size))
return rdd.map(func)
def subtract_Background(rdd, size=12):
'''
Usage:
- subtrackt Background (based on C)
args:
- radius: the smooth size
'''
def func(frame):
return subtract_Background(frame, size)
return rdd.map(func)
def shrink(rdd, shrink_size=2):
def func(frame):
_X,_Y = frame.shape
_sX, _sY = _X / shrink_size, _Y / shrink_size
shrink_frame = np.zeros([_sX,_sY])
for i in range(_sX):
for j in range(_sY):
shrink_frame[i][j] = sum(frame[i*shrink_size:(i+1)*shrink_size,j*shrink_size:(j+1)*shrink_size].flatten()) / (shrink_size*shrink_size)
return shrink_frame.astype(frame.dtype)
return rdd.map(func)
<|code_end|>
using the current file's imports:
import skimage.external.tifffile as tiff
import numpy as np
import math
import skimage.morphology as mor
import skimage.morphology as mor
from MEHI.utils.tool import exeTime
from MEHI.udf._intensity import normalization
from MEHI.udf._intensity import saturation
from MEHI.udf._subtract_bg import subtract_Background
from skimage.morphology import disk
from skimage.filters import rank
and any relevant context from other files:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
. Output only the next line. | @exeTime
|
Predict the next line for this snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/25 10:44:53
# FileName : IO.py
################################
@exeTime
def load_tiff(pwd, start_index=None, end_index=None):
'''
Usage:
- just read all the image under the pwd
'''
if os.path.isdir(pwd):
img_stack = []
names = []
for imgname in os.listdir(pwd):
if imgname.endswith('.tif'):
names.append(imgname)
names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
names = names[start_index:end_index]
for z,imgname in enumerate(names):
msg = "reading %d-th frame" % (z+1)
end = len(names)
<|code_end|>
with the help of current file imports:
import skimage.external.tifffile as tiff
import numpy as np
import os
import pandas as pd
import pandas as pd
import zlib
from MEHI.utils.tool import exeTime,bar
and context from other files:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def bar(level):
# '''
# Usage:
# - this will show a progress bar
# - e.g. bar('info')(msg, i, 100)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg, i, end):
# if i <= end:
# sys.stdout.write('[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] ('+ str(i)+'/' + str(end) + ') '+ msg + '\r')
# sys.stdout.flush()
# if i == end:
# print
# return wraper
# else:
# def wraper(msg, i, end):
# pass
# return wraper
, which may contain function names, class names, or code. Output only the next line. | bar('info')(msg, z+1, end) |
Next line prediction: <|code_start|>################################
# Author : septicmk
# Date : 2015/08/17 11:13:23
# FileName : test.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[128]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
log('info')('load tiff ...')
<|code_end|>
. Use current file imports:
(from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time)
and context including class names, function names, or small code snippets from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | fus = IO.load_tiff(sc, pwd+'/fus_dev/') |
Next line prediction: <|code_start|>################################
# Author : septicmk
# Date : 2015/08/17 11:13:23
# FileName : test.py
################################
conf = SparkConf().setAppName('seg').setMaster('local[128]').set('spark.executor.memory','20g').set('spark.driver.maxResultSize','20g').set('spark.driver.memory','40g').set('spark.local.dir','/dev/shm').set('spark.storage.memoryFraction','0.2').set('spark.default.parallelism','256')
sc = SparkContext(conf=conf)
pwd = '/mnt/xfs_snode21/0401fusion'
s = time.time()
<|code_end|>
. Use current file imports:
(from MEHI.paralleled import preprocess as prep
from MEHI.paralleled import segmentation as seg
from MEHI.paralleled import IO
from MEHI.utils.tool import exeTime, log
from pyspark import SparkContext, SparkConf
import numpy as np
import time)
and context including class names, function names, or small code snippets from other files:
# Path: MEHI/paralleled/preprocess.py
# def stripe_removal(rdd):
# def func(frame):
# def intensity_normalization(rdd, dtype=None):
# def func(frame):
# def saturation(rdd, precent):
# def func(frame):
# def flip(rdd):
# def func(frame):
# def invert(rdd):
# def func(frame):
# def black_tophat(rdd, size=15):
# def func(frame):
# def subtract_Background(rdd, size=12):
# def func(frame):
# def shrink(rdd, shrink_size=2):
# def func(frame):
# def projection(img_stack, method='max'):
# def smooth(rdd, smooth_size):
# def func(frame):
# def blockshaped_all(img_stack, nrows, ncols):
# def blockshaped(arr, nrows, ncols):
# def recovershape_all(img_stack, nrows, ncols):
# def recovershape(arr_list, nrows, ncols):
# _X,_Y = frame.shape
#
# Path: MEHI/paralleled/segmentation.py
# def threshold(rdd, method='adaptive', *args):
# def adaptive(frame):
# def otsu(frame):
# def duel(frame):
# def phansalkar(frame):
# def peak_filter(rdd, smooth_size):
# def func(frame):
# def watershed(rdd, min_radius):
# def func(dframe):
# def properties(labeled_stack, image_stack, min_radius, max_radius):
# def clustering(prop, threshold):
# def df_average(df, weights_column):
# def fusion(labeled_stack, image_stack, min_radius, max_radius):
# def debug(labeled_stack, image_stack, min_radius, max_radiusm, prop):
# def watershed_3d(image_stack, binary, min_distance=10, min_radius=6):
# def properties_3d(labeled_stack):
#
# Path: MEHI/paralleled/IO.py
# def load_tiff(sc, pwd, start_index=None, end_index=None):
# def func(name):
# def save_tiff(img_stack, pwd):
# def load_table(pwd):
# def save_table(tab, pwd):
#
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
#
# def log(level):
# '''
# Usage:
# - this will just show info
# - e.g. log('info')(msg)
# '''
# from MEHI.utils.configuration import loglevel
# if level in loglevel:
# def wraper(msg):
# print '[' + bcolors.decode(level) + level + bcolors.decode('endc') + '] '+ msg
# return wraper
# else:
# def wraper(msg):
# pass
# return wraper
. Output only the next line. | log('info')('load tiff ...') |
Here is a snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/24 15:39:02
# FileName : test_preprocess.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side/'
R_pwd = os.path.abspath('.') + '/test_data/R_side/'
class LocalTestPreprocessCase(LocalTestCase):
def setUp(self):
super(LocalTestPreprocessCase, self).setUp()
<|code_end|>
. Write the next line using the current file imports:
from MEHI.serial.preprocess import *
from MEHI.serial.IO import load_tiff
from test_utils import LocalTestCase
import numpy as np
import os
and context from other files:
# Path: MEHI/serial/IO.py
# @exeTime
# def load_tiff(pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# for z,imgname in enumerate(names):
# msg = "reading %d-th frame" % (z+1)
# end = len(names)
# bar('info')(msg, z+1, end)
# img_pwd = os.path.join(pwd, imgname)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# img_stack.append(img)
# return np.array(img_stack)
# else:
# return tiff.imread(pwd)
, which may include functions, classes, or code. Output only the next line. | self.L_imgs = load_tiff(L_pwd) |
Using the snippet: <|code_start|> tx, ty, sita, sx, sy, hx, hy= tuple(vec)
A = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
B = np.array([[math.cos(sita), -math.sin(sita), 0], [math.sin(sita), math.cos(sita), 0], [0, 0, 1]])
C = np.array([[sx, 0, 0], [0, sy, 0], [0, 0, 1]])
D = np.array([[1, hx, 0], [0, 1, 0], [0, 0, 1]])
E = np.array([[1, 0, 0], [hy, 1 , 0], [0, 0, 1]])
F = np.dot(np.dot(A,B),C)
return np.dot(np.dot(F,D),E)
def _update(vec, imgA, imgB):
H = _generate_H(imgA, imgB)
_H = H.copy()
_X, _Y = imgA.shape
U = _get_trans(vec)
for i in range(_X):
for j in range(_Y):
p = np.array([i,j,1])
q = np.dot(U, p)
p = (p[0],p[1])
q = (q[0],q[1])
_PV_interpolation(_H, p, q, imgA, imgB)
return _mutual_info(_H)
def _trans(frame, vec):
frame = frame.copy(order='C')
ret = np.zeros_like(frame)
U = _get_trans(vec)
trans(frame, U, ret)
return ret
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import math
import scipy.optimize as sciop
import scipy.optimize as sciop
from MEHI.utils.tool import exeTime
from MEHI.udf._trans import trans
from MEHI.udf._update import update
from skimage.feature import register_translation
from scipy.ndimage import fourier_shift
and context (class names, function names, or code) available:
# Path: MEHI/utils/tool.py
# def exeTime(func):
# '''
# Usage:
# - just put '@exeTime'(with out quotation) before your function
# - will show the running time
# '''
# import time
# def wraper(*args, **args2):
# s = time.time()
# ret = func(*args, **args2)
# e = time.time()
# msg = "%3.3fs taken for {%s}" % (e-s, func.__name__)
# log('time')(msg)
# return ret
# return wraper
. Output only the next line. | @exeTime
|
Based on the snippet: <|code_start|>################################
# Author : septicmk
# Date : 2015/07/30 15:30:35
# FileName : test_segmentation.py
################################
L_pwd = os.path.abspath('.') + '/test_data/L_side_8/'
R_pwd = os.path.abspath('.') + '/test_data/R_side_8/'
class LocalTestSegmentationCase(LocalTestCase):
def setUp(self):
super(LocalTestSegmentationCase, self).setUp()
<|code_end|>
, predict the immediate next line with the help of imports:
from MEHI.serial.segmentation import *
from MEHI.serial.IO import load_tiff
from test_utils import LocalTestCase
from nose.tools import assert_equals
import numpy as np
import os
and context (classes, functions, sometimes code) from other files:
# Path: MEHI/serial/IO.py
# @exeTime
# def load_tiff(pwd, start_index=None, end_index=None):
# '''
# Usage:
# - just read all the image under the pwd
# '''
# if os.path.isdir(pwd):
# img_stack = []
# names = []
# for imgname in os.listdir(pwd):
# if imgname.endswith('.tif'):
# names.append(imgname)
# names = sorted(names, key = lambda x: int(filter(str.isdigit, x)))
# if (start_index) and (end_index) and (0 <= start_index < end_index) and (start_index < end_index <= len(names)):
# names = names[start_index:end_index]
# for z,imgname in enumerate(names):
# msg = "reading %d-th frame" % (z+1)
# end = len(names)
# bar('info')(msg, z+1, end)
# img_pwd = os.path.join(pwd, imgname)
# if img_pwd.endswith('.tif'):
# img = tiff.imread(img_pwd)
# img_stack.append(img)
# return np.array(img_stack)
# else:
# return tiff.imread(pwd)
. Output only the next line. | self.L_imgs = load_tiff(L_pwd) |
Continue the code snippet: <|code_start|> return np.array(y)
def curvature(x):
"""Curvature of a timeseries
This test is commonly known as gradient for historical reasons, but that
is a bad name choice since it is not the actual gradient, like:
d/dx + d/dy + d/dz,
but as defined by GTSPP, EuroGOOS and others, which is actually the
curvature of the timeseries..
Note
----
- Pandas.Series operates with indexes, so it should be done different. In
that case, call for _curvature_pandas.
"""
if isinstance(x, ma.MaskedArray):
x[x.mask] = np.nan
x = x.data
if PANDAS_AVAILABLE and isinstance(x, pd.Series):
return _curvature_pandas(x)
x = np.atleast_1d(x)
y = np.nan * x
y[1:-1] = x[1:-1] - (x[:-2] + x[2:]) / 2.0
return y
<|code_end|>
. Use current file imports:
import logging
import numpy as np
import pandas as pd
from numpy import ma
from cotede.qctests import QCCheckVar
and context (classes, functions, or code) from other files:
# Path: cotede/qctests/core.py
# class QCCheckVar(QCCheck):
# """Template for a QC check of a specific variable
# """
#
# def __init__(self, data, varname, cfg=None, autoflag=True, attrs=None):
# self.varname = varname
# super().__init__(data=data, cfg=cfg, autoflag=autoflag, attrs=attrs)
. Output only the next line. | class Gradient(QCCheckVar): |
Predict the next line after this snippet: <|code_start|> "low": {"type": "trimf", "params": [0.0, 0.225, 0.45]},
"medium": {"type": "trimf", "params": [0.275, 0.5, 0.725]},
"high": {"type": "smf", "params": [0.55, 0.775]},
},
"features": {
"f1": {
"weight": 1,
"low": {"type": "zmf", "params": [0.07, 0.2]},
"medium": {"type": "trapmf", "params": [0.07, 0.2, 2, 6]},
"high": {"type": "smf", "params": [2, 6]},
},
"f2": {
"weight": 1,
"low": {"type": "zmf", "params": [3, 4]},
"medium": {"type": "trapmf", "params": [3, 4, 5, 6]},
"high": {"type": "smf", "params": [5, 6]},
},
"f3": {
"weight": 1,
"low": {"type": "zmf", "params": [0.5, 1.5]},
"medium": {"type": "trapmf", "params": [0.5, 1.5, 3, 4]},
"high": {"type": "smf", "params": [3, 4]},
},
},
}
def test_fuzzyfy():
features = {"f1": np.array([1.0]), "f2": np.array([5.2]), "f3": np.array([0.9])}
<|code_end|>
using the current file's imports:
import numpy as np
from numpy.testing import assert_allclose
from cotede.fuzzy import fuzzyfy
and any relevant context from other files:
# Path: cotede/fuzzy/fuzzy_core.py
# def fuzzyfy(data, features, output, require="all"):
# """
# Notes
# -----
# In the generalize this once the membership combining rules are defined
# in the cfg, so I can decide to use mean or max.
# """
# features_list = list(features.keys())
#
# N = max([len(data[f]) for f in features_list])
#
# # The fuzzy set are usually: low, medium, high
# # The membership of each fuzzy set are each feature scaled.
# membership = {f: {} for f in output.keys()}
#
# mfuncs = {"smf": smf, "trimf": trimf, "trapmf": trapmf, "zmf": zmf}
# for t in features_list:
# for m in membership:
# assert m in features[t], "Missing %s in %s" % (m, features[t])
# f = mfuncs[features[t][m]["type"]]
# membership[m][t] = f(np.asanyarray(data[t]), features[t][m]["params"])
#
# # Rule Set
# rules = {}
# # Low: u_low = mean(S_l(spike), S_l(clim)...)
# # u_low = np.mean([weights['spike']['low'],
# # weights['woa_relbias']['low']], axis=0)
# # Medium: u_medium = mean(S_l(spike), S_l(clim)...)
# # u_medium = np.mean([weights['spike']['medium'],
# # weights['woa_relbias']['medium']], axis=0)
#
# for m in [m for m in membership if m != "high"]:
# tmp = np.vstack([membership[m][f] for f in membership[m]])
# if require == "any":
# rules[m] = np.nanmean(tmp, axis=0)
# else:
# rules[m] = np.mean(tmp, axis=0)
#
# # High: u_high = max(S_l(spike), S_l(clim)...)
# # u_high = np.max([weights['spike']['high'],
# # weights['woa_relbias']['high']], axis=0)
#
# tmp = np.vstack([membership["high"][f] for f in membership["high"]])
# if require == "any":
# rules["high"] = np.nanmax(tmp, axis=0)
# else:
# rules["high"] = np.max(tmp, axis=0)
#
# return rules
. Output only the next line. | rules = fuzzyfy(features, **CFG) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
module_logger = logging.getLogger(__name__)
try:
except ImportError:
module_logger.debug("Module Shapely is not available")
<|code_end|>
with the help of current file imports:
import logging
import numpy as np
import shapely.wkt
import shapely
from numpy import ma
from .qctests import QCCheckVar
from shapely.geometry import Point
and context from other files:
# Path: cotede/qctests/qctests.py
# def frozen_profile():
# def grey_list():
# def valid_speed():
# def gross_sensor_drift():
# def platform_identification():
, which may contain function names, class names, or code. Output only the next line. | class RegionalRange(QCCheckVar): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
"""
module_logger = logging.getLogger(__name__)
class SpikeDepthConditional(QCCheckVar):
def set_features(self):
<|code_end|>
, generate the next line using the imports in this file:
import logging
import numpy as np
from numpy import ma
from .qctests import QCCheckVar
from .spike import spike
and context (functions, classes, or occasionally code) from other files:
# Path: cotede/qctests/qctests.py
# def frozen_profile():
# def grey_list():
# def valid_speed():
# def gross_sensor_drift():
# def platform_identification():
#
# Path: cotede/qctests/spike.py
# def spike(x):
# """ Spike
# """
# if isinstance(x, ma.MaskedArray):
# x[x.mask] = np.nan
# x = x.data
#
# x = np.atleast_1d(x)
# y = np.nan * x
# y[1:-1] = np.abs(x[1:-1] - (x[:-2] + x[2:]) / 2.0) - np.abs((x[2:] - x[:-2]) / 2.0)
# return y
. Output only the next line. | self.features = {"spike": spike(self.data[self.varname])} |
Given the following code snippet before the placeholder: <|code_start|>
if (RoC_small (t) + 0.5 × RoC_medium (t)) < (cRoC_small (t - 1) + 0.5 × cRoC_medium (t - 1)):
cRoC_i (t) = RoC_i (t)
else
cRoC_i (t) = (1 - k) × RoC_i(t) + k * cRoC_i(t - 1)
i = small, medium, large
"""
module_logger = logging.getLogger(__name__)
def cum_rate_of_change(x, memory):
"""Cummulative rate of change
"""
if isinstance(x, ma.MaskedArray):
x[x.mask] = np.nan
x = x.data
y = np.nan * np.ones_like(x)
y[1:] = np.absolute(np.diff(x))
for i in range(2, y.size):
if y[i] < y[i - 1]:
y[i] = (1 - memory) * y[i] + memory * y[i - 1]
return y
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import logging
from numpy import ma
from .qctests import QCCheckVar
and context including class names, function names, and sometimes code from other files:
# Path: cotede/qctests/qctests.py
# def frozen_profile():
# def grey_list():
# def valid_speed():
# def gross_sensor_drift():
# def platform_identification():
. Output only the next line. | class CumRateOfChange(QCCheckVar): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.