Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|> ) # noqa
return real_extract
def hydrometer_adjustment(sg, temp, units=IMPERIAL_UNITS):
"""
Adjust the Hydrometer if the temperature deviates from 59degF.
:param float sg: Specific Gravity
:param float temp: Temperature
:param str units: The units
:return: Specific Gravity corrected for temperature
:rtype: float
:raises SugarException: If temperature outside freezing to boiling range of water
The correction formula is from Lyons (1992), who used the following formula
to fit data from the Handbook of Chemistry and Physics (CRC):
:math:`\\text{Correction(@59F)} = 1.313454 - 0.132674 \\times T + 2.057793e^{-3} \\times T^2 - 2.627634e^{-6} \\times T^3`
where T is in degrees F.
Sources:
* http://www.topdownbrew.com/SGCorrection.html
* http://hbd.org/brewery/library/HydromCorr0992.html
* http://www.brewersfriend.com/hydrometer-temp/
* http://www.primetab.com/formulas.html
""" # noqa
validate_units(units)
<|code_end|>
with the help of current file imports:
from ..constants import HYDROMETER_ADJUSTMENT_TEMP
from ..constants import IMPERIAL_UNITS
from ..constants import SI_UNITS
from ..exceptions import SugarException
from ..validators import validate_units
from .temperature import celsius_to_fahrenheit
and context from other files:
# Path: brew/constants.py
# HYDROMETER_ADJUSTMENT_TEMP = 59.0
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class SugarException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
#
# Path: brew/utilities/temperature.py
# def celsius_to_fahrenheit(temp):
# """
# Convert degrees Celsius to degrees Fahrenheit
#
# :param float temp: The temperature in Celsius
# :return: The temperature in Fahrenheit
# :rtype: float
# """
# return (temp * 1.8) + 32.0
, which may contain function names, class names, or code. Output only the next line. | if units == SI_UNITS: |
Given snippet: <|code_start|>
def brix_to_sg(brix):
"""
Degrees Brix to Specific Gravity
:param float brix: Degrees Brix
:return: Specific Gravity
:rtype: float
Source:
* http://www.brewersfriend.com/brix-converter/
"""
return (brix / (258.6 - ((brix / 258.2) * 227.1))) + 1
def sg_to_brix(sg):
"""
Specific Gravity to Degrees Brix
:param float sg: Specific Gravity
:return: Degrees Brix
:rtype: float
Source:
* http://en.wikipedia.org/wiki/Brix
* http://www.brewersfriend.com/brix-converter/
"""
if sg > 1.17874:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..constants import HYDROMETER_ADJUSTMENT_TEMP
from ..constants import IMPERIAL_UNITS
from ..constants import SI_UNITS
from ..exceptions import SugarException
from ..validators import validate_units
from .temperature import celsius_to_fahrenheit
and context:
# Path: brew/constants.py
# HYDROMETER_ADJUSTMENT_TEMP = 59.0
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class SugarException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
#
# Path: brew/utilities/temperature.py
# def celsius_to_fahrenheit(temp):
# """
# Convert degrees Celsius to degrees Fahrenheit
#
# :param float temp: The temperature in Celsius
# :return: The temperature in Fahrenheit
# :rtype: float
# """
# return (temp * 1.8) + 32.0
which might include code, classes, or functions. Output only the next line. | raise SugarException(u"Above 40 degBx this function no longer works") |
Given snippet: <|code_start|> 1 + attenuation_coeff
) # noqa
return real_extract
def hydrometer_adjustment(sg, temp, units=IMPERIAL_UNITS):
"""
Adjust the Hydrometer if the temperature deviates from 59degF.
:param float sg: Specific Gravity
:param float temp: Temperature
:param str units: The units
:return: Specific Gravity corrected for temperature
:rtype: float
:raises SugarException: If temperature outside freezing to boiling range of water
The correction formula is from Lyons (1992), who used the following formula
to fit data from the Handbook of Chemistry and Physics (CRC):
:math:`\\text{Correction(@59F)} = 1.313454 - 0.132674 \\times T + 2.057793e^{-3} \\times T^2 - 2.627634e^{-6} \\times T^3`
where T is in degrees F.
Sources:
* http://www.topdownbrew.com/SGCorrection.html
* http://hbd.org/brewery/library/HydromCorr0992.html
* http://www.brewersfriend.com/hydrometer-temp/
* http://www.primetab.com/formulas.html
""" # noqa
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..constants import HYDROMETER_ADJUSTMENT_TEMP
from ..constants import IMPERIAL_UNITS
from ..constants import SI_UNITS
from ..exceptions import SugarException
from ..validators import validate_units
from .temperature import celsius_to_fahrenheit
and context:
# Path: brew/constants.py
# HYDROMETER_ADJUSTMENT_TEMP = 59.0
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class SugarException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
#
# Path: brew/utilities/temperature.py
# def celsius_to_fahrenheit(temp):
# """
# Convert degrees Celsius to degrees Fahrenheit
#
# :param float temp: The temperature in Celsius
# :return: The temperature in Fahrenheit
# :rtype: float
# """
# return (temp * 1.8) + 32.0
which might include code, classes, or functions. Output only the next line. | validate_units(units) |
Using the snippet: <|code_start|> """
Adjust the Hydrometer if the temperature deviates from 59degF.
:param float sg: Specific Gravity
:param float temp: Temperature
:param str units: The units
:return: Specific Gravity corrected for temperature
:rtype: float
:raises SugarException: If temperature outside freezing to boiling range of water
The correction formula is from Lyons (1992), who used the following formula
to fit data from the Handbook of Chemistry and Physics (CRC):
:math:`\\text{Correction(@59F)} = 1.313454 - 0.132674 \\times T + 2.057793e^{-3} \\times T^2 - 2.627634e^{-6} \\times T^3`
where T is in degrees F.
Sources:
* http://www.topdownbrew.com/SGCorrection.html
* http://hbd.org/brewery/library/HydromCorr0992.html
* http://www.brewersfriend.com/hydrometer-temp/
* http://www.primetab.com/formulas.html
""" # noqa
validate_units(units)
if units == SI_UNITS:
if temp < 0.0 or 100.0 < temp:
raise SugarException(
u"Correction does not work outside temps 0 - 100C"
) # noqa
<|code_end|>
, determine the next line of code. You have imports:
from ..constants import HYDROMETER_ADJUSTMENT_TEMP
from ..constants import IMPERIAL_UNITS
from ..constants import SI_UNITS
from ..exceptions import SugarException
from ..validators import validate_units
from .temperature import celsius_to_fahrenheit
and context (class names, function names, or code) available:
# Path: brew/constants.py
# HYDROMETER_ADJUSTMENT_TEMP = 59.0
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class SugarException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
#
# Path: brew/utilities/temperature.py
# def celsius_to_fahrenheit(temp):
# """
# Convert degrees Celsius to degrees Fahrenheit
#
# :param float temp: The temperature in Celsius
# :return: The temperature in Fahrenheit
# :rtype: float
# """
# return (temp * 1.8) + 32.0
. Output only the next line. | temp = celsius_to_fahrenheit(temp) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCliAbv(unittest.TestCase):
def setUp(self):
self.og = 1.057
self.fg = 1.013
def test_get_abv(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import textwrap
import unittest
from brew.cli.abv import get_abv
from brew.cli.abv import get_parser
from brew.cli.abv import main
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
and context:
# Path: brew/cli/abv.py
# def get_abv(
# og,
# fg,
# og_temp=HYDROMETER_ADJUSTMENT_TEMP,
# fg_temp=HYDROMETER_ADJUSTMENT_TEMP,
# alternative=False,
# refractometer=False,
# units=IMPERIAL_UNITS,
# verbose=False,
# ):
# """
# Get Alcohol by Volume for CLI Utility
#
# og - Original Specific Gravity
# fg - Final Specific Gravity
# og_temp - Temperature of reading for og
# fg_temp - Temperature of reading for fg
# alternative - Use alternative ABV calculation
# refractometer - Adjust for using a refractometer for readings
# units - Type of units to use in calculations
# verbose - Return verbose information about calculations
# """
# # Gravity is required for calculation
# if not og:
# raise Exception(u"Original gravity required")
# if not fg:
# raise Exception(u"Final gravity required")
#
# # Ensure the gravity units are not mixed up
# if og < fg:
# raise Exception(u"Original Gravity must be higher than Final Gravity")
#
# if units not in [IMPERIAL_UNITS, SI_UNITS]:
# raise Exception(
# u"Units must be in either {} or {}".format(IMPERIAL_UNITS, SI_UNITS) # noqa
# )
#
# # Adjust the gravity based on temperature
# og = hydrometer_adjustment(og, og_temp, units=units)
# fg = hydrometer_adjustment(fg, fg_temp, units=units)
#
# # Adjust the final gravity if using a refractometer
# if refractometer:
# fg = refractometer_adjustment(og, fg)
#
# # Calculate the ABV
# if alternative:
# abv = alcohol_by_volume_alternative(og, fg)
# else:
# abv = alcohol_by_volume_standard(og, fg)
#
# if verbose:
# out = []
# t_unit = u"F" if units == IMPERIAL_UNITS else u"C"
# out.append(u"OG : {:0.3f}".format(og))
# out.append(u"OG Adj : {:0.3f}".format(og))
# out.append(u"OG Temp: {:0.2f} {}".format(og_temp, t_unit))
# out.append(u"FG : {:0.3f}".format(fg))
# out.append(u"FG Adj : {:0.3f}".format(fg))
# out.append(u"FG Temp: {:0.2f} {}".format(fg_temp, t_unit))
# out.append(u"ABV : {:0.2%}".format(abv))
# return u"\n".join(out)
# else:
# return abv
#
# Path: brew/cli/abv.py
# def get_parser():
# parser = argparse.ArgumentParser(description=u"ABV Calculator")
# parser.add_argument(
# u"-o",
# u"--og",
# metavar=u"O",
# type=float,
# required=True,
# help=u"Original Gravity",
# )
# parser.add_argument(
# u"-f", u"--fg", metavar=u"F", type=float, required=True, help=u"Final Gravity"
# )
# parser.add_argument(
# u"--og-temp",
# metavar=u"T",
# type=float,
# default=HYDROMETER_ADJUSTMENT_TEMP,
# help=u"Original Gravity Temperature (default: %(default)s)",
# ) # noqa
# parser.add_argument(
# u"--fg-temp",
# metavar=u"T",
# type=float,
# default=HYDROMETER_ADJUSTMENT_TEMP,
# help=u"Final Gravity Temperature (default: %(default)s)",
# ) # noqa
# parser.add_argument(
# u"-a",
# u"--alternative",
# action=u"store_true",
# default=False,
# help=u"Use alternative ABV equation",
# )
# parser.add_argument(
# u"-r",
# u"--refractometer",
# action=u"store_true",
# default=False,
# help=u"Adjust the Final Gravity if using a Refractometer reading",
# ) # noqa
# parser.add_argument(
# u"--units",
# metavar=u"U",
# type=str,
# default=IMPERIAL_UNITS,
# help=u"Units to use (default: %(default)s)",
# )
# parser.add_argument(
# u"-v", u"--verbose", action=u"store_true", default=False, help=u"Verbose Output"
# )
# return parser
#
# Path: brew/cli/abv.py
# def main(parser_fn=get_parser, parser_kwargs=None):
# parser = None
# if not parser_kwargs:
# parser = parser_fn()
# else:
# parser = parser_fn(**parser_kwargs)
# args = parser.parse_args()
# try:
# out = get_abv(
# args.og,
# args.fg,
# og_temp=args.og_temp,
# fg_temp=args.fg_temp,
# alternative=args.alternative,
# refractometer=args.refractometer,
# units=args.units,
# verbose=args.verbose,
# )
# if args.verbose:
# print(out)
# else:
# print(u"{:0.2%}".format(out))
# except Exception as e:
# print(e)
# sys.exit(1)
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
which might include code, classes, or functions. Output only the next line. | abv = get_abv(self.og, self.fg) |
Based on the snippet: <|code_start|>#! /usr/bin/env python
"""
Ray Daniels
Designing Great Beers
Appendix 2: Course Grind Potential Extract
Notes:
The chart appears to have been developed with the moisture content set
to zero (0.0) and the Brew House Efficiency set to 100% (1.0). This
is not typical and the book even states that you should expect moisture
content at around 4.0% and Brew House Efficiency at arount 90.0%.
"""
def get_chart():
mc = 0.0
bhe = 1.0
chart = []
for dbcg in range(5000, 7600, 100) + range(7600, 8025, 25):
<|code_end|>
, predict the immediate next line with the help of imports:
from brew.utilities.malt import sg_from_dry_basis
from brew.utilities.sugar import sg_to_gu
and context (classes, functions, sometimes code) from other files:
# Path: brew/utilities/malt.py
# def sg_from_dry_basis(
# dbcg,
# moisture_content=MOISTURE_FINISHED_MALT,
# moisture_correction=MOISTURE_CORRECTION,
# brew_house_efficiency=0.90,
# ):
# """
# Specific Gravity from Dry Basis Percentage
#
# :param float dbcg: Dry Basis Coarse Grain in decimal form
# :param float moisture_content: A percentage of moisture content in finished malt in decimal form
# :param float moisture_correction: A percentage correction in decimal form
# :param float brew_house_efficiency: The efficiency in decimal form
# :return: Specific Gravity available from Malt
# :rtype: float
# """ # noqa
# validate_percentage(dbcg)
# validate_percentage(moisture_content)
# validate_percentage(moisture_correction)
# validate_percentage(brew_house_efficiency)
# gu = (
# (dbcg - moisture_content - moisture_correction)
# * brew_house_efficiency
# * SUCROSE_PPG
# )
# return gu_to_sg(gu)
#
# Path: brew/utilities/sugar.py
# def sg_to_gu(sg):
# """
# Specific Gravity to Gravity Units
#
# :param float sg: Specific Gravity
# :return: Gravity Units
# :rtype: float
# """
# return (sg - 1) * 1000.0
. Output only the next line. | sg = sg_from_dry_basis( |
Here is a snippet: <|code_start|>#! /usr/bin/env python
"""
Ray Daniels
Designing Great Beers
Appendix 2: Course Grind Potential Extract
Notes:
The chart appears to have been developed with the moisture content set
to zero (0.0) and the Brew House Efficiency set to 100% (1.0). This
is not typical and the book even states that you should expect moisture
content at around 4.0% and Brew House Efficiency at arount 90.0%.
"""
def get_chart():
mc = 0.0
bhe = 1.0
chart = []
for dbcg in range(5000, 7600, 100) + range(7600, 8025, 25):
sg = sg_from_dry_basis(
dbcg / 10000.0, moisture_content=mc, brew_house_efficiency=bhe
)
<|code_end|>
. Write the next line using the current file imports:
from brew.utilities.malt import sg_from_dry_basis
from brew.utilities.sugar import sg_to_gu
and context from other files:
# Path: brew/utilities/malt.py
# def sg_from_dry_basis(
# dbcg,
# moisture_content=MOISTURE_FINISHED_MALT,
# moisture_correction=MOISTURE_CORRECTION,
# brew_house_efficiency=0.90,
# ):
# """
# Specific Gravity from Dry Basis Percentage
#
# :param float dbcg: Dry Basis Coarse Grain in decimal form
# :param float moisture_content: A percentage of moisture content in finished malt in decimal form
# :param float moisture_correction: A percentage correction in decimal form
# :param float brew_house_efficiency: The efficiency in decimal form
# :return: Specific Gravity available from Malt
# :rtype: float
# """ # noqa
# validate_percentage(dbcg)
# validate_percentage(moisture_content)
# validate_percentage(moisture_correction)
# validate_percentage(brew_house_efficiency)
# gu = (
# (dbcg - moisture_content - moisture_correction)
# * brew_house_efficiency
# * SUCROSE_PPG
# )
# return gu_to_sg(gu)
#
# Path: brew/utilities/sugar.py
# def sg_to_gu(sg):
# """
# Specific Gravity to Gravity Units
#
# :param float sg: Specific Gravity
# :return: Gravity Units
# :rtype: float
# """
# return (sg - 1) * 1000.0
, which may include functions, classes, or code. Output only the next line. | gu = sg_to_gu(sg) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
__all__ = [u"Yeast"]
class Yeast(object):
"""
A representation of a type of Yeast as added to a Recipe.
"""
def __init__(self, name, percent_attenuation=0.75):
"""
:param float percent_attenuation: The percentage the yeast is expected to attenuate the sugar in the yeast to create alcohol
:raises YeastException: If percent_attenuation is not provided
""" # noqa
self.name = name
if percent_attenuation is None:
<|code_end|>
. Use current file imports:
(import json
import sys
import textwrap
from .exceptions import YeastException
from .validators import validate_optional_fields
from .validators import validate_percentage
from .validators import validate_required_fields)
and context including class names, function names, or small code snippets from other files:
# Path: brew/exceptions.py
# class YeastException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_optional_fields(data, optional_fields, data_field=u"data"):
# """
# Validate fields which are optional as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) optional_fields: Values and types to check for in data
# :param str data_field: The key in the data dictionary containing the optional fields
# :raises ValidatorException: Optional field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """ # noqa
# # If no optional data field present then return
# if data_field not in data:
# return
# for field, field_type in optional_fields:
# if field in data[data_field]:
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# # With optional fields only check the type as they are overrides
# # and not all overrides need to be present
# if not isinstance(data[data_field][field], field_type):
# raise ValidatorException(
# u"Optional field '{}' in '{}' is not of type '{}'".format( # noqa
# field, data_field, field_type
# )
# )
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
. Output only the next line. | raise YeastException( |
Given snippet: <|code_start|> out = u"{0}, percent_attenuation={1}".format(out, self.percent_attenuation)
out = u"{0})".format(out)
return out
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if (self.name == other.name) and (
self.percent_attenuation == other.percent_attenuation
):
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
return {
u"name": self.name,
u"data": {u"percent_attenuation": self.percent_attenuation},
}
def to_json(self):
return json.dumps(self.to_dict(), sort_keys=True)
@classmethod
def validate(cls, yeast_data):
required_fields = [(u"name", str)]
optional_fields = [(u"percent_attenuation", float)]
validate_required_fields(yeast_data, required_fields)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import sys
import textwrap
from .exceptions import YeastException
from .validators import validate_optional_fields
from .validators import validate_percentage
from .validators import validate_required_fields
and context:
# Path: brew/exceptions.py
# class YeastException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_optional_fields(data, optional_fields, data_field=u"data"):
# """
# Validate fields which are optional as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) optional_fields: Values and types to check for in data
# :param str data_field: The key in the data dictionary containing the optional fields
# :raises ValidatorException: Optional field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """ # noqa
# # If no optional data field present then return
# if data_field not in data:
# return
# for field, field_type in optional_fields:
# if field in data[data_field]:
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# # With optional fields only check the type as they are overrides
# # and not all overrides need to be present
# if not isinstance(data[data_field][field], field_type):
# raise ValidatorException(
# u"Optional field '{}' in '{}' is not of type '{}'".format( # noqa
# field, data_field, field_type
# )
# )
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
which might include code, classes, or functions. Output only the next line. | validate_optional_fields(yeast_data, optional_fields) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
__all__ = [u"Yeast"]
class Yeast(object):
"""
A representation of a type of Yeast as added to a Recipe.
"""
def __init__(self, name, percent_attenuation=0.75):
"""
:param float percent_attenuation: The percentage the yeast is expected to attenuate the sugar in the yeast to create alcohol
:raises YeastException: If percent_attenuation is not provided
""" # noqa
self.name = name
if percent_attenuation is None:
raise YeastException(
u"{}: Must provide percent attenuation".format(self.name) # noqa
)
<|code_end|>
using the current file's imports:
import json
import sys
import textwrap
from .exceptions import YeastException
from .validators import validate_optional_fields
from .validators import validate_percentage
from .validators import validate_required_fields
and any relevant context from other files:
# Path: brew/exceptions.py
# class YeastException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_optional_fields(data, optional_fields, data_field=u"data"):
# """
# Validate fields which are optional as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) optional_fields: Values and types to check for in data
# :param str data_field: The key in the data dictionary containing the optional fields
# :raises ValidatorException: Optional field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """ # noqa
# # If no optional data field present then return
# if data_field not in data:
# return
# for field, field_type in optional_fields:
# if field in data[data_field]:
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# # With optional fields only check the type as they are overrides
# # and not all overrides need to be present
# if not isinstance(data[data_field][field], field_type):
# raise ValidatorException(
# u"Optional field '{}' in '{}' is not of type '{}'".format( # noqa
# field, data_field, field_type
# )
# )
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
. Output only the next line. | self.percent_attenuation = validate_percentage(percent_attenuation) |
Given the code snippet: <|code_start|> if self.percent_attenuation:
out = u"{0}, percent_attenuation={1}".format(out, self.percent_attenuation)
out = u"{0})".format(out)
return out
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if (self.name == other.name) and (
self.percent_attenuation == other.percent_attenuation
):
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
return {
u"name": self.name,
u"data": {u"percent_attenuation": self.percent_attenuation},
}
def to_json(self):
return json.dumps(self.to_dict(), sort_keys=True)
@classmethod
def validate(cls, yeast_data):
required_fields = [(u"name", str)]
optional_fields = [(u"percent_attenuation", float)]
<|code_end|>
, generate the next line using the imports in this file:
import json
import sys
import textwrap
from .exceptions import YeastException
from .validators import validate_optional_fields
from .validators import validate_percentage
from .validators import validate_required_fields
and context (functions, classes, or occasionally code) from other files:
# Path: brew/exceptions.py
# class YeastException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_optional_fields(data, optional_fields, data_field=u"data"):
# """
# Validate fields which are optional as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) optional_fields: Values and types to check for in data
# :param str data_field: The key in the data dictionary containing the optional fields
# :raises ValidatorException: Optional field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """ # noqa
# # If no optional data field present then return
# if data_field not in data:
# return
# for field, field_type in optional_fields:
# if field in data[data_field]:
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# # With optional fields only check the type as they are overrides
# # and not all overrides need to be present
# if not isinstance(data[data_field][field], field_type):
# raise ValidatorException(
# u"Optional field '{}' in '{}' is not of type '{}'".format( # noqa
# field, data_field, field_type
# )
# )
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
. Output only the next line. | validate_required_fields(yeast_data, required_fields) |
Given snippet: <|code_start|>
def alcohol_by_volume_standard(og, fg):
"""
Alcohol by Volume Standard Calculation
:param float og: Original Gravity
:param float fg: Final Gravity
:return: Alcohol by Volume decimal percentage
:rtype: float
Most brewing sites use this basic formula:
:math:`\\text{ABV} = \\big(\\text{og} - \\text{fg}\\big) \\times 131.25`
This equation was created before the computer age. It is easy to do by
hand, and over time became the accepted formula for home brewers!
Variations on this equation which report within tenths of each other
come from The Joy of Homebrewing Method by Charlie Papazian, Bee Lee's
Method, Beer Advocate Method. Some variations use 131 instead of 131.25.
The resulting difference is pretty minor.
Source:
* http://www.brewersfriend.com/2011/06/16/alcohol-by-volume-calculator-updated/
* http://www.brewmorebeer.com/calculate-percent-alcohol-in-beer/
:math:`\\text{ABV} = \\frac{46.07 \\text{g/mol C2H6O}}{44.0095 \\text{g/mol CO2}} \\times \\frac{1.0}{0.7936} \\times 100 \\times (og - fg)`
""" # noqa
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..constants import ABV_CONST
from ..constants import ALCOHOL_SPECIFIC_GRAVITY
from .sugar import apparent_extract_to_real_extract
and context:
# Path: brew/constants.py
# ABV_CONST = 131.25 # RATIO_C2H6O_TO_CO2 / ALCOHOL_SPECIFIC_GRAVITY * 100.0
#
# Path: brew/constants.py
# ALCOHOL_SPECIFIC_GRAVITY = 0.7936
#
# Path: brew/utilities/sugar.py
# def apparent_extract_to_real_extract(original_extract, apparent_extract):
# """
# Apparent Extract to Real Extract in degrees Plato
#
# :param float original_extract: Original degrees Plato
# :param float apparent_extract: Apparent degrees Plato of finished beer
# :return: Real degrees Plato of finished beer
# :rtype: float
#
# Source:
#
# * Formula from Balling: De Clerck, Jean, A Textbook Of Brewing, Chapman & Hall Ltd., 1958
# """ # noqa
# attenuation_coeff = 0.22 + 0.001 * original_extract
# real_extract = (attenuation_coeff * original_extract + apparent_extract) / (
# 1 + attenuation_coeff
# ) # noqa
# return real_extract
which might include code, classes, or functions. Output only the next line. | return (og - fg) * ABV_CONST / 100.0 |
Predict the next line after this snippet: <|code_start|> equation, giving Alcohol by Weight. This is then converted to Alcohol
by Volume multiplying by the ratio of Final Gravity to Density of Ethanol.
The alternate equation reports a higher ABV for higher gravity beers.
This equation is just a different take on it. Scientists rarely agree
when it comes to equations. There will probably be another equation for
ABV down the road.
The complex formula, and variations on it come from:
* Ritchie Products Ltd, (Zymurgy, Summer 1995, vol. 18, no. 2)
* Michael L. Hall's article Brew by the Numbers: Add Up What's in Your Beer, and Designing Great Beers by Daniels.
Source:
* http://www.brewersfriend.com/2011/06/16/alcohol-by-volume-calculator-updated/
""" # noqa
# Density listed (possibly incorrectly) from Zymergy Mag
DENSITY_ETHANOL = 0.794
return (76.08 * (og - fg) / (1.775 - og)) * (fg / DENSITY_ETHANOL) / 100.0
def alcohol_by_weight(abv):
"""
Alcohol by Weight from ABV
:param float abv: Alcohol by Volume
:return: Alcohol by Weight
:rtype: float
"""
<|code_end|>
using the current file's imports:
from ..constants import ABV_CONST
from ..constants import ALCOHOL_SPECIFIC_GRAVITY
from .sugar import apparent_extract_to_real_extract
and any relevant context from other files:
# Path: brew/constants.py
# ABV_CONST = 131.25 # RATIO_C2H6O_TO_CO2 / ALCOHOL_SPECIFIC_GRAVITY * 100.0
#
# Path: brew/constants.py
# ALCOHOL_SPECIFIC_GRAVITY = 0.7936
#
# Path: brew/utilities/sugar.py
# def apparent_extract_to_real_extract(original_extract, apparent_extract):
# """
# Apparent Extract to Real Extract in degrees Plato
#
# :param float original_extract: Original degrees Plato
# :param float apparent_extract: Apparent degrees Plato of finished beer
# :return: Real degrees Plato of finished beer
# :rtype: float
#
# Source:
#
# * Formula from Balling: De Clerck, Jean, A Textbook Of Brewing, Chapman & Hall Ltd., 1958
# """ # noqa
# attenuation_coeff = 0.22 + 0.001 * original_extract
# real_extract = (attenuation_coeff * original_extract + apparent_extract) / (
# 1 + attenuation_coeff
# ) # noqa
# return real_extract
. Output only the next line. | return abv * ALCOHOL_SPECIFIC_GRAVITY |
Predict the next line for this snippet: <|code_start|> Source:
* Formula from Balling: De Clerck, Jean, A Textbook Of Brewing, Chapman & Hall Ltd., 1958
* http://beersmith.com/blog/2010/09/07/apparent-and-real-attenuation-for-beer-brewers-part-1/
* http://beersmith.com/blog/2010/09/14/apparent-and-real-attenuation-for-beer-brewers-part-2/
""" # noqa
return (original_extract - apparent_extract) / original_extract
def real_attenuation(original_extract, real_extract):
"""
Real Attenuation
:param float original_extract: Original degrees Plato
:param float real_extract: Real degrees Plato of finished beer
:return: The percent of real attenuation
:rtype: float
"""
return (original_extract - real_extract) / original_extract
def real_attenuation_from_apparent_extract(original_extract, apparent_extract):
"""
Real Attenuation from Apparent Extract
:param float original_extract: Original degrees Plato
:param float apparent_extract: Apparent degrees Plato of finished beer
:return: The percent of real attenuation
:rtype: float
"""
<|code_end|>
with the help of current file imports:
from ..constants import ABV_CONST
from ..constants import ALCOHOL_SPECIFIC_GRAVITY
from .sugar import apparent_extract_to_real_extract
and context from other files:
# Path: brew/constants.py
# ABV_CONST = 131.25 # RATIO_C2H6O_TO_CO2 / ALCOHOL_SPECIFIC_GRAVITY * 100.0
#
# Path: brew/constants.py
# ALCOHOL_SPECIFIC_GRAVITY = 0.7936
#
# Path: brew/utilities/sugar.py
# def apparent_extract_to_real_extract(original_extract, apparent_extract):
# """
# Apparent Extract to Real Extract in degrees Plato
#
# :param float original_extract: Original degrees Plato
# :param float apparent_extract: Apparent degrees Plato of finished beer
# :return: Real degrees Plato of finished beer
# :rtype: float
#
# Source:
#
# * Formula from Balling: De Clerck, Jean, A Textbook Of Brewing, Chapman & Hall Ltd., 1958
# """ # noqa
# attenuation_coeff = 0.22 + 0.001 * original_extract
# real_extract = (attenuation_coeff * original_extract + apparent_extract) / (
# 1 + attenuation_coeff
# ) # noqa
# return real_extract
, which may contain function names, class names, or code. Output only the next line. | real_extract = apparent_extract_to_real_extract(original_extract, apparent_extract) |
Given the following code snippet before the placeholder: <|code_start|>
:param Recipe recipe: A Recipe object
:return: True if recipe matches style, otherwise False
:rtype: bool
"""
if (
self.og_matches(recipe.og)
and self.fg_matches(recipe.fg)
and self.abv_matches(recipe.abv)
and self.ibu_matches(recipe.ibu)
and self.color_matches(recipe.color)
):
return True
return False
def recipe_errors(self, recipe):
"""
Return list errors if the recipe doesn't match the style
:param Recipe recipe: A Recipe object
:return: Errors
:rtype: list
"""
errors = []
errors.extend(self.og_errors(recipe.og))
errors.extend(self.fg_errors(recipe.fg))
errors.extend(self.abv_errors(recipe.abv))
errors.extend(self.ibu_errors(recipe.ibu))
try:
errors.extend(self.color_errors(recipe.color))
<|code_end|>
, predict the next line using imports from the current file:
import json
import sys
import textwrap
from .exceptions import ColorException
from .exceptions import StyleException
from .validators import validate_required_fields
and context including class names, function names, and sometimes code from other files:
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/exceptions.py
# class StyleException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
. Output only the next line. | except ColorException: |
Here is a snippet: <|code_start|> :param str style: The style name
:param list(float) og: The lower and upper original gravity
:param list(float) fg: The lower and upper final gravity
:param list(float) abv: The lower and upper alcohol by volume
:param list(float) ibu: The lower and upper IBU
:param list(float) color: The lower and upper color (in SRM)
"""
self.category = category
self.subcategory = subcategory
self.style = style
self.og = self._validate_input_list(og, float, u"Original Gravity")
self.fg = self._validate_input_list(fg, float, u"Final Gravity")
self.abv = self._validate_input_list(abv, (int, float), u"ABV")
self.ibu = self._validate_input_list(ibu, (int, float), u"IBU")
self.color = self._validate_input_list(color, (int, float), u"Color")
@classmethod
def _validate_input_list(cls, value_list, value_type, name):
"""
Private class to validate inputs for class parameters
:param list value_list: A list of values to validate
:param str name: The name of the value_list being validated
:raises StyleException: If value_list for item is empty
:raises StyleException: If value_list is not a list or tuple
:raises StyleException: If two values are not provided
:raises StyleException: If either value of wrong type
:raises StyleException: If value_list is out of order
"""
if not value_list:
<|code_end|>
. Write the next line using the current file imports:
import json
import sys
import textwrap
from .exceptions import ColorException
from .exceptions import StyleException
from .validators import validate_required_fields
and context from other files:
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/exceptions.py
# class StyleException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
, which may include functions, classes, or code. Output only the next line. | raise StyleException(u"Must provide value_list for {}".format(name)) |
Given the code snippet: <|code_start|> return errors
def to_dict(self):
style_dict = {
u"style": self.style,
u"category": self.category,
u"subcategory": self.subcategory,
u"og": self.og,
u"fg": self.fg,
u"abv": self.abv,
u"ibu": self.ibu,
u"color": self.color,
}
return style_dict
def to_json(self):
return json.dumps(self.to_dict(), sort_keys=True)
@classmethod
def validate(cls, recipe):
required_fields = [
(u"style", str),
(u"category", str),
(u"subcategory", str),
(u"og", (list, tuple)),
(u"fg", (list, tuple)),
(u"abv", (list, tuple)),
(u"ibu", (list, tuple)),
(u"color", (list, tuple)),
]
<|code_end|>
, generate the next line using the imports in this file:
import json
import sys
import textwrap
from .exceptions import ColorException
from .exceptions import StyleException
from .validators import validate_required_fields
and context (functions, classes, or occasionally code) from other files:
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/exceptions.py
# class StyleException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_required_fields(data, required_fields):
# """
# Validate fields which are required as part of the data.
#
# :param dict data: A python dictionary to check for required fields
# :param list(tuple) required_fields: Values and types to check for in data
# :raises ValidatorException: Required field is missing from data
# :raises ValidatorException: Required field is of the wrong type
#
# The format is a list of tuples where the first element is a string with
# a value that should be a key found in the data dict and
# where the second element is a python type or list/tuple of
# python types to check the field against.
# """
# for field, field_type in required_fields:
# if field not in data:
# raise ValidatorException(
# u"Required field '{}' missing from data".format(field) # noqa
# )
# if field_type == str:
# try:
# field_type = unicode
# except NameError:
# field_type = str
# if not isinstance(data[field], field_type):
# raise ValidatorException(
# u"Required field '{}' is not of type '{}'".format( # noqa
# field, field_type
# )
# )
. Output only the next line. | validate_required_fields(recipe, required_fields) |
Next line prediction: <|code_start|>def main():
recipe = {
u"name": u"10 Pound Stout (Extract)",
u"start_volume": 4.0,
u"final_volume": 5.0,
u"grains": [
{u"name": u"Amber Liquid Extract", u"weight": 7.0, u"grain_type": u"lme"},
{u"name": u"Dark Dry Extract", u"weight": 3.0, u"grain_type": u"dme"},
{
u"name": u"Caramel Crystal Malt 120l",
u"weight": 1.0,
u"grain_type": u"specialty",
},
{
u"name": u"Black Barley Stout",
u"weight": 0.5,
u"grain_type": u"specialty",
},
{u"name": u"Roasted Barley", u"weight": 0.5, u"grain_type": u"specialty"},
],
u"hops": [
{u"name": u"Columbus", u"weight": 1.0, u"boil_time": 60.0},
{u"name": u"Columbus", u"weight": 1.0, u"boil_time": 5.0},
],
u"yeast": {u"name": u"Wyeast 1084"},
u"data": {u"brew_house_yield": 0.80, u"units": u"imperial"},
}
data_dir = os.path.abspath(os.path.join(os.getcwd(), "data/"))
<|code_end|>
. Use current file imports:
(import os
from brew.parsers import JSONDataLoader
from brew.parsers import parse_recipe
from brew.utilities.efficiency import calculate_brew_house_yield # noqa)
and context including class names, function names, or small code snippets from other files:
# Path: brew/parsers.py
# class JSONDataLoader(DataLoader):
# """
# Load data from JSON files inside the data_dir.
# """
#
# #: The JSON file extension
# EXT = "json"
#
# @classmethod
# def read_data(cls, filename):
# """
# :param str filename: The filename of the file to read
# :return: The data loaded from a JSON file
# """
# data = None
# with open(filename, "r") as data_file:
# data = json.loads(data_file.read())
# return data
#
# Path: brew/parsers.py
# def parse_recipe(
# recipe,
# loader,
# cereals_loader=None,
# hops_loader=None,
# yeast_loader=None,
# cereals_dir_suffix="cereals/",
# hops_dir_suffix="hops/",
# yeast_dir_suffix="yeast/",
# ):
# """
# Parse a recipe from a python Dict
#
# :param dict recipe: A representation of a recipe
# :param DataLoader loader: A class to load additional information
# :param DataLoader cereal_loader: A class to load additional information specific to cereals
# :param DataLoader hops_loader: A class to load additional information specific to hops
# :param DataLoader yeast_loader: A class to load additional information specific to yeast
#
# A recipe must have the following top level attributes:
#
# * name (str)
# * start_volume (float)
# * final_volume (float)
# * grains (list(dict))
# * hops (list(dict))
# * yeast (dict)
#
# Additionally the recipe may contain override data in the 'data'
# attribute with the following keys:
#
# * brew_house_yield (float)
# * units (str)
#
# All other fields will be ignored and may be used for other metadata.
#
# The dict objects in the grains, hops, and yeast values are required to have
# the key 'name' and the remaining attributes will be looked up in the data
# directory if they are not provided.
# """ # noqa
# if cereals_loader is None:
# cereals_loader = loader
# if hops_loader is None:
# hops_loader = loader
# if yeast_loader is None:
# yeast_loader = loader
#
# Recipe.validate(recipe)
#
# grain_additions = []
# for grain in recipe[u"grains"]:
# grain_additions.append(
# parse_cereals(grain, cereals_loader, dir_suffix=cereals_dir_suffix)
# )
#
# hop_additions = []
# for hop in recipe[u"hops"]:
# hop_additions.append(parse_hops(hop, hops_loader, dir_suffix=hops_dir_suffix))
#
# yeast = parse_yeast(recipe[u"yeast"], yeast_loader, dir_suffix=yeast_dir_suffix)
#
# recipe_kwargs = {
# u"grain_additions": grain_additions,
# u"hop_additions": hop_additions,
# u"yeast": yeast,
# u"start_volume": recipe[u"start_volume"],
# u"final_volume": recipe[u"final_volume"],
# }
# if u"data" in recipe:
# if u"brew_house_yield" in recipe[u"data"]:
# recipe_kwargs[u"brew_house_yield"] = recipe[u"data"][u"brew_house_yield"]
# if u"units" in recipe[u"data"]:
# recipe_kwargs[u"units"] = recipe[u"data"][u"units"]
#
# beer = Recipe(recipe[u"name"], **recipe_kwargs)
# return beer
#
# Path: brew/utilities/efficiency.py
# def calculate_brew_house_yield(wort_volume, sg, grain_additions):
# """
# Calculate Brew House Yield
#
# :param float wort_volume: The volume of the wort
# :param float sg: THe specific gravity of the wort
# :param list grain_additions: A list of grain additions in the wort
# :type grain_additions: list of GrainAddition objects
# :return: The brew house yield as a percentage
#
# Brew House Yield is a function of the wort volume, the measured specific
# gravity, and the grain additions used to make the wort. This equation is
# thrown off by use of LME or DME since both have 100% efficiency in a brew.
# A better measure is to look at just the grains that needed to be steeped
# seperately and measure the specific gravity of that process.
# """
# total_gu = sum([grain_add.gu for grain_add in grain_additions])
# return (sg_to_gu(sg) * wort_volume) / total_gu
. Output only the next line. | loader = JSONDataLoader(data_dir) |
Based on the snippet: <|code_start|>
recipe = {
u"name": u"10 Pound Stout (Extract)",
u"start_volume": 4.0,
u"final_volume": 5.0,
u"grains": [
{u"name": u"Amber Liquid Extract", u"weight": 7.0, u"grain_type": u"lme"},
{u"name": u"Dark Dry Extract", u"weight": 3.0, u"grain_type": u"dme"},
{
u"name": u"Caramel Crystal Malt 120l",
u"weight": 1.0,
u"grain_type": u"specialty",
},
{
u"name": u"Black Barley Stout",
u"weight": 0.5,
u"grain_type": u"specialty",
},
{u"name": u"Roasted Barley", u"weight": 0.5, u"grain_type": u"specialty"},
],
u"hops": [
{u"name": u"Columbus", u"weight": 1.0, u"boil_time": 60.0},
{u"name": u"Columbus", u"weight": 1.0, u"boil_time": 5.0},
],
u"yeast": {u"name": u"Wyeast 1084"},
u"data": {u"brew_house_yield": 0.80, u"units": u"imperial"},
}
data_dir = os.path.abspath(os.path.join(os.getcwd(), "data/"))
loader = JSONDataLoader(data_dir)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from brew.parsers import JSONDataLoader
from brew.parsers import parse_recipe
from brew.utilities.efficiency import calculate_brew_house_yield # noqa
and context (classes, functions, sometimes code) from other files:
# Path: brew/parsers.py
# class JSONDataLoader(DataLoader):
# """
# Load data from JSON files inside the data_dir.
# """
#
# #: The JSON file extension
# EXT = "json"
#
# @classmethod
# def read_data(cls, filename):
# """
# :param str filename: The filename of the file to read
# :return: The data loaded from a JSON file
# """
# data = None
# with open(filename, "r") as data_file:
# data = json.loads(data_file.read())
# return data
#
# Path: brew/parsers.py
# def parse_recipe(
# recipe,
# loader,
# cereals_loader=None,
# hops_loader=None,
# yeast_loader=None,
# cereals_dir_suffix="cereals/",
# hops_dir_suffix="hops/",
# yeast_dir_suffix="yeast/",
# ):
# """
# Parse a recipe from a python Dict
#
# :param dict recipe: A representation of a recipe
# :param DataLoader loader: A class to load additional information
# :param DataLoader cereal_loader: A class to load additional information specific to cereals
# :param DataLoader hops_loader: A class to load additional information specific to hops
# :param DataLoader yeast_loader: A class to load additional information specific to yeast
#
# A recipe must have the following top level attributes:
#
# * name (str)
# * start_volume (float)
# * final_volume (float)
# * grains (list(dict))
# * hops (list(dict))
# * yeast (dict)
#
# Additionally the recipe may contain override data in the 'data'
# attribute with the following keys:
#
# * brew_house_yield (float)
# * units (str)
#
# All other fields will be ignored and may be used for other metadata.
#
# The dict objects in the grains, hops, and yeast values are required to have
# the key 'name' and the remaining attributes will be looked up in the data
# directory if they are not provided.
# """ # noqa
# if cereals_loader is None:
# cereals_loader = loader
# if hops_loader is None:
# hops_loader = loader
# if yeast_loader is None:
# yeast_loader = loader
#
# Recipe.validate(recipe)
#
# grain_additions = []
# for grain in recipe[u"grains"]:
# grain_additions.append(
# parse_cereals(grain, cereals_loader, dir_suffix=cereals_dir_suffix)
# )
#
# hop_additions = []
# for hop in recipe[u"hops"]:
# hop_additions.append(parse_hops(hop, hops_loader, dir_suffix=hops_dir_suffix))
#
# yeast = parse_yeast(recipe[u"yeast"], yeast_loader, dir_suffix=yeast_dir_suffix)
#
# recipe_kwargs = {
# u"grain_additions": grain_additions,
# u"hop_additions": hop_additions,
# u"yeast": yeast,
# u"start_volume": recipe[u"start_volume"],
# u"final_volume": recipe[u"final_volume"],
# }
# if u"data" in recipe:
# if u"brew_house_yield" in recipe[u"data"]:
# recipe_kwargs[u"brew_house_yield"] = recipe[u"data"][u"brew_house_yield"]
# if u"units" in recipe[u"data"]:
# recipe_kwargs[u"units"] = recipe[u"data"][u"units"]
#
# beer = Recipe(recipe[u"name"], **recipe_kwargs)
# return beer
#
# Path: brew/utilities/efficiency.py
# def calculate_brew_house_yield(wort_volume, sg, grain_additions):
# """
# Calculate Brew House Yield
#
# :param float wort_volume: The volume of the wort
# :param float sg: THe specific gravity of the wort
# :param list grain_additions: A list of grain additions in the wort
# :type grain_additions: list of GrainAddition objects
# :return: The brew house yield as a percentage
#
# Brew House Yield is a function of the wort volume, the measured specific
# gravity, and the grain additions used to make the wort. This equation is
# thrown off by use of LME or DME since both have 100% efficiency in a brew.
# A better measure is to look at just the grains that needed to be steeped
# seperately and measure the specific gravity of that process.
# """
# total_gu = sum([grain_add.gu for grain_add in grain_additions])
# return (sg_to_gu(sg) * wort_volume) / total_gu
. Output only the next line. | beer = parse_recipe(recipe, loader) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestRecipeExtract(unittest.TestCase):
def setUp(self):
# Define Recipes
self.recipe = recipe
self.recipe_lme = recipe_lme
self.recipe_dme = recipe_dme
<|code_end|>
using the current file's imports:
import unittest
from brew.constants import IMPERIAL_UNITS
from fixtures import recipe
from fixtures import recipe_dme
from fixtures import recipe_lme
and any relevant context from other files:
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
. Output only the next line. | self.assertEquals(self.recipe.units, IMPERIAL_UNITS) |
Given the code snippet: <|code_start|> return srm * 1.97
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97
def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS):
"""
Calculate MCU from Grain
:param float grain_weight: Grain weight in lbs or kg
:param float beer_color: Beer color in deg Lovibond
:param float final_volume: Final Volume in gal or liters
:param str units: The units
Source:
* http://beersmith.com/blog/2008/04/29/beer-color-understanding-srm-lovibond-and-ebc/
""" # noqa
validate_units(units)
if units == SI_UNITS:
grain_weight = grain_weight * POUND_PER_KG
<|code_end|>
, generate the next line using the imports in this file:
from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units
and context (functions, classes, or occasionally code) from other files:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
. Output only the next line. | final_volume = final_volume * GAL_PER_LITER |
Given the code snippet: <|code_start|> u"calculate_srm",
u"lovibond_to_srm",
u"srm_to_lovibond",
u"srm_to_a430",
u"ebc_to_a430",
]
def srm_to_ebc(srm):
"""
Convert SRM to EBC Color
:param float srm: SRM Color
:return: EBC Color
:rtype: float
"""
return srm * 1.97
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97
<|code_end|>
, generate the next line using the imports in this file:
from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units
and context (functions, classes, or occasionally code) from other files:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
. Output only the next line. | def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS): |
Next line prediction: <|code_start|> """
return srm * 1.97
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97
def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS):
"""
Calculate MCU from Grain
:param float grain_weight: Grain weight in lbs or kg
:param float beer_color: Beer color in deg Lovibond
:param float final_volume: Final Volume in gal or liters
:param str units: The units
Source:
* http://beersmith.com/blog/2008/04/29/beer-color-understanding-srm-lovibond-and-ebc/
""" # noqa
validate_units(units)
if units == SI_UNITS:
<|code_end|>
. Use current file imports:
(from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units)
and context including class names, function names, or small code snippets from other files:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
. Output only the next line. | grain_weight = grain_weight * POUND_PER_KG |
Here is a snippet: <|code_start|> :rtype: float
"""
return srm * 1.97
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97
def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS):
"""
Calculate MCU from Grain
:param float grain_weight: Grain weight in lbs or kg
:param float beer_color: Beer color in deg Lovibond
:param float final_volume: Final Volume in gal or liters
:param str units: The units
Source:
* http://beersmith.com/blog/2008/04/29/beer-color-understanding-srm-lovibond-and-ebc/
""" # noqa
validate_units(units)
<|code_end|>
. Write the next line using the current file imports:
from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units
and context from other files:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
, which may include functions, classes, or code. Output only the next line. | if units == SI_UNITS: |
Based on the snippet: <|code_start|> Calculate MCU from Grain
:param float grain_weight: Grain weight in lbs or kg
:param float beer_color: Beer color in deg Lovibond
:param float final_volume: Final Volume in gal or liters
:param str units: The units
Source:
* http://beersmith.com/blog/2008/04/29/beer-color-understanding-srm-lovibond-and-ebc/
""" # noqa
validate_units(units)
if units == SI_UNITS:
grain_weight = grain_weight * POUND_PER_KG
final_volume = final_volume * GAL_PER_LITER
mcu = grain_weight * beer_color / final_volume
return mcu
def calculate_srm_mosher(mcu):
"""
Mosher Equation for SRM
:param float mcu: The Malt Color Units
:return: SRM Color
:rtype: float
:raises ColorException: If the MCU is < 7.0
""" # noqa
if mcu < 7.0:
<|code_end|>
, predict the immediate next line with the help of imports:
from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units
and context (classes, functions, sometimes code) from other files:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
. Output only the next line. | raise ColorException(u"Mosher equation does not work for MCU < 7.0") |
Using the snippet: <|code_start|> :return: EBC Color
:rtype: float
"""
return srm * 1.97
def ebc_to_srm(ebc):
"""
Convert EBC to SRM Color
:param float ebc: EBC Color
:return: SRM Color
:rtype: float
"""
return ebc / 1.97
def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS):
"""
Calculate MCU from Grain
:param float grain_weight: Grain weight in lbs or kg
:param float beer_color: Beer color in deg Lovibond
:param float final_volume: Final Volume in gal or liters
:param str units: The units
Source:
* http://beersmith.com/blog/2008/04/29/beer-color-understanding-srm-lovibond-and-ebc/
""" # noqa
<|code_end|>
, determine the next line of code. You have imports:
from ..constants import GAL_PER_LITER
from ..constants import IMPERIAL_UNITS
from ..constants import POUND_PER_KG
from ..constants import SI_UNITS
from ..exceptions import ColorException
from ..validators import validate_units
and context (class names, function names, or code) available:
# Path: brew/constants.py
# GAL_PER_LITER = 1.0 / LITER_PER_GAL
#
# Path: brew/constants.py
# IMPERIAL_UNITS = u"imperial"
#
# Path: brew/constants.py
# POUND_PER_KG = 1.0 / KG_PER_POUND
#
# Path: brew/constants.py
# SI_UNITS = u"metric"
#
# Path: brew/exceptions.py
# class ColorException(BrewdayException):
# pass
#
# Path: brew/validators.py
# def validate_units(units):
# """
# Validate units
#
# :param str units: Unit type
# :return: units
# :rtype: str
# :raises ValidatorException: If units is unknown
# """
# if units in [IMPERIAL_UNITS, SI_UNITS]:
# return units
# raise ValidatorException(
# u"Unkown units '{}', must use {} or {}".format(units, IMPERIAL_UNITS, SI_UNITS)
# )
. Output only the next line. | validate_units(units) |
Here is a snippet: <|code_start|>def main():
print("Enzymatic rests schedule")
liquor_to_grist_ratio = 1.5 # qt:lbs
grain_weight = 8.0 # lbs
water_volume = grain_weight * liquor_to_grist_ratio # qt
print("")
print("Starting with {} lbs of grain".format(grain_weight))
target_temp = 110
initial_temp = 70 # grain temperature without water
sk_temp = strike_temp(
target_temp, initial_temp, liquor_to_grist_ratio=liquor_to_grist_ratio
)
print("")
print(
"Bring {} qts of water to {} degF before adding grains".format(
water_volume, round(sk_temp, 1)
)
) # noqa
print("Your temperature should then reach {} degF".format(target_temp))
print("Keep your temperature here for 20 minutes")
initial_temp = sk_temp
target_temp = 140
infusion_temp = 210
<|code_end|>
. Write the next line using the current file imports:
from brew.utilities.temperature import mash_infusion
from brew.utilities.temperature import strike_temp
and context from other files:
# Path: brew/utilities/temperature.py
# def mash_infusion(
# target_temp, initial_temp, grain_weight, water_volume, infusion_temp=212
# ):
# """
# Get Volume of water to infuse into mash to reach scheduled temperature
#
# All temperatures in F.
#
# http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions
#
# :param float target_temp: Mash Temperature to Achieve
# :param float inital_temp: Mash Temperature
# :param float grain_weight: Total weight of grain in mash (lbs)
# :param float water_volume: Total volume of water in mash (qt)
# :param float infusion_temp: Temperature of water to infuse
# :return: The volume of water to add to the mash (qt)
# :rtype: float
# """
# return (
# (target_temp - initial_temp)
# * (0.2 * grain_weight + water_volume)
# / (infusion_temp - target_temp)
# )
#
# Path: brew/utilities/temperature.py
# def strike_temp(target_temp, initial_temp, liquor_to_grist_ratio=1.5):
# """
# Get Strike Water Temperature
#
# All temperatures in F.
#
# http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions
#
# :param float target_temp: Mash Temperature to Achieve
# :param float initial_temp: Malt Temperature
# :param float liquor_to_grist_ratio: The Liquor to Grist Ratio (qt:lbs)
# :return: The strike water temperature
# :rtype: float
# """ # noqa
# return (0.2 / liquor_to_grist_ratio) * (target_temp - initial_temp) + target_temp
, which may include functions, classes, or code. Output only the next line. | infusion_volume = mash_infusion( |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
print("Enzymatic rests schedule")
liquor_to_grist_ratio = 1.5 # qt:lbs
grain_weight = 8.0 # lbs
water_volume = grain_weight * liquor_to_grist_ratio # qt
print("")
print("Starting with {} lbs of grain".format(grain_weight))
target_temp = 110
initial_temp = 70 # grain temperature without water
<|code_end|>
, predict the next line using imports from the current file:
from brew.utilities.temperature import mash_infusion
from brew.utilities.temperature import strike_temp
and context including class names, function names, and sometimes code from other files:
# Path: brew/utilities/temperature.py
# def mash_infusion(
# target_temp, initial_temp, grain_weight, water_volume, infusion_temp=212
# ):
# """
# Get Volume of water to infuse into mash to reach scheduled temperature
#
# All temperatures in F.
#
# http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions
#
# :param float target_temp: Mash Temperature to Achieve
# :param float inital_temp: Mash Temperature
# :param float grain_weight: Total weight of grain in mash (lbs)
# :param float water_volume: Total volume of water in mash (qt)
# :param float infusion_temp: Temperature of water to infuse
# :return: The volume of water to add to the mash (qt)
# :rtype: float
# """
# return (
# (target_temp - initial_temp)
# * (0.2 * grain_weight + water_volume)
# / (infusion_temp - target_temp)
# )
#
# Path: brew/utilities/temperature.py
# def strike_temp(target_temp, initial_temp, liquor_to_grist_ratio=1.5):
# """
# Get Strike Water Temperature
#
# All temperatures in F.
#
# http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions
#
# :param float target_temp: Mash Temperature to Achieve
# :param float initial_temp: Malt Temperature
# :param float liquor_to_grist_ratio: The Liquor to Grist Ratio (qt:lbs)
# :return: The strike water temperature
# :rtype: float
# """ # noqa
# return (0.2 / liquor_to_grist_ratio) * (target_temp - initial_temp) + target_temp
. Output only the next line. | sk_temp = strike_temp( |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCliTemp(unittest.TestCase):
def setUp(self):
self.c = 15.6
self.f = 60.1
def test_get_sugar_conversion_fahrenheit(self):
out = get_temp_conversion(self.f, None)
self.assertEquals(out, self.c)
def test_get_sugar_conversion_celsius(self):
out = get_temp_conversion(None, self.c)
self.assertEquals(out, self.f)
class TestCliArgparserTemp(unittest.TestCase):
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from brew.cli.temp import get_parser
from brew.cli.temp import get_temp_conversion
from brew.cli.temp import main
and context:
# Path: brew/cli/temp.py
# def get_parser():
# parser = argparse.ArgumentParser(description=u"Temperature Conversion")
# parser.add_argument(
# u"-c", u"--celsius", metavar=u"C", type=float, help=u"Temperature in Celsius"
# )
# parser.add_argument(
# u"-f",
# u"--fahrenheit",
# metavar=u"F",
# type=float,
# help=u"Temperature in Fahrenheit",
# )
# return parser
#
# Path: brew/cli/temp.py
# def get_temp_conversion(fahrenheit, celsius):
# """
# Convert temperature between fahrenheit and celsius
# """
# if fahrenheit:
# return round(fahrenheit_to_celsius(fahrenheit), 1)
# elif celsius:
# return round(celsius_to_fahrenheit(celsius), 1)
#
# Path: brew/cli/temp.py
# def main(parser_fn=get_parser, parser_kwargs=None):
# parser = None
# if not parser_kwargs:
# parser = parser_fn()
# else:
# parser = parser_fn(**parser_kwargs)
# args = parser.parse_args()
# if args.fahrenheit and args.celsius:
# print(u"Must provide only one of Fahrenheit or Celsius")
# sys.exit(1)
# elif not (args.fahrenheit or args.celsius):
# print(u"Must provide one of Fahrenheit or Celsius")
# sys.exit(1)
# out = get_temp_conversion(args.fahrenheit, args.celsius)
# print(out)
which might include code, classes, or functions. Output only the next line. | self.parser = get_parser() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCliTemp(unittest.TestCase):
def setUp(self):
self.c = 15.6
self.f = 60.1
def test_get_sugar_conversion_fahrenheit(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from brew.cli.temp import get_parser
from brew.cli.temp import get_temp_conversion
from brew.cli.temp import main
and context (functions, classes, or occasionally code) from other files:
# Path: brew/cli/temp.py
# def get_parser():
# parser = argparse.ArgumentParser(description=u"Temperature Conversion")
# parser.add_argument(
# u"-c", u"--celsius", metavar=u"C", type=float, help=u"Temperature in Celsius"
# )
# parser.add_argument(
# u"-f",
# u"--fahrenheit",
# metavar=u"F",
# type=float,
# help=u"Temperature in Fahrenheit",
# )
# return parser
#
# Path: brew/cli/temp.py
# def get_temp_conversion(fahrenheit, celsius):
# """
# Convert temperature between fahrenheit and celsius
# """
# if fahrenheit:
# return round(fahrenheit_to_celsius(fahrenheit), 1)
# elif celsius:
# return round(celsius_to_fahrenheit(celsius), 1)
#
# Path: brew/cli/temp.py
# def main(parser_fn=get_parser, parser_kwargs=None):
# parser = None
# if not parser_kwargs:
# parser = parser_fn()
# else:
# parser = parser_fn(**parser_kwargs)
# args = parser.parse_args()
# if args.fahrenheit and args.celsius:
# print(u"Must provide only one of Fahrenheit or Celsius")
# sys.exit(1)
# elif not (args.fahrenheit or args.celsius):
# print(u"Must provide one of Fahrenheit or Celsius")
# sys.exit(1)
# out = get_temp_conversion(args.fahrenheit, args.celsius)
# print(out)
. Output only the next line. | out = get_temp_conversion(self.f, None) |
Based on the snippet: <|code_start|> expected = {u"celsius": 25.0, u"fahrenheit": None}
self.assertEquals(out.__dict__, expected)
def test_get_parser_fahrenheit(self):
args = [u"-f", u"62.0"]
out = self.parser.parse_args(args)
expected = {u"celsius": None, u"fahrenheit": 62.0}
self.assertEquals(out.__dict__, expected)
class TestCliMainTemp(unittest.TestCase):
def setUp(self):
class Parser(object):
def __init__(self, output):
self.output = output
def parse_args(self):
class Args(object):
pass
args = Args()
if self.output:
for k, v in self.output.items():
setattr(args, k, v)
return args
def g_parser(output=None):
return Parser(output)
self.parser_fn = g_parser
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from brew.cli.temp import get_parser
from brew.cli.temp import get_temp_conversion
from brew.cli.temp import main
and context (classes, functions, sometimes code) from other files:
# Path: brew/cli/temp.py
# def get_parser():
# parser = argparse.ArgumentParser(description=u"Temperature Conversion")
# parser.add_argument(
# u"-c", u"--celsius", metavar=u"C", type=float, help=u"Temperature in Celsius"
# )
# parser.add_argument(
# u"-f",
# u"--fahrenheit",
# metavar=u"F",
# type=float,
# help=u"Temperature in Fahrenheit",
# )
# return parser
#
# Path: brew/cli/temp.py
# def get_temp_conversion(fahrenheit, celsius):
# """
# Convert temperature between fahrenheit and celsius
# """
# if fahrenheit:
# return round(fahrenheit_to_celsius(fahrenheit), 1)
# elif celsius:
# return round(celsius_to_fahrenheit(celsius), 1)
#
# Path: brew/cli/temp.py
# def main(parser_fn=get_parser, parser_kwargs=None):
# parser = None
# if not parser_kwargs:
# parser = parser_fn()
# else:
# parser = parser_fn(**parser_kwargs)
# args = parser.parse_args()
# if args.fahrenheit and args.celsius:
# print(u"Must provide only one of Fahrenheit or Celsius")
# sys.exit(1)
# elif not (args.fahrenheit or args.celsius):
# print(u"Must provide one of Fahrenheit or Celsius")
# sys.exit(1)
# out = get_temp_conversion(args.fahrenheit, args.celsius)
# print(out)
. Output only the next line. | self.main = main |
Here is a snippet: <|code_start|>
:param float grain: Weight of Grain
:return: DME Weight
:rtype: float
"""
return malt * 3.0 / 5.0
def specialty_grain_to_liquid_malt_weight(grain):
"""
Specialty Grain to LME Weight
:param float grain: Weight of Specialty Grain
:return: LME Weight
:rtype: float
"""
return grain * 0.89
def liquid_malt_to_specialty_grain_weight(malt):
"""
LME to Specialty Grain Weight
:param float grain: Weight of LME
:return: Specialty Grain Weight
:rtype: float
"""
return malt / 0.89
<|code_end|>
. Write the next line using the current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
, which may include functions, classes, or code. Output only the next line. | def fine_grind_to_coarse_grind(fine_grind, fc_diff=FC_DIFF_TWO_ROW): |
Given snippet: <|code_start|> :param float brew_house_efficiency: The efficiency in decimal form
:return: Specific Gravity available from Malt
:rtype: float
""" # noqa
validate_percentage(dbcg)
validate_percentage(moisture_content)
validate_percentage(moisture_correction)
validate_percentage(brew_house_efficiency)
return (
(dbcg - moisture_content - moisture_correction)
* brew_house_efficiency
* SUCROSE_PLATO
)
def basis_to_hwe(basis_percentage):
"""
Basis Percentage to Hot Water Extract
:param float basis_percentage: Basis as percentage
:return: Hot Water Extract as Ldeg/kg, dry basis
:rtype: float
Ldeg/kg means how many litres of wort with a specific gravity of 1.001 you
could produce from a kilogram of the fermentable
For example, if you had a kilogram of sucrose, you could make up 386 litres
of wort with a specific gravity of 1.001.
"""
validate_percentage(basis_percentage)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
which might include code, classes, or functions. Output only the next line. | return basis_percentage * LITERS_OF_WORT_AT_SG |
Continue the code snippet: <|code_start|> """
Dry Basis to As-Is Basis Percentage
:param float dry_basis: A percentage from the malt bill in decimal form
:param float moisture_content: A percentage of moisture content in finished malt in decimal form
:return: As-Is Basis
:rtype: float
""" # noqa
validate_percentage(dry_basis)
validate_percentage(moisture_content)
return dry_basis * (1.0 - moisture_content)
def as_is_basis_to_dry_basis(as_is, moisture_content=MOISTURE_FINISHED_MALT):
"""
As-Is Basis to Dry Basis Percentage
:param float as_is: A percentage from the malt bill in decimal form
:param float moisture_content: A percentage of moisture content in finished malt in decimal form
:return: Dry Basis
:rtype: float
""" # noqa
validate_percentage(as_is)
validate_percentage(moisture_content)
return as_is / (1.0 - moisture_content)
def sg_from_dry_basis(
dbcg,
moisture_content=MOISTURE_FINISHED_MALT,
<|code_end|>
. Use current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context (classes, functions, or code) from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
. Output only the next line. | moisture_correction=MOISTURE_CORRECTION, |
Based on the snippet: <|code_start|>
def fine_grind_to_coarse_grind(fine_grind, fc_diff=FC_DIFF_TWO_ROW):
"""
Fine Grind to Coarse Grind Percentage
:param float fine_grind: A percentage from the malt bill
:param float fc_diff: The F/C difference percentage from the malt bill
:return: Coarse Grind Percentage
:rtype: float
"""
validate_percentage(fine_grind)
validate_percentage(fc_diff)
return fine_grind - fc_diff
def coarse_grind_to_fine_grind(coarse_grind, fc_diff=FC_DIFF_TWO_ROW):
"""
Coarse Grind to Fine Grind Percentage
:param float coarse_grind: A percentage from the malt bill
:param float fc_diff: The F/C difference percentage from the malt bill
:return: Fine Grind Percentage
:rtype: float
"""
validate_percentage(coarse_grind)
validate_percentage(fc_diff)
return coarse_grind + fc_diff
<|code_end|>
, predict the immediate next line with the help of imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context (classes, functions, sometimes code) from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
. Output only the next line. | def dry_basis_to_as_is_basis(dry_basis, moisture_content=MOISTURE_FINISHED_MALT): |
Given snippet: <|code_start|>
Ldeg/kg means how many litres of wort with a specific gravity of 1.001 you
could produce from a kilogram of the fermentable
For example, if you had a kilogram of sucrose, you could make up 386 litres
of wort with a specific gravity of 1.001.
"""
validate_percentage(basis_percentage)
return basis_percentage * LITERS_OF_WORT_AT_SG
def hwe_to_basis(hwe):
"""
Hot Water Extract to Basis Percentage
:param float hwe: Hot Water Extract as Ldeg/kg, dry basis
:return: Basis as percentage
:rtype: float
"""
return hwe / LITERS_OF_WORT_AT_SG
def ppg_to_hwe(ppg):
"""
Points Per Gallon to Hot Water Extract
:param float ppg: Points Per Gallon
:return: Hot Water Extract
:rtype: float
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
which might include code, classes, or functions. Output only the next line. | return ppg * PPG_TO_HWE_CONVERSION |
Based on the snippet: <|code_start|> (dbcg - moisture_content - moisture_correction)
* brew_house_efficiency
* SUCROSE_PPG
)
return gu_to_sg(gu)
def plato_from_dry_basis(
dbcg,
moisture_content=MOISTURE_FINISHED_MALT,
moisture_correction=MOISTURE_CORRECTION,
brew_house_efficiency=0.90,
):
"""
Degrees Plato from Dry Basis Percentage
:param float dbcg: Dry Basis Coarse Grain in decimal form
:param float moisture_content: A percentage of moisture content in finished malt in decimal form
:param float moisture_correction: A percentage correction in decimal form
:param float brew_house_efficiency: The efficiency in decimal form
:return: Specific Gravity available from Malt
:rtype: float
""" # noqa
validate_percentage(dbcg)
validate_percentage(moisture_content)
validate_percentage(moisture_correction)
validate_percentage(brew_house_efficiency)
return (
(dbcg - moisture_content - moisture_correction)
* brew_house_efficiency
<|code_end|>
, predict the immediate next line with the help of imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context (classes, functions, sometimes code) from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
. Output only the next line. | * SUCROSE_PLATO |
Predict the next line for this snippet: <|code_start|> :rtype: float
""" # noqa
validate_percentage(as_is)
validate_percentage(moisture_content)
return as_is / (1.0 - moisture_content)
def sg_from_dry_basis(
dbcg,
moisture_content=MOISTURE_FINISHED_MALT,
moisture_correction=MOISTURE_CORRECTION,
brew_house_efficiency=0.90,
):
"""
Specific Gravity from Dry Basis Percentage
:param float dbcg: Dry Basis Coarse Grain in decimal form
:param float moisture_content: A percentage of moisture content in finished malt in decimal form
:param float moisture_correction: A percentage correction in decimal form
:param float brew_house_efficiency: The efficiency in decimal form
:return: Specific Gravity available from Malt
:rtype: float
""" # noqa
validate_percentage(dbcg)
validate_percentage(moisture_content)
validate_percentage(moisture_correction)
validate_percentage(brew_house_efficiency)
gu = (
(dbcg - moisture_content - moisture_correction)
* brew_house_efficiency
<|code_end|>
with the help of current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
, which may contain function names, class names, or code. Output only the next line. | * SUCROSE_PPG |
Given the code snippet: <|code_start|> """
Specialty Grain to LME Weight
:param float grain: Weight of Specialty Grain
:return: LME Weight
:rtype: float
"""
return grain * 0.89
def liquid_malt_to_specialty_grain_weight(malt):
"""
LME to Specialty Grain Weight
:param float grain: Weight of LME
:return: Specialty Grain Weight
:rtype: float
"""
return malt / 0.89
def fine_grind_to_coarse_grind(fine_grind, fc_diff=FC_DIFF_TWO_ROW):
"""
Fine Grind to Coarse Grind Percentage
:param float fine_grind: A percentage from the malt bill
:param float fc_diff: The F/C difference percentage from the malt bill
:return: Coarse Grind Percentage
:rtype: float
"""
<|code_end|>
, generate the next line using the imports in this file:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context (functions, classes, or occasionally code) from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
. Output only the next line. | validate_percentage(fine_grind) |
Continue the code snippet: <|code_start|> validate_percentage(as_is)
validate_percentage(moisture_content)
return as_is / (1.0 - moisture_content)
def sg_from_dry_basis(
dbcg,
moisture_content=MOISTURE_FINISHED_MALT,
moisture_correction=MOISTURE_CORRECTION,
brew_house_efficiency=0.90,
):
"""
Specific Gravity from Dry Basis Percentage
:param float dbcg: Dry Basis Coarse Grain in decimal form
:param float moisture_content: A percentage of moisture content in finished malt in decimal form
:param float moisture_correction: A percentage correction in decimal form
:param float brew_house_efficiency: The efficiency in decimal form
:return: Specific Gravity available from Malt
:rtype: float
""" # noqa
validate_percentage(dbcg)
validate_percentage(moisture_content)
validate_percentage(moisture_correction)
validate_percentage(brew_house_efficiency)
gu = (
(dbcg - moisture_content - moisture_correction)
* brew_house_efficiency
* SUCROSE_PPG
)
<|code_end|>
. Use current file imports:
from ..constants import FC_DIFF_TWO_ROW
from ..constants import LITERS_OF_WORT_AT_SG
from ..constants import MOISTURE_CORRECTION
from ..constants import MOISTURE_FINISHED_MALT
from ..constants import PPG_TO_HWE_CONVERSION
from ..constants import SUCROSE_PLATO
from ..constants import SUCROSE_PPG
from ..validators import validate_percentage
from .sugar import gu_to_sg
and context (classes, functions, or code) from other files:
# Path: brew/constants.py
# FC_DIFF_TWO_ROW = 0.017
#
# Path: brew/constants.py
# LITERS_OF_WORT_AT_SG = 386.0
#
# Path: brew/constants.py
# MOISTURE_CORRECTION = 0.0
#
# Path: brew/constants.py
# MOISTURE_FINISHED_MALT = 0.04
#
# Path: brew/constants.py
# PPG_TO_HWE_CONVERSION = LITER_PER_GAL * POUND_PER_KG
#
# Path: brew/constants.py
# SUCROSE_PLATO = 11.486
#
# Path: brew/constants.py
# SUCROSE_PPG = 46.214
#
# Path: brew/validators.py
# def validate_percentage(percent):
# """
# Validate decimal percentage
#
# :param float percent: Percentage between 0.0 and 1.0
# :return: percentage
# :rtype: float
# :raises ValidatorException: If decimal percentage not between 0.0 and 1.0
# """
# if 0.0 <= percent <= 1.0:
# return percent
# raise ValidatorException(u"Percentage values should be in decimal format")
#
# Path: brew/utilities/sugar.py
# def gu_to_sg(gu):
# """
# Gravity Units to Specific Gravity
#
# :param float gu: Gravity Units
# :return: Specific Gravity
# :rtype: float
# """
# return 1 + (gu / 1000.0)
. Output only the next line. | return gu_to_sg(gu) |
Given the code snippet: <|code_start|> html = value['html']
try:
pdf = pisa.CreatePDF(
StringIO(html.encode('utf-8')), buff, encoding='utf-8'
)
except AttributeError:
raise SethRendererException(u"Error generating PDF file.")
if pdf.err:
raise SethRendererException(u"Error generating PDF file.")
file_name = value.pop('file_name', self.get_filename(value))
self.prepare_response(request, 'application/pdf', file_name, value)
result = buff.getvalue()
buff.close()
return result
class CsvRenderer(BaseSethRenderer):
def __init__(self, info):
self.info = info
def __call__(self, value, system):
request = system['request']
if not 'rows' in value:
raise SethRendererException(u"No rows provided")
buff = StringIO()
<|code_end|>
, generate the next line using the imports in this file:
import logging
from time import time
from cStringIO import StringIO
from pyramid.renderers import render
from seth.helpers.unicodecsv import UnicodeWriter
from xhtml2pdf import pisa
and context (functions, classes, or occasionally code) from other files:
# Path: seth/helpers/unicodecsv.py
# class UnicodeWriter(object):
# def __init__(self, f, dialect=csv.excel, encoding='utf-8', errors='strict',
# *args, **kwds):
# self.encoding = encoding
# self.writer = csv.writer(f, dialect, *args, **kwds)
# self.encoding_errors = errors
#
# def writerow(self, row):
# self.writer.writerow(_stringify_list(row, self.encoding, self.encoding_errors))
#
# def writerows(self, rows):
# for row in rows:
# self.writerow(row)
#
# @property
# def dialect(self):
# return self.writer.dialect
. Output only the next line. | writer = UnicodeWriter(buff, encoding='utf-8') |
Given the code snippet: <|code_start|>
class Model(object):
json_included = []
json_excluded = []
__table_args__ = {}
def _get_attrs_to_include(self):
return self.json_included
@declared_attr
def manager(cls):
# manager is a class that can have some additional methods
# apart from just those provided by sqlalchemy interface
return BaseManager(model_class=cls)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, Boolean
from sqlalchemy.ext.declarative import declared_attr
from seth.decorators import classproperty
from seth.db.managers import BaseManager
and context (functions, classes, or occasionally code) from other files:
# Path: seth/decorators.py
# class classproperty(object):
# def __init__(self, f):
# self.f = f
#
# def __get__(self, obj, owner):
# return self.f(owner)
#
# Path: seth/db/managers.py
# class BaseManager(object):
# """ Proxy manager for all models created as subclasses of
# `*seth.db.base.Model`. Provides basic crud interface
# and couple of utility functions
#
# For example:
#
# .. code-block:: python
#
# MyModel.manager.get_all(1, 2, 3)
# MyModel.manager.first()
# MyModel.manager.create(**{})
# MyModel.manager.find(id=3)
#
# """
# def __init__(self, model_class, **kwargs):
# self.model_class = model_class
#
# @property
# def query(self):
# """ Provides shortcut to sqlalchemy's `*session.query` function
# from manager.
#
# For example:
#
# .. code-block:: python
#
# MyModel.manager.query
#
# or
#
# .. code-block:: python
#
# MyModel.query
#
# """
# return db.get_session().query(self.model_class)
#
# def _isinstance(self, model, raise_error=True):
# rv = isinstance(model, self.model_class)
# if not rv and raise_error:
# raise ValueError('%s is not of type %s' % (model, self.model_class))
# return rv
#
# def validate_params(self, kwargs):
# return kwargs
#
# def save(self, model, **kwargs):
# """ Saves model instance.
# Before actual saving it runs `*_isinstance` function.
# """
# self._isinstance(model)
# db.get_session().add(model)
# return model
#
# def new(self, **kwargs):
# """ Returns new model instance initialized with data
# found in `*kwargs`
# """
# return self.model_class(**self.validate_params(kwargs))
#
# def create(self, **kwargs):
# """ Returns new model instance initialized with data
# found in `*kwargs` and saves it in database.
# """
# return self.save(self.new(**kwargs))
#
# def all(self):
# """ Returns all models from database.
# """
# return self.model_class.query.all()
#
# def get(self, id):
# """ Returns model instance based on primary key or `*None`
# """
# return self.model_class.query.get(id)
#
# def get_all(self, *ids):
# """ Returns all model instances that much primary keys provided
#
# For example:
#
# .. code-block:: python
#
# models = MyModel.manager.get_all(1, 2, 3)
#
# """
# return self.model_class.query.filter(self.model_class.id.in_(ids)).all()
#
# def get_or_404(self, **kwargs):
# """ Returns model instance that matches `*kwargs` or raises `*HTTPNotFound`
# """
#
# obj = self.model_class.query.filter_by(**kwargs).first()
# if not obj:
# raise HTTPNotFound(u"Object doest not exist")
# return obj
#
# def get_or_create(self, **kwargs):
# """ Returns model instance that matches `*kwargs` or creates it
# if it does not exist.
#
# For example:
#
# .. code-block:: python
#
# obj, created = MyModel.manager.get_or_created(id=1)
#
# """
# obj = self.model_class.query.filter_by(**kwargs).first()
# if obj:
# return obj, False
# else:
# return self.create(**kwargs), True
#
# def find(self, **kwargs):
# """ Returns model instances that match `*kwargs`.
# """
#
# return self.model_class.query.filter_by(**kwargs)
#
# def first(self, **kwargs):
# """ Returns first model instance that matches `*kwargs`.
# """
#
# return self.find(**kwargs).first()
#
# def update(self, model, **kwargs):
# self._isinstance(model)
# for k, v in self.validate_params(kwargs).iteritems():
# setattr(model, k, v)
# self.save(model)
# return model
#
# def delete(self, model):
# """ Deletes model instance performing verification first.
# """
#
# self._isinstance(model)
# db.get_session().delete(model)
#
# def filter_query(self, qs=None, filters=None):
# if not qs:
# qs = self.query
#
# filters = filters if filters else []
# for f in filters:
# qs = qs.filter(f)
# return qs
#
# def paginate(self, filters=None, page=1, per_page=20, **kwargs):
# qs = self.filter_query(self.query, filters)
# return paginate(qs, page, per_page, **kwargs)
. Output only the next line. | @classproperty |
Given the following code snippet before the placeholder: <|code_start|>
class Model(object):
json_included = []
json_excluded = []
__table_args__ = {}
def _get_attrs_to_include(self):
return self.json_included
@declared_attr
def manager(cls):
# manager is a class that can have some additional methods
# apart from just those provided by sqlalchemy interface
<|code_end|>
, predict the next line using imports from the current file:
from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, Boolean
from sqlalchemy.ext.declarative import declared_attr
from seth.decorators import classproperty
from seth.db.managers import BaseManager
and context including class names, function names, and sometimes code from other files:
# Path: seth/decorators.py
# class classproperty(object):
# def __init__(self, f):
# self.f = f
#
# def __get__(self, obj, owner):
# return self.f(owner)
#
# Path: seth/db/managers.py
# class BaseManager(object):
# """ Proxy manager for all models created as subclasses of
# `*seth.db.base.Model`. Provides basic crud interface
# and couple of utility functions
#
# For example:
#
# .. code-block:: python
#
# MyModel.manager.get_all(1, 2, 3)
# MyModel.manager.first()
# MyModel.manager.create(**{})
# MyModel.manager.find(id=3)
#
# """
# def __init__(self, model_class, **kwargs):
# self.model_class = model_class
#
# @property
# def query(self):
# """ Provides shortcut to sqlalchemy's `*session.query` function
# from manager.
#
# For example:
#
# .. code-block:: python
#
# MyModel.manager.query
#
# or
#
# .. code-block:: python
#
# MyModel.query
#
# """
# return db.get_session().query(self.model_class)
#
# def _isinstance(self, model, raise_error=True):
# rv = isinstance(model, self.model_class)
# if not rv and raise_error:
# raise ValueError('%s is not of type %s' % (model, self.model_class))
# return rv
#
# def validate_params(self, kwargs):
# return kwargs
#
# def save(self, model, **kwargs):
# """ Saves model instance.
# Before actual saving it runs `*_isinstance` function.
# """
# self._isinstance(model)
# db.get_session().add(model)
# return model
#
# def new(self, **kwargs):
# """ Returns new model instance initialized with data
# found in `*kwargs`
# """
# return self.model_class(**self.validate_params(kwargs))
#
# def create(self, **kwargs):
# """ Returns new model instance initialized with data
# found in `*kwargs` and saves it in database.
# """
# return self.save(self.new(**kwargs))
#
# def all(self):
# """ Returns all models from database.
# """
# return self.model_class.query.all()
#
# def get(self, id):
# """ Returns model instance based on primary key or `*None`
# """
# return self.model_class.query.get(id)
#
# def get_all(self, *ids):
# """ Returns all model instances that much primary keys provided
#
# For example:
#
# .. code-block:: python
#
# models = MyModel.manager.get_all(1, 2, 3)
#
# """
# return self.model_class.query.filter(self.model_class.id.in_(ids)).all()
#
# def get_or_404(self, **kwargs):
# """ Returns model instance that matches `*kwargs` or raises `*HTTPNotFound`
# """
#
# obj = self.model_class.query.filter_by(**kwargs).first()
# if not obj:
# raise HTTPNotFound(u"Object doest not exist")
# return obj
#
# def get_or_create(self, **kwargs):
# """ Returns model instance that matches `*kwargs` or creates it
# if it does not exist.
#
# For example:
#
# .. code-block:: python
#
# obj, created = MyModel.manager.get_or_created(id=1)
#
# """
# obj = self.model_class.query.filter_by(**kwargs).first()
# if obj:
# return obj, False
# else:
# return self.create(**kwargs), True
#
# def find(self, **kwargs):
# """ Returns model instances that match `*kwargs`.
# """
#
# return self.model_class.query.filter_by(**kwargs)
#
# def first(self, **kwargs):
# """ Returns first model instance that matches `*kwargs`.
# """
#
# return self.find(**kwargs).first()
#
# def update(self, model, **kwargs):
# self._isinstance(model)
# for k, v in self.validate_params(kwargs).iteritems():
# setattr(model, k, v)
# self.save(model)
# return model
#
# def delete(self, model):
# """ Deletes model instance performing verification first.
# """
#
# self._isinstance(model)
# db.get_session().delete(model)
#
# def filter_query(self, qs=None, filters=None):
# if not qs:
# qs = self.query
#
# filters = filters if filters else []
# for f in filters:
# qs = qs.filter(f)
# return qs
#
# def paginate(self, filters=None, page=1, per_page=20, **kwargs):
# qs = self.filter_query(self.query, filters)
# return paginate(qs, page, per_page, **kwargs)
. Output only the next line. | return BaseManager(model_class=cls) |
Given the code snippet: <|code_start|> def get(self, **kwargs):
return self.not_allowed()
def post(self, **kwargs):
return self.not_allowed()
def put(self, **kwargs):
return self.not_allowed()
def delete(self, **kwargs):
return self.not_allowed()
def patch(self, **kwargs):
return self.not_allowed()
def head(self, **kwargs):
return self.not_allowed()
def options(self, **kwargs):
return self.not_allowed()
def trace(self, **kwargs):
return self.not_allowed()
def connect(self, **kwargs):
return self.not_allowed()
class QuerySetMixin(object):
model = None
<|code_end|>
, generate the next line using the imports in this file:
from seth.paginator import paginate
and context (functions, classes, or occasionally code) from other files:
# Path: seth/paginator.py
# def paginate(qs, page=1, per_page=20, **kwargs):
# if page < 1:
# raise PaginationException(u"Page has to be grater or equal 1")
#
# if per_page < 0:
# raise PaginationException(u"Page has to be grater than 0")
#
# total = int(qs.count())
#
# if total < (page-1) * per_page:
# page, per_page = 1, 20
#
# items = qs.limit(per_page).offset((page - 1) * per_page).all()
#
# if not items and page != 1:
# return False
#
# return Pagination(qs, page, per_page, total, items, **kwargs)
. Output only the next line. | paginate = True |
Using the snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
class Handler(object):
def __init__(self):
super(Handler, self).__init__()
self.timestamp = None
self.proto = None
self.src_ip = None
self.dst_ip = None
self.sport = None
self.dport = None
self.ident = None
self.length = None
self.data = None
<|code_end|>
, determine the next line of code. You have imports:
import dpkt
import datetime
from ovizart.modules.traffic.log.logger import Logger
and context (class names, function names, or code) available:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
. Output only the next line. | self.log = Logger("TCP Protocol Handler", "DEBUG") |
Using the snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
sys.path.append("../")
class Handler:
def __init__(self, debug_mode="DEBUG"):
<|code_end|>
, determine the next line of code. You have imports:
import sys
import dpkt
from ovizart.modules.traffic.log.logger import Logger
and context (class names, function names, or code) available:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
. Output only the next line. | self._logger = Logger(log_name="Pcap Handler", log_mode=debug_mode) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
class Handler(object):
def __init__(self):
super(Handler, self).__init__()
self.timestamp = None
self.proto = None
self.src_ip = None
self.dst_ip = None
self.sport = None
self.dport = None
self.ident = None
self.length = None
self.data = None
<|code_end|>
. Write the next line using the current file imports:
import dpkt
import datetime
from ovizart.modules.traffic.log.logger import Logger
and context from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
, which may include functions, classes, or code. Output only the next line. | self.log = Logger("TCP Protocol Handler", "DEBUG") |
Continue the code snippet: <|code_start|>
class Handler(object):
def __init__(self):
super(Handler, self).__init__()
def get_flow_ips(self, **args):
result = self.read_conn_log(args['path'], args['parent_hash_value'], args['user_id'])
return result
def read_conn_log(self, path, parent_hash_value, user_id):
result = [] # lets the keys the connection id, values the ts
conn_log_path = os.path.join(path, "conn.log")
f = open(conn_log_path, "r")
for line in f.readlines():
if line.startswith("#"): continue
info = line.split()
tmp = info[2:6]
dt = datetime.datetime.fromtimestamp(float(info[0]))
tmp.append(dt)
<|code_end|>
. Use current file imports:
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import FlowDetails
import os
import datetime
and context (classes, functions, or code) from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
. Output only the next line. | check = FlowDetails.objects.filter(parent_hash_value=parent_hash_value, user_id=user_id, src_ip=tmp[0], sport=int(tmp[1]), |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
class Handler(object):
def __init__(self):
super(Handler, self).__init__()
<|code_end|>
, predict the next line using imports from the current file:
from ovizart.modules.traffic.log.logger import Logger
and context including class names, function names, and sometimes code from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
. Output only the next line. | self.log = Logger("Base Protocol Handler", "DEBUG") |
Predict the next line after this snippet: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
<|code_end|>
using the current file's imports:
from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin
and any relevant context from other files:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
. Output only the next line. | rest_api.register(AppProtocolVisualizePacketCountResource()) |
Here is a snippet: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
rest_api.register(AppProtocolVisualizePacketCountResource())
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin
and context from other files:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
, which may include functions, classes, or code. Output only the next line. | rest_api.register(AllProtocolsResource()) |
Next line prediction: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
rest_api.register(AppProtocolVisualizePacketCountResource())
rest_api.register(AllProtocolsResource())
<|code_end|>
. Use current file imports:
(from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin)
and context including class names, function names, or small code snippets from other files:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
. Output only the next line. | rest_api.register(AllProtocolsByHashResource()) |
Given snippet: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
rest_api.register(AppProtocolVisualizePacketCountResource())
rest_api.register(AllProtocolsResource())
rest_api.register(AllProtocolsByHashResource())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin
and context:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
which might include code, classes, or functions. Output only the next line. | rest_api.register(AppProtocolResourceByHash()) |
Here is a snippet: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
rest_api.register(AppProtocolVisualizePacketCountResource())
rest_api.register(AllProtocolsResource())
rest_api.register(AllProtocolsByHashResource())
rest_api.register(AppProtocolResourceByHash())
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin
and context from other files:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
, which may include functions, classes, or code. Output only the next line. | rest_api.register(AppProtocolVisualizePacketSizeByHashResource()) |
Based on the snippet: <|code_start|>
rest_api = Api(api_name='rest')
rest_api.register(AppProtocolResource())
rest_api.register(AppProtocolVisualizePacketSizeResource())
rest_api.register(AppProtocolVisualizePacketCountResource())
rest_api.register(AllProtocolsResource())
rest_api.register(AllProtocolsByHashResource())
rest_api.register(AppProtocolResourceByHash())
rest_api.register(AppProtocolVisualizePacketSizeByHashResource())
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls.defaults import *
from django.conf import settings
from tastypie.api import Api
from ovizart.api.api import AppProtocolResource, AppProtocolVisualizePacketSizeResource, \
AppProtocolVisualizePacketCountResource, AllProtocolsResource, \
AllProtocolsByHashResource, AppProtocolResourceByHash, \
AppProtocolVisualizePacketSizeByHashResource, \
AppProtocolVisualizePacketCountByHashResource
from django.contrib import admin
and context (classes, functions, sometimes code) from other files:
# Path: ovizart/api/api.py
# class AppProtocolResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'user_id': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
#
# class AllProtocolsResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
#
# class AllProtocolsByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'all_protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# serializer = AllProtocolsJSONSerializer()
# filtering = {
# 'parent_hash_value': ALL,
# }
#
# class AppProtocolResourceByHash(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocols_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# }
# serializer = CustomJSONSerializer()
#
# class AppProtocolVisualizePacketSizeByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_size_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketSizeCustomJSONSerializer()
#
# class AppProtocolVisualizePacketCountByHashResource(ModelResource):
# class Meta:
# queryset = FlowDetails.objects.all()
# resource_name = 'protocol_count_by_hash'
# list_allowed_methods = ['get']
# detail_allowed_methods = ['get']
# limit = 0 # unlimited
# filtering = {
# 'parent_hash_value': ALL,
# 'protocol': ALL,
# }
# serializer = AppProtocolPacketCountCustomJSONSerializer()
. Output only the next line. | rest_api.register(AppProtocolVisualizePacketCountByHashResource()) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
sys.path.append("../")
class Handler:
def __init__(self, handler, debug_mode="DEBUG"):
self.pcap = handler.get_pcap()
self.pcap_handler = handler
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from ovizart.modules.traffic.pcap.handler import Handler
from ovizart.modules.traffic.log.logger import Logger
from ovizart.modules.utils.handler import generate_random_name
and context (classes, functions, sometimes code) from other files:
# Path: ovizart/modules/traffic/pcap/handler.py
# class Handler:
#
# def __init__(self, debug_mode="DEBUG"):
# self._logger = Logger(log_name="Pcap Handler", log_mode=debug_mode)
# self._logger.message("Pcap Handler initialized")
# self._pcap = None
# self._filter_type = None
# self._file_pointer = None
#
# def open_file(self, pcap_file, mode="rb"):
# try:
# self._file_pointer = file(pcap_file, mode)
# self._logger.set_log_level("DEBUG")
# self._logger.message(("%s is opened at %s mode") % (pcap_file, mode))
# except:
# self._logger.set_log_level("ERROR")
# self._logger.message("Error at opening pcap file")
#
# def open_pcap(self, mode="r"):
# if mode == "r":
# self._pcap = dpkt.pcap.Reader(self._file_pointer)
# self._logger.set_log_level("DEBUG")
# self._logger.message("pcap reader is created")
# if mode == "w":
# self._pcap = dpkt.pcap.Writer(self._file_pointer)
#
# def write_pcap(self, buf, ts):
# self._pcap.writepkt(buf, ts)
#
# def close_file(self):
# self._file_pointer.close()
#
# def set_filter_type(self, t):
# self._filter_type = t
# self._logger.set_log_level("DEBUG")
# self._logger.message(("Filter type is set %s") % (t))
#
# def get_filter_type(self):
# return self._filter_type
#
# def get_pcap(self):
# return self._pcap
#
# def get_eth(self, buf):
# eth = dpkt.ethernet.Ethernet(buf)
# if eth.type == dpkt.ethernet.ETH_TYPE_IP:
# return eth
# else:
# self._logger.set_log_level("ERROR")
# self._logger.message("No Eth is returned")
# return False
#
# def get_ip(self, eth):
# ip = eth.data
# if ip.p == dpkt.ip.IP_PROTO_TCP:
# return ip
# else:
# self._logger.set_log_level("ERROR")
# self._logger.message("No IP is returned")
# return False
#
# def get_tcp(self, ip):
# tcp = ip.data
# #self._logger.message(("TCP is returned %s") % (tcp))
# return tcp
#
# def get_udp(self, ip):
# udp = ip.data
# return udp
#
# def get_reader(self):
# return self._pcap
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/modules/utils/handler.py
# def generate_random_name(N):
# return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
. Output only the next line. | self._logger = Logger(log_name="Flow Handler", log_mode=debug_mode) |
Continue the code snippet: <|code_start|> continue
#src_ip = self.ip.src
#dst_ip = self.ip.dst
# for human readable ip
# from socket import inet_ntoa
# inet_ntoa(dst_ip)
if self.pcap_handler.get_filter_type() == "TCP":
if not ip:
continue
tcp = self.pcap_handler.get_tcp(ip)
forward_index = (ip.src, tcp.sport, ip.dst, tcp.dport)
backward_index = (ip.dst, tcp.dport, ip.src, tcp.sport)
if index.has_key(forward_index):
flow_num = index[forward_index]
elif index.has_key(backward_index):
flow_num = index[backward_index]
direction[flow_num] = 2
else:
index[forward_index] = flow_id
flow_num = flow_id
direction[flow_num] = 1
if flow.has_key(flow_num):
flow[flow_num].append((buf,ts))
else:
flow[flow_num] = [(buf, ts)]
flow_id += 1
return flow, direction
def save_flow(self, flow, pcap_handler, save_path=""):
<|code_end|>
. Use current file imports:
import sys
from ovizart.modules.traffic.pcap.handler import Handler
from ovizart.modules.traffic.log.logger import Logger
from ovizart.modules.utils.handler import generate_random_name
and context (classes, functions, or code) from other files:
# Path: ovizart/modules/traffic/pcap/handler.py
# class Handler:
#
# def __init__(self, debug_mode="DEBUG"):
# self._logger = Logger(log_name="Pcap Handler", log_mode=debug_mode)
# self._logger.message("Pcap Handler initialized")
# self._pcap = None
# self._filter_type = None
# self._file_pointer = None
#
# def open_file(self, pcap_file, mode="rb"):
# try:
# self._file_pointer = file(pcap_file, mode)
# self._logger.set_log_level("DEBUG")
# self._logger.message(("%s is opened at %s mode") % (pcap_file, mode))
# except:
# self._logger.set_log_level("ERROR")
# self._logger.message("Error at opening pcap file")
#
# def open_pcap(self, mode="r"):
# if mode == "r":
# self._pcap = dpkt.pcap.Reader(self._file_pointer)
# self._logger.set_log_level("DEBUG")
# self._logger.message("pcap reader is created")
# if mode == "w":
# self._pcap = dpkt.pcap.Writer(self._file_pointer)
#
# def write_pcap(self, buf, ts):
# self._pcap.writepkt(buf, ts)
#
# def close_file(self):
# self._file_pointer.close()
#
# def set_filter_type(self, t):
# self._filter_type = t
# self._logger.set_log_level("DEBUG")
# self._logger.message(("Filter type is set %s") % (t))
#
# def get_filter_type(self):
# return self._filter_type
#
# def get_pcap(self):
# return self._pcap
#
# def get_eth(self, buf):
# eth = dpkt.ethernet.Ethernet(buf)
# if eth.type == dpkt.ethernet.ETH_TYPE_IP:
# return eth
# else:
# self._logger.set_log_level("ERROR")
# self._logger.message("No Eth is returned")
# return False
#
# def get_ip(self, eth):
# ip = eth.data
# if ip.p == dpkt.ip.IP_PROTO_TCP:
# return ip
# else:
# self._logger.set_log_level("ERROR")
# self._logger.message("No IP is returned")
# return False
#
# def get_tcp(self, ip):
# tcp = ip.data
# #self._logger.message(("TCP is returned %s") % (tcp))
# return tcp
#
# def get_udp(self, ip):
# udp = ip.data
# return udp
#
# def get_reader(self):
# return self._pcap
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/modules/utils/handler.py
# def generate_random_name(N):
# return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
. Output only the next line. | random_key = generate_random_name(10) |
Predict the next line for this snippet: <|code_start|># Create your views here.
def login_user(request):
log = Logger("Login form", "DEBUG")
form = None
logged = False
if request.session.has_key('logged_in'):
logged = True
if logged or request.method == "POST":
<|code_end|>
with the help of current file imports:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.conf import settings
from ovizart.main.forms import LoginForm
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
from ovizart.pcap.models import UserJSonFile
from django.utils import simplejson as json
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Flow, FlowDetails, PacketDetails
from django.core.paginator import Paginator, InvalidPage, EmptyPage
import urllib2
import tempfile
import os
and context from other files:
# Path: ovizart/main/forms.py
# class LoginForm(ModelForm):
# user_email = forms.EmailField()
# class Meta:
# model = User
# fields = ('username', 'user_email', 'password')
#
# def clean(self):
# data = self.cleaned_data
# email = data.get('user_email')
# if not email:
# raise forms.ValidationError(u'Email can not be empty!')
# hash = hashlib.sha1()
# hash.update(email)
# email_hash = hash.hexdigest()
# username = self.cleaned_data.get('username')
# if not username:
# raise forms.ValidationError(u'Username can not be empty!')
# try:
# user = User.objects.get(username=username)
# except User.DoesNotExist:
# raise forms.ValidationError(u'User does not exist.')
# if email and UserProfile.objects.filter(user_email=email_hash, user=user).count():
# return data
# else:
# raise forms.ValidationError(u'Profile for the user does not exist')
#
# Path: ovizart/pcap/models.py
# class UserJSonFile(models.Model):
# user_id = models.CharField(max_length=100)
# json_type = models.CharField(max_length=10) # possible value is summary for the summary view
# json_file_name = models.CharField(max_length=100) # save the name of the already created file name on disk
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Flow(models.Model):
# user_id = models.CharField(max_length=100)
# hash_value = models.CharField(max_length=50)
# file_name = models.CharField(max_length=50)
# upload_time = models.DateTimeField()
# file_type = models.CharField(max_length=150)
# file_size = models.IntegerField()
# path = models.FilePathField()
# pcaps = ListField(EmbeddedModelField('Pcap', null=True, blank=True))
# details = ListField(EmbeddedModelField('FlowDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
#
# class PacketDetails(models.Model):
# #datetime.datetime.fromtimestamp(float("1286715787.71")).strftime('%Y-%m-%d %H:%M:%S')
# ident = models.IntegerField()
# flow_hash = models.CharField(max_length=50)
# timestamp = models.DateTimeField()
# length = models.IntegerField()
# protocol = models.IntegerField()
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# data = models.TextField(null=True, blank=True)
#
# def __unicode__(self):
# return u'(%s, %s, %s, %s, %s)' % (self.protocol, self.src_ip, self.sport, self.dst_ip, self.dport)
#
# objects = MongoDBManager()
, which may contain function names, class names, or code. Output only the next line. | form = LoginForm(request.POST) |
Continue the code snippet: <|code_start|> summary_protocol = protocol
summaries = PacketDetails.objects.filter(protocol=proto_dict[protocol])
summary = filter(lambda x: x.timestamp.year == int(date), summaries)
paginator = Paginator(summary, 15)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
page_summary = paginator.page(page)
except (EmptyPage, InvalidPage):
page_summary = paginator.page(paginator.num_pages)
context = {
'page_title': 'Protocol Summary',
'page_summary': page_summary,
'summary_type': summary_type,
'summary_protocol': summary_protocol
}
return render_to_response("main/flow_summary.html", context,
context_instance=RequestContext(request))
def main(request):
<|code_end|>
. Use current file imports:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.conf import settings
from ovizart.main.forms import LoginForm
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
from ovizart.pcap.models import UserJSonFile
from django.utils import simplejson as json
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Flow, FlowDetails, PacketDetails
from django.core.paginator import Paginator, InvalidPage, EmptyPage
import urllib2
import tempfile
import os
and context (classes, functions, or code) from other files:
# Path: ovizart/main/forms.py
# class LoginForm(ModelForm):
# user_email = forms.EmailField()
# class Meta:
# model = User
# fields = ('username', 'user_email', 'password')
#
# def clean(self):
# data = self.cleaned_data
# email = data.get('user_email')
# if not email:
# raise forms.ValidationError(u'Email can not be empty!')
# hash = hashlib.sha1()
# hash.update(email)
# email_hash = hash.hexdigest()
# username = self.cleaned_data.get('username')
# if not username:
# raise forms.ValidationError(u'Username can not be empty!')
# try:
# user = User.objects.get(username=username)
# except User.DoesNotExist:
# raise forms.ValidationError(u'User does not exist.')
# if email and UserProfile.objects.filter(user_email=email_hash, user=user).count():
# return data
# else:
# raise forms.ValidationError(u'Profile for the user does not exist')
#
# Path: ovizart/pcap/models.py
# class UserJSonFile(models.Model):
# user_id = models.CharField(max_length=100)
# json_type = models.CharField(max_length=10) # possible value is summary for the summary view
# json_file_name = models.CharField(max_length=100) # save the name of the already created file name on disk
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Flow(models.Model):
# user_id = models.CharField(max_length=100)
# hash_value = models.CharField(max_length=50)
# file_name = models.CharField(max_length=50)
# upload_time = models.DateTimeField()
# file_type = models.CharField(max_length=150)
# file_size = models.IntegerField()
# path = models.FilePathField()
# pcaps = ListField(EmbeddedModelField('Pcap', null=True, blank=True))
# details = ListField(EmbeddedModelField('FlowDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
#
# class PacketDetails(models.Model):
# #datetime.datetime.fromtimestamp(float("1286715787.71")).strftime('%Y-%m-%d %H:%M:%S')
# ident = models.IntegerField()
# flow_hash = models.CharField(max_length=50)
# timestamp = models.DateTimeField()
# length = models.IntegerField()
# protocol = models.IntegerField()
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# data = models.TextField(null=True, blank=True)
#
# def __unicode__(self):
# return u'(%s, %s, %s, %s, %s)' % (self.protocol, self.src_ip, self.sport, self.dst_ip, self.dport)
#
# objects = MongoDBManager()
. Output only the next line. | flows = Flow.objects.all().order_by("-upload_time") |
Using the snippet: <|code_start|> context = {
'form': form,
'page_title': 'Login Page'
}
return render_to_response("main/login.html", context,
context_instance=RequestContext(request))
def logout_user(request):
if request.session.has_key('uploaded_hash'):
del request.session['uploaded_hash']
if request.session.has_key('uploaded_file_name'):
del request.session['uploaded_file_name']
logout(request)
return HttpResponseRedirect(reverse('login_page'))
def welcome(request):
context = {
'page_title': 'Welcome to %s' % settings.PROJECT_NAME
}
if request.user.is_authenticated():
return render_to_response("main/welcome.html", context,
context_instance=RequestContext(request))
else:
return HttpResponseRedirect(reverse('login_page'))
def flow_protocol_summary(request, protocol, date):
if protocol not in ['UDP', 'TCP']:
summary_type = "flow"
summary_protocol = protocol
<|code_end|>
, determine the next line of code. You have imports:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.conf import settings
from ovizart.main.forms import LoginForm
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
from ovizart.pcap.models import UserJSonFile
from django.utils import simplejson as json
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Flow, FlowDetails, PacketDetails
from django.core.paginator import Paginator, InvalidPage, EmptyPage
import urllib2
import tempfile
import os
and context (class names, function names, or code) available:
# Path: ovizart/main/forms.py
# class LoginForm(ModelForm):
# user_email = forms.EmailField()
# class Meta:
# model = User
# fields = ('username', 'user_email', 'password')
#
# def clean(self):
# data = self.cleaned_data
# email = data.get('user_email')
# if not email:
# raise forms.ValidationError(u'Email can not be empty!')
# hash = hashlib.sha1()
# hash.update(email)
# email_hash = hash.hexdigest()
# username = self.cleaned_data.get('username')
# if not username:
# raise forms.ValidationError(u'Username can not be empty!')
# try:
# user = User.objects.get(username=username)
# except User.DoesNotExist:
# raise forms.ValidationError(u'User does not exist.')
# if email and UserProfile.objects.filter(user_email=email_hash, user=user).count():
# return data
# else:
# raise forms.ValidationError(u'Profile for the user does not exist')
#
# Path: ovizart/pcap/models.py
# class UserJSonFile(models.Model):
# user_id = models.CharField(max_length=100)
# json_type = models.CharField(max_length=10) # possible value is summary for the summary view
# json_file_name = models.CharField(max_length=100) # save the name of the already created file name on disk
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Flow(models.Model):
# user_id = models.CharField(max_length=100)
# hash_value = models.CharField(max_length=50)
# file_name = models.CharField(max_length=50)
# upload_time = models.DateTimeField()
# file_type = models.CharField(max_length=150)
# file_size = models.IntegerField()
# path = models.FilePathField()
# pcaps = ListField(EmbeddedModelField('Pcap', null=True, blank=True))
# details = ListField(EmbeddedModelField('FlowDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
#
# class PacketDetails(models.Model):
# #datetime.datetime.fromtimestamp(float("1286715787.71")).strftime('%Y-%m-%d %H:%M:%S')
# ident = models.IntegerField()
# flow_hash = models.CharField(max_length=50)
# timestamp = models.DateTimeField()
# length = models.IntegerField()
# protocol = models.IntegerField()
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# data = models.TextField(null=True, blank=True)
#
# def __unicode__(self):
# return u'(%s, %s, %s, %s, %s)' % (self.protocol, self.src_ip, self.sport, self.dst_ip, self.dport)
#
# objects = MongoDBManager()
. Output only the next line. | summaries = FlowDetails.objects.filter(protocol=protocol) |
Given the following code snippet before the placeholder: <|code_start|> context_instance=RequestContext(request))
def logout_user(request):
if request.session.has_key('uploaded_hash'):
del request.session['uploaded_hash']
if request.session.has_key('uploaded_file_name'):
del request.session['uploaded_file_name']
logout(request)
return HttpResponseRedirect(reverse('login_page'))
def welcome(request):
context = {
'page_title': 'Welcome to %s' % settings.PROJECT_NAME
}
if request.user.is_authenticated():
return render_to_response("main/welcome.html", context,
context_instance=RequestContext(request))
else:
return HttpResponseRedirect(reverse('login_page'))
def flow_protocol_summary(request, protocol, date):
if protocol not in ['UDP', 'TCP']:
summary_type = "flow"
summary_protocol = protocol
summaries = FlowDetails.objects.filter(protocol=protocol)
else:
proto_dict = {'TCP': 6, 'UDP': 17}
summary_type = "packets"
summary_protocol = protocol
<|code_end|>
, predict the next line using imports from the current file:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.conf import settings
from ovizart.main.forms import LoginForm
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
from ovizart.pcap.models import UserJSonFile
from django.utils import simplejson as json
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Flow, FlowDetails, PacketDetails
from django.core.paginator import Paginator, InvalidPage, EmptyPage
import urllib2
import tempfile
import os
and context including class names, function names, and sometimes code from other files:
# Path: ovizart/main/forms.py
# class LoginForm(ModelForm):
# user_email = forms.EmailField()
# class Meta:
# model = User
# fields = ('username', 'user_email', 'password')
#
# def clean(self):
# data = self.cleaned_data
# email = data.get('user_email')
# if not email:
# raise forms.ValidationError(u'Email can not be empty!')
# hash = hashlib.sha1()
# hash.update(email)
# email_hash = hash.hexdigest()
# username = self.cleaned_data.get('username')
# if not username:
# raise forms.ValidationError(u'Username can not be empty!')
# try:
# user = User.objects.get(username=username)
# except User.DoesNotExist:
# raise forms.ValidationError(u'User does not exist.')
# if email and UserProfile.objects.filter(user_email=email_hash, user=user).count():
# return data
# else:
# raise forms.ValidationError(u'Profile for the user does not exist')
#
# Path: ovizart/pcap/models.py
# class UserJSonFile(models.Model):
# user_id = models.CharField(max_length=100)
# json_type = models.CharField(max_length=10) # possible value is summary for the summary view
# json_file_name = models.CharField(max_length=100) # save the name of the already created file name on disk
#
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Flow(models.Model):
# user_id = models.CharField(max_length=100)
# hash_value = models.CharField(max_length=50)
# file_name = models.CharField(max_length=50)
# upload_time = models.DateTimeField()
# file_type = models.CharField(max_length=150)
# file_size = models.IntegerField()
# path = models.FilePathField()
# pcaps = ListField(EmbeddedModelField('Pcap', null=True, blank=True))
# details = ListField(EmbeddedModelField('FlowDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
#
# class PacketDetails(models.Model):
# #datetime.datetime.fromtimestamp(float("1286715787.71")).strftime('%Y-%m-%d %H:%M:%S')
# ident = models.IntegerField()
# flow_hash = models.CharField(max_length=50)
# timestamp = models.DateTimeField()
# length = models.IntegerField()
# protocol = models.IntegerField()
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# data = models.TextField(null=True, blank=True)
#
# def __unicode__(self):
# return u'(%s, %s, %s, %s, %s)' % (self.protocol, self.src_ip, self.sport, self.dst_ip, self.dport)
#
# objects = MongoDBManager()
. Output only the next line. | summaries = PacketDetails.objects.filter(protocol=proto_dict[protocol]) |
Given snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
#hachoir related imports
class Handler:
def __init__(self):
self.file_path = None
self.file_name = None
self.stream = None
self.data = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import os
from django.conf import settings
from ovizart.modules.traffic.log.logger import Logger
from ovizart.modules.utils.handler import generate_name_from_timestame
from hachoir_core.cmd_line import unicodeFilename
from hachoir_core.stream import FileInputStream
from hachoir_regex.pattern import PatternMatching
from hachoir_core.stream.input import NullStreamError
and context:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/modules/utils/handler.py
# def generate_name_from_timestame():
# timestamp = str(time.time())
# md5 = hashlib.md5(timestamp)
# return md5.hexdigest()
which might include code, classes, or functions. Output only the next line. | self.log = Logger("File Handler", "DEBUG") |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
#hachoir related imports
class Handler:
def __init__(self):
self.file_path = None
self.file_name = None
self.stream = None
self.data = None
self.log = Logger("File Handler", "DEBUG")
def create_dir(self):
now = datetime.datetime.now()
self.log.message("Now is: %s:" % now)
directory_name = now.strftime("%d-%m-%y")
self.log.message("Directory name: %s:" % directory_name)
directory_path = "/".join([settings.PROJECT_ROOT, "uploads", directory_name])
self.log.message("Directory path: %s" % directory_path)
if not os.path.exists(directory_path):
os.mkdir(directory_path)
self.log.message("Directory created")
# we need to create another directory also for each upload
<|code_end|>
using the current file's imports:
import datetime
import os
from django.conf import settings
from ovizart.modules.traffic.log.logger import Logger
from ovizart.modules.utils.handler import generate_name_from_timestame
from hachoir_core.cmd_line import unicodeFilename
from hachoir_core.stream import FileInputStream
from hachoir_regex.pattern import PatternMatching
from hachoir_core.stream.input import NullStreamError
and any relevant context from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/modules/utils/handler.py
# def generate_name_from_timestame():
# timestamp = str(time.time())
# md5 = hashlib.md5(timestamp)
# return md5.hexdigest()
. Output only the next line. | new_dir = generate_name_from_timestame() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
RESCAN_URL = "https://www.virustotal.com/vtapi/v2/file/rescan"
API_KEY = "891c2810d3931fac5af1a2861ac9db18e508a972bb1eaa03d0b43428938d4b93"
HOST = "www.virustotal.com"
SCAN_URL = "https://www.virustotal.com/vtapi/v2/file/scan"
REPORT_URL = "https://www.virustotal.com/vtapi/v2/file/report"
class Handler:
def __init__(self):
<|code_end|>
with the help of current file imports:
import simplejson
import urllib
import urllib2
import os
from ovizart.modules.malware.virustotal import postfile
from ovizart.modules.md5.handler import Handler as MD5Handler
and context from other files:
# Path: ovizart/modules/md5/handler.py
# class Handler:
# def __init__(self):
# self._file_name = None
#
# def set_file(self, file_name):
# self._file_name = file_name
#
# def get_hash(self, file_name):
# self._file_name = file_name
# md5 = hashlib.md5()
# with open(self._file_name, 'rb') as f:
# for chunk in iter(lambda: f.read(8192), b''):
# md5.update(chunk)
# return md5.hexdigest()
, which may contain function names, class names, or code. Output only the next line. | self.md5_handler = MD5Handler() |
Here is a snippet: <|code_start|> self.file_name_li = []
self.flow = None
self.toProcess = dict()
self.reportRoot = None
self.streamcounter = 0
def get_flow_ips(self, **args):
path = args['path']
file_name = args['file_name']
self.reportRoot = path
full_path = "/".join([path, file_name])
cmd = " ".join(["tcpflow -v -r", full_path])
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=path).communicate()[1]
result = []
for line in output.split("\n"):
if "new flow" in line:
# the the created flow files are the ones that we are looking for
ip = line.split(":")[1].strip()
# test whether this is an smtp flow
smtp_flow_file_path = "/".join([path, ip])
if not self.decode_SMTP(smtp_flow_file_path):
continue
self.file_name_li.append(ip)
src_ip, sport, dst_ip, dport = self.parse_aFile(ip)
packet = None
found = False
for pcap in self.flow.pcaps:
# this line is required, otherwise pcap.pcakets is not returning the info
<|code_end|>
. Write the next line using the current file imports:
import base64
import hashlib
import os.path, os
import subprocess
import email, mimetypes
import zipfile
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Pcap, SMTPDetails, FlowDetails
and context from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Pcap(models.Model):
# hash_value = models.CharField(max_length=100)
# file_name = models.FileField(upload_to="uploads", null=True, blank=True)
# path = models.FilePathField()
# packets = ListField(EmbeddedModelField('PacketDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class SMTPDetails(models.Model):
# login_data = ListField(null=True, blank=True)
# msg_from = models.CharField(max_length=100, null=True, blank=True)
# rcpt_to = models.CharField(max_length=100, null=True, blank=True)
# raw = models.TextField(null=True, blank=True)
# msgdata = models.TextField(null=True, blank=True)
# attachment_path = ListField(null=True, blank=True)
# flow_details = EmbeddedModelField('FlowDetails', null=True, blank=True)
#
# objects = MongoDBManager()
#
# def get_path_dict(self):
# #/home/oguz/git/ovizart/ovizart/uploads/16-06-12/a6a6defb7253043a55281d01aa66538a/smtp-messages/1/part-001.ksh
# result = []
# for path in self.attachment_path:
# tmp = dict()
# r = path.split("uploads")
# file_name = os.path.basename(r[1])
# tmp['file_name'] = file_name
# tmp['path'] = r[1]
# result.append(tmp)
#
# return result
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
, which may include functions, classes, or code. Output only the next line. | pcap = Pcap.objects.get(id = pcap.id) |
Based on the snippet: <|code_start|> self.report_SMTP(f, smtp_details)
def process_SMTP(self, aFile):
a = False
b = False
for i in self.toProcess[aFile]['raw']:
if a and i.startswith("MAIL FROM"):
a = False
if b and i == ".":
b = False
if a:
self.toProcess[aFile]['logindata'].append(i)
if b:
self.toProcess[aFile]['msgdata'].append(i)
if i == "AUTH LOGIN":
a = True
self.toProcess[aFile]['logindata'] = []
if i == "DATA":
b = True
self.toProcess[aFile]['msgdata'] = []
if i.startswith("MAIL FROM:"):
self.toProcess[aFile]['msg_from'] = i[11:]
if i.startswith("RCPT TO:"):
self.toProcess[aFile]['rcpt_to'] = i[9:]
ip = aFile
src_ip, sport, dst_ip, dport = self.parse_aFile(ip)
flow_details = FlowDetails.objects.get(src_ip=src_ip, sport=sport, dst_ip=dst_ip, dport=dport)
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
import hashlib
import os.path, os
import subprocess
import email, mimetypes
import zipfile
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Pcap, SMTPDetails, FlowDetails
and context (classes, functions, sometimes code) from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Pcap(models.Model):
# hash_value = models.CharField(max_length=100)
# file_name = models.FileField(upload_to="uploads", null=True, blank=True)
# path = models.FilePathField()
# packets = ListField(EmbeddedModelField('PacketDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class SMTPDetails(models.Model):
# login_data = ListField(null=True, blank=True)
# msg_from = models.CharField(max_length=100, null=True, blank=True)
# rcpt_to = models.CharField(max_length=100, null=True, blank=True)
# raw = models.TextField(null=True, blank=True)
# msgdata = models.TextField(null=True, blank=True)
# attachment_path = ListField(null=True, blank=True)
# flow_details = EmbeddedModelField('FlowDetails', null=True, blank=True)
#
# objects = MongoDBManager()
#
# def get_path_dict(self):
# #/home/oguz/git/ovizart/ovizart/uploads/16-06-12/a6a6defb7253043a55281d01aa66538a/smtp-messages/1/part-001.ksh
# result = []
# for path in self.attachment_path:
# tmp = dict()
# r = path.split("uploads")
# file_name = os.path.basename(r[1])
# tmp['file_name'] = file_name
# tmp['path'] = r[1]
# result.append(tmp)
#
# return result
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
. Output only the next line. | smtp_details = SMTPDetails.objects.create(login_data=self.toProcess[aFile]['logindata'], |
Given the following code snippet before the placeholder: <|code_start|> smtp_details = self.process_SMTP(f)
self.report_SMTP(f, smtp_details)
def process_SMTP(self, aFile):
a = False
b = False
for i in self.toProcess[aFile]['raw']:
if a and i.startswith("MAIL FROM"):
a = False
if b and i == ".":
b = False
if a:
self.toProcess[aFile]['logindata'].append(i)
if b:
self.toProcess[aFile]['msgdata'].append(i)
if i == "AUTH LOGIN":
a = True
self.toProcess[aFile]['logindata'] = []
if i == "DATA":
b = True
self.toProcess[aFile]['msgdata'] = []
if i.startswith("MAIL FROM:"):
self.toProcess[aFile]['msg_from'] = i[11:]
if i.startswith("RCPT TO:"):
self.toProcess[aFile]['rcpt_to'] = i[9:]
ip = aFile
src_ip, sport, dst_ip, dport = self.parse_aFile(ip)
<|code_end|>
, predict the next line using imports from the current file:
import base64
import hashlib
import os.path, os
import subprocess
import email, mimetypes
import zipfile
from ovizart.modules.traffic.log.logger import Logger
from ovizart.pcap.models import Pcap, SMTPDetails, FlowDetails
and context including class names, function names, and sometimes code from other files:
# Path: ovizart/modules/traffic/log/logger.py
# class Logger:
#
# def __init__(self, log_name, log_mode):
# logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
# self.mode = log_mode
# self.log = logging.getLogger(log_name)
# self.log.setLevel(log_mode)
#
# def set_log_level(self, level="DEBUG"):
# self.log.setLevel(level)
#
# def message(self, message):
# if self.mode == "DEBUG":
# self.log.debug(message)
# if self.mode == "ERROR":
# self.log.error(message)
# if self.mode == "INFO":
# self.log.info(message)
#
# Path: ovizart/pcap/models.py
# class Pcap(models.Model):
# hash_value = models.CharField(max_length=100)
# file_name = models.FileField(upload_to="uploads", null=True, blank=True)
# path = models.FilePathField()
# packets = ListField(EmbeddedModelField('PacketDetails', null=True, blank=True))
#
# def __unicode__(self):
# return u'%s/%s' % (self.path, self.file_name)
#
# def get_upload_path(self):
# hash_dir = os.path.basename(self.path)
# root = os.path.basename(os.path.dirname(self.path))
# return os.path.join(root, hash_dir)
#
# class SMTPDetails(models.Model):
# login_data = ListField(null=True, blank=True)
# msg_from = models.CharField(max_length=100, null=True, blank=True)
# rcpt_to = models.CharField(max_length=100, null=True, blank=True)
# raw = models.TextField(null=True, blank=True)
# msgdata = models.TextField(null=True, blank=True)
# attachment_path = ListField(null=True, blank=True)
# flow_details = EmbeddedModelField('FlowDetails', null=True, blank=True)
#
# objects = MongoDBManager()
#
# def get_path_dict(self):
# #/home/oguz/git/ovizart/ovizart/uploads/16-06-12/a6a6defb7253043a55281d01aa66538a/smtp-messages/1/part-001.ksh
# result = []
# for path in self.attachment_path:
# tmp = dict()
# r = path.split("uploads")
# file_name = os.path.basename(r[1])
# tmp['file_name'] = file_name
# tmp['path'] = r[1]
# result.append(tmp)
#
# return result
#
# class FlowDetails(models.Model):
# parent_hash_value = models.CharField(max_length=50)
# user_id = models.CharField(max_length=100)
# src_ip = models.IPAddressField()
# dst_ip = models.IPAddressField()
# sport = models.IntegerField()
# dport = models.IntegerField()
# protocol = models.CharField(max_length=10)
# timestamp = models.DateTimeField()
#
# objects = MongoDBManager()
. Output only the next line. | flow_details = FlowDetails.objects.get(src_ip=src_ip, sport=sport, dst_ip=dst_ip, dport=dport) |
Next line prediction: <|code_start|>""""ML-ENSEMBLE
Testing suite for Layer and Transformer
"""
def test_fit():
"""[Parallel | Layer | Threading | Subset | No Proba | No Prep] test fit"""
args = get_layer('fit', 'threading', 'subsemble', False, False)
<|code_end|>
. Use current file imports:
(from mlens.testing import get_layer, run_layer)
and context including class names, function names, or small code snippets from other files:
# Path: mlens/testing/dummy.py
# def get_layer(self, kls, proba, preprocessing, *args, **kwargs):
# """Generate a layer instance.
#
# Parameters
# ----------
# kls : str
# class type
#
# proba : bool
# whether to set ``proba`` to ``True``
#
# preprocessing : bool
# layer with preprocessing cases
# """
# indexer, kwargs = self.load_indexer(kls, args, kwargs)
#
# learner_kwargs = {'proba': kwargs.pop('proba', proba),
# 'scorer': kwargs.pop('scorer', None)}
#
# layer = Layer(name='layer', dtype=np.float64, **kwargs)
#
# if preprocessing:
# ests = ESTIMATORS_PROBA if proba else ESTIMATORS
# prep = PREPROCESSING
# else:
# ests = ECM_PROBA if proba else ECM
# prep = []
#
# group = make_group(indexer, ests, prep,
# learner_kwargs=learner_kwargs, name='group')
# layer.push(group)
# return layer
#
# def run_layer(job, layer, X, y, F, wf=None):
# """Sub-routine for running learner job"""
# if job != 'fit':
# run_layer('fit', layer, X, y, F)
#
# P = np.zeros(F.shape)
#
# path = _get_path(layer.backend, is_learner=False)
# args = {
# 'dir': path,
# 'job': job,
# 'auxiliary': {'X': X, 'y': y} if job == 'fit' else {'X': X},
# 'main': {'X': X, 'y': y, 'P': P} if job == 'fit' else {'X': X, 'P': P}
# }
#
# if layer.backend == 'manual':
# # Run manually
# layer.setup(X, y, job)
# if layer.transformers:
# for transformer in layer.transformers:
# for subtransformer in transformer(args, 'auxiliary'):
# subtransformer()
# for learner in layer.learners:
# for sublearner in learner(args, 'main'):
# sublearner()
#
# if job == 'fit':
# layer.collect()
#
# else:
# args = (X, y) if job == 'fit' else (X,)
# with ParallelProcessing(layer.backend, layer.n_jobs) as manager:
# P = manager.map(layer, job, *args, path=path, return_preds=True)
#
# if isinstance(path, str) and layer.backend == 'manual':
# try:
# shutil.rmtree(path)
# except OSError:
# warnings.warn(
# "Failed to destroy temporary test cache at %s" % path)
#
# if wf is not None:
# if job in ['fit', 'transform']:
# w = [obj.estimator.coef_
# for lr in layer.learners for obj in lr.sublearners]
# else:
# w = [obj.estimator.coef_
# for lr in layer.learners for obj in lr.learner]
# np.testing.assert_array_equal(P, F)
# np.testing.assert_array_equal(w, wf)
#
# assert P.__class__.__name__ == 'ndarray'
# assert w[0].__class__.__name__ == 'ndarray'
. Output only the next line. | run_layer(*args) |
Based on the snippet: <|code_start|> ...
[-1, -2, -3, -4, -5]
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
"""
if isinstance(backend, _basestring):
backend = BACKENDS[backend](**backend_params)
old_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None)
try:
_backend.backend_and_jobs = (backend, n_jobs)
# return the backend instance to make it easier to write tests
yield backend, n_jobs
finally:
if old_backend_and_jobs is None:
if getattr(_backend, 'backend_and_jobs', None) is not None:
del _backend.backend_and_jobs
else:
_backend.backend_and_jobs = old_backend_and_jobs
# Under Linux or OS X the default start method of multiprocessing
# can cause third party libraries to crash. Under Python 3.4+ it is possible
# to set an environment variable to switch the default start method from
# 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost
# of causing semantic changes and some additional pool instantiation overhead.
if hasattr(mp, 'get_context'):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import functools
import time
import threading
import itertools
import warnings
import cPickle as pickle
import pickle
from math import sqrt
from numbers import Integral
from contextlib import contextmanager
from ...config import get_start_method
from ._multiprocessing_helpers import mp
from .format_stack import format_outer_frames
from .logger import Logger, short_format_time
from .my_exceptions import TransportableException, _mk_exception
from .disk import memstr_to_bytes
from ._parallel_backends import (FallbackToBackend, MultiprocessingBackend,
ThreadingBackend, SequentialBackend)
from ._compat import _basestring
from ._parallel_backends import AutoBatchingMixin # noqa
from ._parallel_backends import ParallelBackendBase # noqa
and context (classes, functions, sometimes code) from other files:
# Path: mlens/config.py
# def get_start_method():
# """Return start method"""
# return _START_METHOD
. Output only the next line. | method = get_start_method().strip() or None |
Based on the snippet: <|code_start|>"""ML-ENSEMBLE
:author: Sebastian Flennerhag
:copyright: 2017-2018
:licence: MIT
"""
from __future__ import division, print_function
<|code_end|>
, predict the immediate next line with the help of imports:
from ..externals.sklearn.base import BaseEstimator, TransformerMixin
and context (classes, functions, sometimes code) from other files:
# Path: mlens/externals/sklearn/base.py
# class BaseEstimator(object):
# """Base class for all estimators in scikit-learn
# Notes
# -----
# All estimators should specify all the parameters that can be set
# at the class level in their ``__init__`` as explicit keyword
# arguments (no ``*args`` or ``**kwargs``).
# """
#
# @classmethod
# def _get_param_names(cls):
# """Get parameter names for the estimator"""
# # fetch the constructor or the original constructor before
# # deprecation wrapping if any
# init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# if init is object.__init__:
# # No explicit constructor to introspect
# return []
#
# # introspect the constructor arguments to find the model parameters
# # to represent
# init_signature = signature(init)
# # Consider the constructor parameters excluding 'self'
# parameters = [p for p in init_signature.parameters.values()
# if p.name != 'self' and p.kind != p.VAR_KEYWORD]
# for p in parameters:
# if p.kind == p.VAR_POSITIONAL:
# raise RuntimeError("scikit-learn estimators should always "
# "specify their parameters in the signature"
# " of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
# " follow this convention."
# % (cls, init_signature))
# # Extract and sort argument names excluding 'self'
# return sorted([p.name for p in parameters])
#
# def get_params(self, deep=True):
# """Get parameters for this estimator.
# Parameters
# ----------
# deep : boolean, optional
# If True, will return the parameters for this estimator and
# contained subobjects that are estimators.
# Returns
# -------
# params : mapping of string to any
# Parameter names mapped to their values.
# """
# out = dict()
# for key in self._get_param_names():
# value = getattr(self, key, None)
# if deep and hasattr(value, 'get_params'):
# deep_items = value.get_params().items()
# out.update((key + '__' + k, val) for k, val in deep_items)
# out[key] = value
# return out
#
# def set_params(self, **params):
# """Set the parameters of this estimator.
# The method works on simple estimators as well as on nested objects
# (such as pipelines). The latter have parameters of the form
# ``<component>__<parameter>`` so that it's possible to update each
# component of a nested object.
# Returns
# -------
# self
# """
# if not params:
# # Simple optimization to gain speed (inspect is slow)
# return self
# valid_params = self.get_params(deep=True)
#
# nested_params = defaultdict(dict) # grouped by prefix
# for key, value in params.items():
# key, delim, sub_key = key.partition('__')
# if key not in valid_params:
# raise ValueError('Invalid parameter %s for estimator %s. '
# 'Check the list of available parameters '
# 'with `estimator.get_params().keys()`.' %
# (key, self))
#
# if delim:
# nested_params[key][sub_key] = value
# else:
# setattr(self, key, value)
# valid_params[key] = value
#
# for key, sub_params in nested_params.items():
# valid_params[key].set_params(**sub_params)
#
# return self
#
# def __repr__(self):
# class_name = self.__class__.__name__
# return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
# offset=len(class_name),),)
#
# def __getstate__(self):
# try:
# state = super(BaseEstimator, self).__getstate__()
# except AttributeError:
# state = self.__dict__.copy()
#
# if type(self).__module__.startswith('sklearn.'):
# return dict(state.items(), _sklearn_version=__version__)
# else:
# return state
#
# def __setstate__(self, state):
# if type(self).__module__.startswith('sklearn.'):
# pickle_version = state.pop("_sklearn_version", "pre-0.18")
# if pickle_version != __version__:
# warnings.warn(
# "Trying to unpickle estimator {0} from version {1} when "
# "using version {2}. This might lead to breaking code or "
# "invalid results. Use at your own risk.".format(
# self.__class__.__name__, pickle_version, __version__),
# UserWarning)
# try:
# super(BaseEstimator, self).__setstate__(state)
# except AttributeError:
# self.__dict__.update(state)
#
# class TransformerMixin(object):
# """Mixin class for all transformers in scikit-learn."""
#
# def fit_transform(self, X, y=None, **fit_params):
# """Fit to data, then transform it.
# Fits transformer to X and y with optional parameters fit_params
# and returns a transformed version of X.
# Parameters
# ----------
# X : numpy array of shape [n_samples, n_features]
# Training set.
# y : numpy array of shape [n_samples]
# Target values.
# Returns
# -------
# X_new : numpy array of shape [n_samples, n_features_new]
# Transformed array.
# """
# # non-optimized default implementation; override when a better
# # method is possible for a given clustering algorithm
# if y is None:
# # fit method of arity 1 (unsupervised transformation)
# return self.fit(X, **fit_params).transform(X)
# else:
# # fit method of arity 2 (supervised transformation)
# return self.fit(X, y, **fit_params).transform(X)
. Output only the next line. | class Subset(BaseEstimator, TransformerMixin): |
Predict the next line for this snippet: <|code_start|>"""ML-ENSEMBLE
:author: Sebastian Flennerhag
:copyright: 2017-2018
:licence: MIT
"""
from __future__ import division, print_function
<|code_end|>
with the help of current file imports:
from ..externals.sklearn.base import BaseEstimator, TransformerMixin
and context from other files:
# Path: mlens/externals/sklearn/base.py
# class BaseEstimator(object):
# """Base class for all estimators in scikit-learn
# Notes
# -----
# All estimators should specify all the parameters that can be set
# at the class level in their ``__init__`` as explicit keyword
# arguments (no ``*args`` or ``**kwargs``).
# """
#
# @classmethod
# def _get_param_names(cls):
# """Get parameter names for the estimator"""
# # fetch the constructor or the original constructor before
# # deprecation wrapping if any
# init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# if init is object.__init__:
# # No explicit constructor to introspect
# return []
#
# # introspect the constructor arguments to find the model parameters
# # to represent
# init_signature = signature(init)
# # Consider the constructor parameters excluding 'self'
# parameters = [p for p in init_signature.parameters.values()
# if p.name != 'self' and p.kind != p.VAR_KEYWORD]
# for p in parameters:
# if p.kind == p.VAR_POSITIONAL:
# raise RuntimeError("scikit-learn estimators should always "
# "specify their parameters in the signature"
# " of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
# " follow this convention."
# % (cls, init_signature))
# # Extract and sort argument names excluding 'self'
# return sorted([p.name for p in parameters])
#
# def get_params(self, deep=True):
# """Get parameters for this estimator.
# Parameters
# ----------
# deep : boolean, optional
# If True, will return the parameters for this estimator and
# contained subobjects that are estimators.
# Returns
# -------
# params : mapping of string to any
# Parameter names mapped to their values.
# """
# out = dict()
# for key in self._get_param_names():
# value = getattr(self, key, None)
# if deep and hasattr(value, 'get_params'):
# deep_items = value.get_params().items()
# out.update((key + '__' + k, val) for k, val in deep_items)
# out[key] = value
# return out
#
# def set_params(self, **params):
# """Set the parameters of this estimator.
# The method works on simple estimators as well as on nested objects
# (such as pipelines). The latter have parameters of the form
# ``<component>__<parameter>`` so that it's possible to update each
# component of a nested object.
# Returns
# -------
# self
# """
# if not params:
# # Simple optimization to gain speed (inspect is slow)
# return self
# valid_params = self.get_params(deep=True)
#
# nested_params = defaultdict(dict) # grouped by prefix
# for key, value in params.items():
# key, delim, sub_key = key.partition('__')
# if key not in valid_params:
# raise ValueError('Invalid parameter %s for estimator %s. '
# 'Check the list of available parameters '
# 'with `estimator.get_params().keys()`.' %
# (key, self))
#
# if delim:
# nested_params[key][sub_key] = value
# else:
# setattr(self, key, value)
# valid_params[key] = value
#
# for key, sub_params in nested_params.items():
# valid_params[key].set_params(**sub_params)
#
# return self
#
# def __repr__(self):
# class_name = self.__class__.__name__
# return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
# offset=len(class_name),),)
#
# def __getstate__(self):
# try:
# state = super(BaseEstimator, self).__getstate__()
# except AttributeError:
# state = self.__dict__.copy()
#
# if type(self).__module__.startswith('sklearn.'):
# return dict(state.items(), _sklearn_version=__version__)
# else:
# return state
#
# def __setstate__(self, state):
# if type(self).__module__.startswith('sklearn.'):
# pickle_version = state.pop("_sklearn_version", "pre-0.18")
# if pickle_version != __version__:
# warnings.warn(
# "Trying to unpickle estimator {0} from version {1} when "
# "using version {2}. This might lead to breaking code or "
# "invalid results. Use at your own risk.".format(
# self.__class__.__name__, pickle_version, __version__),
# UserWarning)
# try:
# super(BaseEstimator, self).__setstate__(state)
# except AttributeError:
# self.__dict__.update(state)
#
# class TransformerMixin(object):
# """Mixin class for all transformers in scikit-learn."""
#
# def fit_transform(self, X, y=None, **fit_params):
# """Fit to data, then transform it.
# Fits transformer to X and y with optional parameters fit_params
# and returns a transformed version of X.
# Parameters
# ----------
# X : numpy array of shape [n_samples, n_features]
# Training set.
# y : numpy array of shape [n_samples]
# Target values.
# Returns
# -------
# X_new : numpy array of shape [n_samples, n_features_new]
# Transformed array.
# """
# # non-optimized default implementation; override when a better
# # method is possible for a given clustering algorithm
# if y is None:
# # fit method of arity 1 (unsupervised transformation)
# return self.fit(X, **fit_params).transform(X)
# else:
# # fit method of arity 2 (supervised transformation)
# return self.fit(X, y, **fit_params).transform(X)
, which may contain function names, class names, or code. Output only the next line. | class Subset(BaseEstimator, TransformerMixin): |
Here is a snippet: <|code_start|>"""ML-Ensemble
:author: Sebastian Flennerhag
:license: MIT
:copyright: 2017-2018
Functions for base computations
"""
from __future__ import division
def load(path, name, raise_on_exception=True):
"""Utility for loading from cache"""
if isinstance(path, str):
f = os.path.join(path, name)
<|code_end|>
. Write the next line using the current file imports:
import os
import warnings
import numpy as np
from scipy.sparse import issparse
from ..utils import pickle_load, pickle_save, load as _load
from ..utils.exceptions import MetricWarning, ParameterChangeWarning
and context from other files:
# Path: mlens/utils/utils.py
# def pickle_save(obj, name):
# """Utility function for pickling an object"""
# with open(pickled(name), 'wb') as f:
# pickle.dump(obj, f)
#
# def pickle_load(name):
# """Utility function for loading pickled object"""
# with open(pickled(name), 'rb') as f:
# return pickle.load(f)
#
# def load(file, enforce_filetype=True):
# """Utility exception handler for loading file"""
# s, lim = get_ivals()
# if enforce_filetype:
# file = pickled(file)
# try:
# return pickle_load(file)
# except (EOFError, OSError, IOError) as exc:
# msg = str(exc)
# warnings.warn(
# "Could not load transformer at %s. Will check every %.1f seconds "
# "for %i seconds before aborting. " % (file, s, lim),
# ParallelProcessingWarning)
#
# ts = time()
# while not os.path.exists(file):
# sleep(s)
# if time() - ts > lim:
# raise ParallelProcessingError(
# "Could not load transformer at %s\nDetails:\n%r" %
# (dir, msg))
#
# return pickle_load(file)
#
# Path: mlens/utils/exceptions.py
# class MetricWarning(UserWarning):
#
# """Warning to notify that scoring do not behave as expected.
#
# Raised if scoring fails or if aggregating scores fails.
# """
#
# class ParameterChangeWarning(UserWarning):
#
# """Warning for different params in blueprint estimator and fitted copy.
#
# .. versionadded:: 0.2.2
# """
, which may include functions, classes, or code. Output only the next line. | obj = _load(f, raise_on_exception) |
Given snippet: <|code_start|> if len(p.shape) == 1:
pred[:, col] = p
else:
pred[:, col:(col + p.shape[1])] = p
else:
r = n - pred.shape[0]
if isinstance(tei[0], tuple):
if len(tei) > 1:
idx = np.hstack([np.arange(t0 - r, t1 - r) for t0, t1 in tei])
else:
tei = tei[0]
idx = slice(tei[0] - r, tei[1] - r)
else:
idx = slice(tei[0] - r, tei[1] - r)
if len(p.shape) == 1:
pred[idx, col] = p
else:
pred[(idx, slice(col, col + p.shape[1]))] = p
def score_predictions(y, p, scorer, name, inst_name):
"""Try-Except wrapper around Learner scoring"""
s = None
if scorer is not None:
try:
s = scorer(y, p)
except Exception as exc:
warnings.warn("[%s] Could not score %s. Details:\n%r" %
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import warnings
import numpy as np
from scipy.sparse import issparse
from ..utils import pickle_load, pickle_save, load as _load
from ..utils.exceptions import MetricWarning, ParameterChangeWarning
and context:
# Path: mlens/utils/utils.py
# def pickle_save(obj, name):
# """Utility function for pickling an object"""
# with open(pickled(name), 'wb') as f:
# pickle.dump(obj, f)
#
# def pickle_load(name):
# """Utility function for loading pickled object"""
# with open(pickled(name), 'rb') as f:
# return pickle.load(f)
#
# def load(file, enforce_filetype=True):
# """Utility exception handler for loading file"""
# s, lim = get_ivals()
# if enforce_filetype:
# file = pickled(file)
# try:
# return pickle_load(file)
# except (EOFError, OSError, IOError) as exc:
# msg = str(exc)
# warnings.warn(
# "Could not load transformer at %s. Will check every %.1f seconds "
# "for %i seconds before aborting. " % (file, s, lim),
# ParallelProcessingWarning)
#
# ts = time()
# while not os.path.exists(file):
# sleep(s)
# if time() - ts > lim:
# raise ParallelProcessingError(
# "Could not load transformer at %s\nDetails:\n%r" %
# (dir, msg))
#
# return pickle_load(file)
#
# Path: mlens/utils/exceptions.py
# class MetricWarning(UserWarning):
#
# """Warning to notify that scoring do not behave as expected.
#
# Raised if scoring fails or if aggregating scores fails.
# """
#
# class ParameterChangeWarning(UserWarning):
#
# """Warning for different params in blueprint estimator and fitted copy.
#
# .. versionadded:: 0.2.2
# """
which might include code, classes, or functions. Output only the next line. | (name, inst_name, exc), MetricWarning) |
Continue the code snippet: <|code_start|> # Iterate over flattened parameter collection
if isinstance(lpar, (list, set, tuple)):
for p1, p2 in zip(lpar, rpar):
check_params(p1, p2)
# --- param check ---
_pass = True
if lpar is None or rpar is None:
# None parameters are liable to be overwritten - ignore
return _pass
try:
if isinstance(lpar, (str, bool)):
_pass = lpar == rpar
if isinstance(lpar, (int, float)):
if np.isnan(lpar):
_pass = np.isnan(rpar)
elif np.isinf(lpar):
_pass = np.isinf(rpar)
else:
_pass = lpar == rpar
except Exception:
# avoid failing a model because we can't make the check we want
pass
if not _pass:
warnings.warn(
"Parameter value (%r) has changed since model was fitted (%r)." %
<|code_end|>
. Use current file imports:
import os
import warnings
import numpy as np
from scipy.sparse import issparse
from ..utils import pickle_load, pickle_save, load as _load
from ..utils.exceptions import MetricWarning, ParameterChangeWarning
and context (classes, functions, or code) from other files:
# Path: mlens/utils/utils.py
# def pickle_save(obj, name):
# """Utility function for pickling an object"""
# with open(pickled(name), 'wb') as f:
# pickle.dump(obj, f)
#
# def pickle_load(name):
# """Utility function for loading pickled object"""
# with open(pickled(name), 'rb') as f:
# return pickle.load(f)
#
# def load(file, enforce_filetype=True):
# """Utility exception handler for loading file"""
# s, lim = get_ivals()
# if enforce_filetype:
# file = pickled(file)
# try:
# return pickle_load(file)
# except (EOFError, OSError, IOError) as exc:
# msg = str(exc)
# warnings.warn(
# "Could not load transformer at %s. Will check every %.1f seconds "
# "for %i seconds before aborting. " % (file, s, lim),
# ParallelProcessingWarning)
#
# ts = time()
# while not os.path.exists(file):
# sleep(s)
# if time() - ts > lim:
# raise ParallelProcessingError(
# "Could not load transformer at %s\nDetails:\n%r" %
# (dir, msg))
#
# return pickle_load(file)
#
# Path: mlens/utils/exceptions.py
# class MetricWarning(UserWarning):
#
# """Warning to notify that scoring do not behave as expected.
#
# Raised if scoring fails or if aggregating scores fails.
# """
#
# class ParameterChangeWarning(UserWarning):
#
# """Warning for different params in blueprint estimator and fitted copy.
#
# .. versionadded:: 0.2.2
# """
. Output only the next line. | (lpar, rpar), ParameterChangeWarning) |
Here is a snippet: <|code_start|>except ImportError:
try:
# Try get performance counter
except ImportError:
# Fall back on wall clock
###############################################################################
def pickled(name):
"""Filetype enforcer"""
if not name.endswith('.pkl'):
name = '.'.join([name, 'pkl'])
return name
def pickle_save(obj, name):
"""Utility function for pickling an object"""
with open(pickled(name), 'wb') as f:
pickle.dump(obj, f)
def pickle_load(name):
"""Utility function for loading pickled object"""
with open(pickled(name), 'rb') as f:
return pickle.load(f)
def load(file, enforce_filetype=True):
"""Utility exception handler for loading file"""
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import warnings
import subprocess
import psutil
import cPickle as pickle
import pickle
from numpy import array
from ..config import get_ivals
from .exceptions import ParallelProcessingError, ParallelProcessingWarning
from time import sleep
from time import perf_counter as time
from time import time
and context from other files:
# Path: mlens/config.py
# def get_ivals():
# """Return _IVALS"""
# return _IVALS
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
, which may include functions, classes, or code. Output only the next line. | s, lim = get_ivals() |
Given the code snippet: <|code_start|>def pickle_save(obj, name):
"""Utility function for pickling an object"""
with open(pickled(name), 'wb') as f:
pickle.dump(obj, f)
def pickle_load(name):
"""Utility function for loading pickled object"""
with open(pickled(name), 'rb') as f:
return pickle.load(f)
def load(file, enforce_filetype=True):
"""Utility exception handler for loading file"""
s, lim = get_ivals()
if enforce_filetype:
file = pickled(file)
try:
return pickle_load(file)
except (EOFError, OSError, IOError) as exc:
msg = str(exc)
warnings.warn(
"Could not load transformer at %s. Will check every %.1f seconds "
"for %i seconds before aborting. " % (file, s, lim),
ParallelProcessingWarning)
ts = time()
while not os.path.exists(file):
sleep(s)
if time() - ts > lim:
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import warnings
import subprocess
import psutil
import cPickle as pickle
import pickle
from numpy import array
from ..config import get_ivals
from .exceptions import ParallelProcessingError, ParallelProcessingWarning
from time import sleep
from time import perf_counter as time
from time import time
and context (functions, classes, or occasionally code) from other files:
# Path: mlens/config.py
# def get_ivals():
# """Return _IVALS"""
# return _IVALS
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | raise ParallelProcessingError( |
Given the following code snippet before the placeholder: <|code_start|> """Filetype enforcer"""
if not name.endswith('.pkl'):
name = '.'.join([name, 'pkl'])
return name
def pickle_save(obj, name):
"""Utility function for pickling an object"""
with open(pickled(name), 'wb') as f:
pickle.dump(obj, f)
def pickle_load(name):
"""Utility function for loading pickled object"""
with open(pickled(name), 'rb') as f:
return pickle.load(f)
def load(file, enforce_filetype=True):
"""Utility exception handler for loading file"""
s, lim = get_ivals()
if enforce_filetype:
file = pickled(file)
try:
return pickle_load(file)
except (EOFError, OSError, IOError) as exc:
msg = str(exc)
warnings.warn(
"Could not load transformer at %s. Will check every %.1f seconds "
"for %i seconds before aborting. " % (file, s, lim),
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import warnings
import subprocess
import psutil
import cPickle as pickle
import pickle
from numpy import array
from ..config import get_ivals
from .exceptions import ParallelProcessingError, ParallelProcessingWarning
from time import sleep
from time import perf_counter as time
from time import time
and context including class names, function names, and sometimes code from other files:
# Path: mlens/config.py
# def get_ivals():
# """Return _IVALS"""
# return _IVALS
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | ParallelProcessingWarning) |
Predict the next line for this snippet: <|code_start|>
if name not in tmp:
# Set up data struct for name
tmp[name] = _dict()
for k in data_dict.keys():
tmp[name][k] = list()
if '%s-m' % k not in data:
data['%s-m' % k] = _dict()
data['%s-s' % k] = _dict()
data['%s-m' % k][name] = list()
data['%s-s' % k][name] = list()
# collect all data dicts belonging to name
for k, v in data_dict.items():
tmp[name][k].append(v)
# Aggregate to get mean and std
for name, data_dict in tmp.items():
for k, v in data_dict.items():
if not v:
continue
try:
# Purge None values from the main est due to no predict times
v = [i for i in v if i is not None]
if v:
data['%s-m' % k][name] = np.mean(v)
data['%s-s' % k][name] = np.std(v)
except Exception as exc:
warnings.warn(
"Aggregating data for %s failed. Raw data:\n%r\n"
<|code_end|>
with the help of current file imports:
import warnings
import numpy as np
from ..utils.exceptions import MetricWarning
from collections import OrderedDict as _dict
and context from other files:
# Path: mlens/utils/exceptions.py
# class MetricWarning(UserWarning):
#
# """Warning to notify that scoring do not behave as expected.
#
# Raised if scoring fails or if aggregating scores fails.
# """
, which may contain function names, class names, or code. Output only the next line. | "Details: %r" % (k, v, exc), MetricWarning) |
Based on the snippet: <|code_start|> if estimator is not None:
if isinstance(estimator, six.string_types):
estimator_name = estimator.lower()
else:
estimator_name = estimator.__class__.__name__.lower()
estimator_name = "[%s] " % estimator_name
else:
estimator_name = ""
return estimator_name
def check_ensemble_build(inst, attr='stack'):
"""Check that layers have been instantiated."""
if not hasattr(inst, attr):
# No layer container. This should not happen!
msg = ("No layer class attached to instance (%s). (Cannot find a "
"'Sequential' class instance as attribute [%s].)")
raise AttributeError(msg % (inst.__class__.__name__, attr))
if getattr(inst, attr) is None:
# No layers instantiated.
if not getattr(inst, 'raise_on_exception', True):
msg = "No Layers in instance (%s). Nothing to fit / predict."
warnings.warn(msg % inst.__class__.__name__,
<|code_end|>
, predict the immediate next line with the help of imports:
import warnings
from .exceptions import (NotFittedError, LayerSpecificationWarning,
LayerSpecificationError, ParallelProcessingError,
ParallelProcessingWarning)
and context (classes, functions, sometimes code) from other files:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# class LayerSpecificationWarning(UserWarning):
#
# """Warning class if layer has been specified in a dubious form.
#
# This warning is raised when the input does not look like expected, but
# is not fatal and a best guess of how to fix it will be made.
# """
#
# class LayerSpecificationError(TypeError, ValueError):
#
# """Error class for incorrectly specified layers."""
#
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | LayerSpecificationWarning) |
Continue the code snippet: <|code_start|> estimator_name = ""
return estimator_name
def check_ensemble_build(inst, attr='stack'):
"""Check that layers have been instantiated."""
if not hasattr(inst, attr):
# No layer container. This should not happen!
msg = ("No layer class attached to instance (%s). (Cannot find a "
"'Sequential' class instance as attribute [%s].)")
raise AttributeError(msg % (inst.__class__.__name__, attr))
if getattr(inst, attr) is None:
# No layers instantiated.
if not getattr(inst, 'raise_on_exception', True):
msg = "No Layers in instance (%s). Nothing to fit / predict."
warnings.warn(msg % inst.__class__.__name__,
LayerSpecificationWarning)
# For PASSED flag on soft fail
return False
else:
msg = ("No Layers in instance (%s). Add layers before calling "
"'fit' and 'predict'.")
<|code_end|>
. Use current file imports:
import warnings
from .exceptions import (NotFittedError, LayerSpecificationWarning,
LayerSpecificationError, ParallelProcessingError,
ParallelProcessingWarning)
and context (classes, functions, or code) from other files:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# class LayerSpecificationWarning(UserWarning):
#
# """Warning class if layer has been specified in a dubious form.
#
# This warning is raised when the input does not look like expected, but
# is not fatal and a best guess of how to fix it will be made.
# """
#
# class LayerSpecificationError(TypeError, ValueError):
#
# """Error class for incorrectly specified layers."""
#
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | raise LayerSpecificationError(msg % inst.__class__.__name__) |
Next line prediction: <|code_start|> msg = ("Unexpected format of 'preprocessing'. Needs to be "
" of type 'None' or 'list' or 'dict'. Got %s .")
raise LayerSpecificationError(msg % type(preprocessing))
if not isinstance(estimators, dict):
msg = ("Unexpected format of 'estimators'. Needs to be "
"'dict' when preprocessing is 'dict'. Got %s.")
raise LayerSpecificationError(msg % type(estimators))
# Check that keys overlap
prep_check = [key in preprocessing for key in estimators]
est_check = [key in estimators for key in preprocessing]
if not all(est_check):
msg = ("Too few estimator cases to match preprocessing cases:\n"
"estimator cases: %r\npreprocessing cases: %r")
raise LayerSpecificationError(msg % (list(estimators),
list(preprocessing)))
if not all(prep_check):
msg = ("Too few preprocessing cases to match estimators cases:\n"
"preprocessing cases: %r\nestimator cases: %r")
raise LayerSpecificationError(msg % (list(preprocessing),
list(estimators)))
def check_initialized(inst):
"""Check if a ParallelProcessing instance is initialized properly."""
if not inst.__initialized__:
msg = "ParallelProcessing is not initialized. Call " \
"'initialize' before calling 'fit'."
<|code_end|>
. Use current file imports:
(import warnings
from .exceptions import (NotFittedError, LayerSpecificationWarning,
LayerSpecificationError, ParallelProcessingError,
ParallelProcessingWarning))
and context including class names, function names, or small code snippets from other files:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# class LayerSpecificationWarning(UserWarning):
#
# """Warning class if layer has been specified in a dubious form.
#
# This warning is raised when the input does not look like expected, but
# is not fatal and a best guess of how to fix it will be made.
# """
#
# class LayerSpecificationError(TypeError, ValueError):
#
# """Error class for incorrectly specified layers."""
#
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | raise ParallelProcessingError(msg) |
Using the snippet: <|code_start|> "estimator cases: %r\npreprocessing cases: %r")
raise LayerSpecificationError(msg % (list(estimators),
list(preprocessing)))
if not all(prep_check):
msg = ("Too few preprocessing cases to match estimators cases:\n"
"preprocessing cases: %r\nestimator cases: %r")
raise LayerSpecificationError(msg % (list(preprocessing),
list(estimators)))
def check_initialized(inst):
"""Check if a ParallelProcessing instance is initialized properly."""
if not inst.__initialized__:
msg = "ParallelProcessing is not initialized. Call " \
"'initialize' before calling 'fit'."
raise ParallelProcessingError(msg)
if getattr(inst, '__fitted__', None):
if inst.layers.raise_on_exception:
raise ParallelProcessingError("This instance is already "
"fitted and its parallel "
"processing jobs has not been "
"terminated. To refit "
"instance, call 'terminate' "
"before calling 'fit'.")
else:
warnings.warn("This instance is already "
"fitted and its parallel "
"processing job has not been "
"terminated. Will refit using previous job's cache.",
<|code_end|>
, determine the next line of code. You have imports:
import warnings
from .exceptions import (NotFittedError, LayerSpecificationWarning,
LayerSpecificationError, ParallelProcessingError,
ParallelProcessingWarning)
and context (class names, function names, or code) available:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# class LayerSpecificationWarning(UserWarning):
#
# """Warning class if layer has been specified in a dubious form.
#
# This warning is raised when the input does not look like expected, but
# is not fatal and a best guess of how to fix it will be made.
# """
#
# class LayerSpecificationError(TypeError, ValueError):
#
# """Error class for incorrectly specified layers."""
#
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
#
# class ParallelProcessingWarning(UserWarning):
#
# """Warnings related to methods on :class:`ParallelProcessing`.
#
# Can be subclassed for more specific warning classes.
# """
. Output only the next line. | ParallelProcessingWarning) |
Predict the next line for this snippet: <|code_start|> fitted instance with stored sample.
"""
self.train_shape = X.shape
sample_idx = {}
for i in range(2):
dim_size = min(X.shape[i], self.size)
sample_idx[i] = permutation(X.shape[i])[:dim_size]
sample = X[ix_(sample_idx[0], sample_idx[1])]
self.sample_idx_ = sample_idx
self.sample_ = sample
return self
def is_train(self, X):
"""Check if an array is the training set.
Parameters
----------
X: array-like
training set to sample observations from.
Returns
----------
self: obj
fitted instance with stored sample.
"""
if not hasattr(self, "train_shape"):
<|code_end|>
with the help of current file imports:
from ..utils.exceptions import NotFittedError
from ..externals.sklearn.base import BaseEstimator
from numpy import array_equal, ix_
from numpy.random import permutation
from numbers import Integral
and context from other files:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# Path: mlens/externals/sklearn/base.py
# class BaseEstimator(object):
# """Base class for all estimators in scikit-learn
# Notes
# -----
# All estimators should specify all the parameters that can be set
# at the class level in their ``__init__`` as explicit keyword
# arguments (no ``*args`` or ``**kwargs``).
# """
#
# @classmethod
# def _get_param_names(cls):
# """Get parameter names for the estimator"""
# # fetch the constructor or the original constructor before
# # deprecation wrapping if any
# init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# if init is object.__init__:
# # No explicit constructor to introspect
# return []
#
# # introspect the constructor arguments to find the model parameters
# # to represent
# init_signature = signature(init)
# # Consider the constructor parameters excluding 'self'
# parameters = [p for p in init_signature.parameters.values()
# if p.name != 'self' and p.kind != p.VAR_KEYWORD]
# for p in parameters:
# if p.kind == p.VAR_POSITIONAL:
# raise RuntimeError("scikit-learn estimators should always "
# "specify their parameters in the signature"
# " of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
# " follow this convention."
# % (cls, init_signature))
# # Extract and sort argument names excluding 'self'
# return sorted([p.name for p in parameters])
#
# def get_params(self, deep=True):
# """Get parameters for this estimator.
# Parameters
# ----------
# deep : boolean, optional
# If True, will return the parameters for this estimator and
# contained subobjects that are estimators.
# Returns
# -------
# params : mapping of string to any
# Parameter names mapped to their values.
# """
# out = dict()
# for key in self._get_param_names():
# value = getattr(self, key, None)
# if deep and hasattr(value, 'get_params'):
# deep_items = value.get_params().items()
# out.update((key + '__' + k, val) for k, val in deep_items)
# out[key] = value
# return out
#
# def set_params(self, **params):
# """Set the parameters of this estimator.
# The method works on simple estimators as well as on nested objects
# (such as pipelines). The latter have parameters of the form
# ``<component>__<parameter>`` so that it's possible to update each
# component of a nested object.
# Returns
# -------
# self
# """
# if not params:
# # Simple optimization to gain speed (inspect is slow)
# return self
# valid_params = self.get_params(deep=True)
#
# nested_params = defaultdict(dict) # grouped by prefix
# for key, value in params.items():
# key, delim, sub_key = key.partition('__')
# if key not in valid_params:
# raise ValueError('Invalid parameter %s for estimator %s. '
# 'Check the list of available parameters '
# 'with `estimator.get_params().keys()`.' %
# (key, self))
#
# if delim:
# nested_params[key][sub_key] = value
# else:
# setattr(self, key, value)
# valid_params[key] = value
#
# for key, sub_params in nested_params.items():
# valid_params[key].set_params(**sub_params)
#
# return self
#
# def __repr__(self):
# class_name = self.__class__.__name__
# return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
# offset=len(class_name),),)
#
# def __getstate__(self):
# try:
# state = super(BaseEstimator, self).__getstate__()
# except AttributeError:
# state = self.__dict__.copy()
#
# if type(self).__module__.startswith('sklearn.'):
# return dict(state.items(), _sklearn_version=__version__)
# else:
# return state
#
# def __setstate__(self, state):
# if type(self).__module__.startswith('sklearn.'):
# pickle_version = state.pop("_sklearn_version", "pre-0.18")
# if pickle_version != __version__:
# warnings.warn(
# "Trying to unpickle estimator {0} from version {1} when "
# "using version {2}. This might lead to breaking code or "
# "invalid results. Use at your own risk.".format(
# self.__class__.__name__, pickle_version, __version__),
# UserWarning)
# try:
# super(BaseEstimator, self).__setstate__(state)
# except AttributeError:
# self.__dict__.update(state)
, which may contain function names, class names, or code. Output only the next line. | raise NotFittedError("This IdTrain instance is not fitted yet.") |
Next line prediction: <|code_start|>"""ML-ENSEMBLE
:author: Sebastian Flennerhag
:copyright: 2017-2018
:licence: MIT
Class for identifying a training set after an estimator has been fitted. Used
for determining whether a `predict` or `transform` method should use
cross validation to create predictions, or estimators fitted on full
training data.
"""
from __future__ import division, print_function
<|code_end|>
. Use current file imports:
(from ..utils.exceptions import NotFittedError
from ..externals.sklearn.base import BaseEstimator
from numpy import array_equal, ix_
from numpy.random import permutation
from numbers import Integral)
and context including class names, function names, or small code snippets from other files:
# Path: mlens/utils/exceptions.py
# class NotFittedError(ValueError, AttributeError):
#
# """Error class for an ensemble or estimator that is not fitted yet
#
# Raised when some method has been called that expects the instance to be
# fitted.
# """
#
# Path: mlens/externals/sklearn/base.py
# class BaseEstimator(object):
# """Base class for all estimators in scikit-learn
# Notes
# -----
# All estimators should specify all the parameters that can be set
# at the class level in their ``__init__`` as explicit keyword
# arguments (no ``*args`` or ``**kwargs``).
# """
#
# @classmethod
# def _get_param_names(cls):
# """Get parameter names for the estimator"""
# # fetch the constructor or the original constructor before
# # deprecation wrapping if any
# init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# if init is object.__init__:
# # No explicit constructor to introspect
# return []
#
# # introspect the constructor arguments to find the model parameters
# # to represent
# init_signature = signature(init)
# # Consider the constructor parameters excluding 'self'
# parameters = [p for p in init_signature.parameters.values()
# if p.name != 'self' and p.kind != p.VAR_KEYWORD]
# for p in parameters:
# if p.kind == p.VAR_POSITIONAL:
# raise RuntimeError("scikit-learn estimators should always "
# "specify their parameters in the signature"
# " of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
# " follow this convention."
# % (cls, init_signature))
# # Extract and sort argument names excluding 'self'
# return sorted([p.name for p in parameters])
#
# def get_params(self, deep=True):
# """Get parameters for this estimator.
# Parameters
# ----------
# deep : boolean, optional
# If True, will return the parameters for this estimator and
# contained subobjects that are estimators.
# Returns
# -------
# params : mapping of string to any
# Parameter names mapped to their values.
# """
# out = dict()
# for key in self._get_param_names():
# value = getattr(self, key, None)
# if deep and hasattr(value, 'get_params'):
# deep_items = value.get_params().items()
# out.update((key + '__' + k, val) for k, val in deep_items)
# out[key] = value
# return out
#
# def set_params(self, **params):
# """Set the parameters of this estimator.
# The method works on simple estimators as well as on nested objects
# (such as pipelines). The latter have parameters of the form
# ``<component>__<parameter>`` so that it's possible to update each
# component of a nested object.
# Returns
# -------
# self
# """
# if not params:
# # Simple optimization to gain speed (inspect is slow)
# return self
# valid_params = self.get_params(deep=True)
#
# nested_params = defaultdict(dict) # grouped by prefix
# for key, value in params.items():
# key, delim, sub_key = key.partition('__')
# if key not in valid_params:
# raise ValueError('Invalid parameter %s for estimator %s. '
# 'Check the list of available parameters '
# 'with `estimator.get_params().keys()`.' %
# (key, self))
#
# if delim:
# nested_params[key][sub_key] = value
# else:
# setattr(self, key, value)
# valid_params[key] = value
#
# for key, sub_params in nested_params.items():
# valid_params[key].set_params(**sub_params)
#
# return self
#
# def __repr__(self):
# class_name = self.__class__.__name__
# return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
# offset=len(class_name),),)
#
# def __getstate__(self):
# try:
# state = super(BaseEstimator, self).__getstate__()
# except AttributeError:
# state = self.__dict__.copy()
#
# if type(self).__module__.startswith('sklearn.'):
# return dict(state.items(), _sklearn_version=__version__)
# else:
# return state
#
# def __setstate__(self, state):
# if type(self).__module__.startswith('sklearn.'):
# pickle_version = state.pop("_sklearn_version", "pre-0.18")
# if pickle_version != __version__:
# warnings.warn(
# "Trying to unpickle estimator {0} from version {1} when "
# "using version {2}. This might lead to breaking code or "
# "invalid results. Use at your own risk.".format(
# self.__class__.__name__, pickle_version, __version__),
# UserWarning)
# try:
# super(BaseEstimator, self).__setstate__(state)
# except AttributeError:
# self.__dict__.update(state)
. Output only the next line. | class IdTrain(BaseEstimator): |
Given the code snippet: <|code_start|>
assert len(cm.cpu) == 2
assert len(cm.rss) == 2
assert len(cm.vms) == 2
def test_cm_exception():
"""[Utils] CMLog: test collecting un-monitored returns None."""
if psutil is not None and not __version__.startswith('2.'):
cm = utils.CMLog(verbose=False)
with open(os.devnull, 'w') as f, redirect_stdout(f):
out = cm.collect()
assert out is None
def test_pickle():
"""[Utils] Check that pickling a standard object works."""
utils.pickle_save(d, 'd')
test = utils.pickle_load('d')
subprocess.check_call(['rm', 'd.pkl'])
assert isinstance(d, dict)
assert test['entry1'] == 'test'
assert test['entry2'] == 'also_test'
def test_load():
"""[Utils] Check that load handles exceptions gracefully"""
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import sysconfig
import subprocess
import psutil
from mlens import config
from mlens.utils import utils
from mlens.utils.exceptions import ParallelProcessingError
from time import sleep
from time import perf_counter as time
from time import time
from contextlib import redirect_stdout, redirect_stderr
from mlens.externals.fixes import redirect as redirect_stdout
and context (functions, classes, or occasionally code) from other files:
# Path: mlens/config.py
# _DTYPE = getattr(numpy, os.environ.get('MLENS_DTYPE', 'float32'))
# _TMPDIR = os.environ.get('MLENS_TMPDIR', tempfile.gettempdir())
# _PREFIX = os.environ.get('MLENS_PREFIX', ".mlens_tmp_cache_")
# _BACKEND = os.environ.get('MLENS_BACKEND', 'threading')
# _START_METHOD = os.environ.get('MLENS_START_METHOD', '')
# _VERBOSE = os.environ.get('MLENS_VERBOSE', 'Y')
# _IVALS = os.environ.get('MLENS_IVALS', '0.01_120').split('_')
# _IVALS = (float(_IVALS[0]), float(_IVALS[1]))
# _PY_VERSION = float(sysconfig._PY_VERSION_SHORT)
# _TMPDIR = tmp
# _PREFIX = prefix
# _DTYPE = dtype
# _BACKEND = backend
# _START_METHOD = method
# _IVALS = (interval, limit)
# _START_METHOD = __get_default_start_method(_START_METHOD)
# def get_ivals():
# def get_dtype():
# def get_prefix():
# def get_backend():
# def get_start_method():
# def get_tmpdir():
# def set_tmpdir(tmp):
# def set_prefix(prefix):
# def set_dtype(dtype):
# def set_backend(backend):
# def set_start_method(method):
# def set_ivals(interval, limit):
# def __get_default_start_method(method):
# def clear_cache(tmp):
# def print_settings():
#
# Path: mlens/utils/utils.py
# def pickled(name):
# def pickle_save(obj, name):
# def pickle_load(name):
# def load(file, enforce_filetype=True):
# def clone_attribute(iterable, attribute):
# def kwarg_parser(func, kwargs):
# def safe_print(*objects, **kwargs):
# def print_time(t0, message='', **kwargs):
# def __init__(self, verbose=False):
# def monitor(self, stop=None, ival=0.1, kill=True):
# def collect(self):
# def _recorder(pid, stop, ival):
# class CMLog(object):
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
. Output only the next line. | config.set_ivals(0.1, 0.1) |
Continue the code snippet: <|code_start|>try:
except ImportError:
psutil = None
__version__ = sysconfig.get_python_version()
# An object to pickle
d = {'entry1': 'test', 'entry2': 'also_test'}
class Logger(object):
"""Temporary class redirect print messages to a python object."""
def __init__(self):
self.log = []
def write(self, msg):
"""Write a printed message to log"""
self.log.append(msg)
def test_print_time():
"""[Utils] print_time: messages looks as expected."""
logger = Logger()
# Initiate a time interval
t0 = time()
sleep(1.3)
# Record recorded print_time message
<|code_end|>
. Use current file imports:
import os
import numpy as np
import sysconfig
import subprocess
import psutil
from mlens import config
from mlens.utils import utils
from mlens.utils.exceptions import ParallelProcessingError
from time import sleep
from time import perf_counter as time
from time import time
from contextlib import redirect_stdout, redirect_stderr
from mlens.externals.fixes import redirect as redirect_stdout
and context (classes, functions, or code) from other files:
# Path: mlens/config.py
# _DTYPE = getattr(numpy, os.environ.get('MLENS_DTYPE', 'float32'))
# _TMPDIR = os.environ.get('MLENS_TMPDIR', tempfile.gettempdir())
# _PREFIX = os.environ.get('MLENS_PREFIX', ".mlens_tmp_cache_")
# _BACKEND = os.environ.get('MLENS_BACKEND', 'threading')
# _START_METHOD = os.environ.get('MLENS_START_METHOD', '')
# _VERBOSE = os.environ.get('MLENS_VERBOSE', 'Y')
# _IVALS = os.environ.get('MLENS_IVALS', '0.01_120').split('_')
# _IVALS = (float(_IVALS[0]), float(_IVALS[1]))
# _PY_VERSION = float(sysconfig._PY_VERSION_SHORT)
# _TMPDIR = tmp
# _PREFIX = prefix
# _DTYPE = dtype
# _BACKEND = backend
# _START_METHOD = method
# _IVALS = (interval, limit)
# _START_METHOD = __get_default_start_method(_START_METHOD)
# def get_ivals():
# def get_dtype():
# def get_prefix():
# def get_backend():
# def get_start_method():
# def get_tmpdir():
# def set_tmpdir(tmp):
# def set_prefix(prefix):
# def set_dtype(dtype):
# def set_backend(backend):
# def set_start_method(method):
# def set_ivals(interval, limit):
# def __get_default_start_method(method):
# def clear_cache(tmp):
# def print_settings():
#
# Path: mlens/utils/utils.py
# def pickled(name):
# def pickle_save(obj, name):
# def pickle_load(name):
# def load(file, enforce_filetype=True):
# def clone_attribute(iterable, attribute):
# def kwarg_parser(func, kwargs):
# def safe_print(*objects, **kwargs):
# def print_time(t0, message='', **kwargs):
# def __init__(self, verbose=False):
# def monitor(self, stop=None, ival=0.1, kill=True):
# def collect(self):
# def _recorder(pid, stop, ival):
# class CMLog(object):
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
. Output only the next line. | utils.print_time(t0, message='test', file=logger) |
Here is a snippet: <|code_start|>
def test_cm_exception():
"""[Utils] CMLog: test collecting un-monitored returns None."""
if psutil is not None and not __version__.startswith('2.'):
cm = utils.CMLog(verbose=False)
with open(os.devnull, 'w') as f, redirect_stdout(f):
out = cm.collect()
assert out is None
def test_pickle():
"""[Utils] Check that pickling a standard object works."""
utils.pickle_save(d, 'd')
test = utils.pickle_load('d')
subprocess.check_call(['rm', 'd.pkl'])
assert isinstance(d, dict)
assert test['entry1'] == 'test'
assert test['entry2'] == 'also_test'
def test_load():
"""[Utils] Check that load handles exceptions gracefully"""
config.set_ivals(0.1, 0.1)
with open(os.devnull, 'w') as f, redirect_stderr(f):
np.testing.assert_raises(
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import sysconfig
import subprocess
import psutil
from mlens import config
from mlens.utils import utils
from mlens.utils.exceptions import ParallelProcessingError
from time import sleep
from time import perf_counter as time
from time import time
from contextlib import redirect_stdout, redirect_stderr
from mlens.externals.fixes import redirect as redirect_stdout
and context from other files:
# Path: mlens/config.py
# _DTYPE = getattr(numpy, os.environ.get('MLENS_DTYPE', 'float32'))
# _TMPDIR = os.environ.get('MLENS_TMPDIR', tempfile.gettempdir())
# _PREFIX = os.environ.get('MLENS_PREFIX', ".mlens_tmp_cache_")
# _BACKEND = os.environ.get('MLENS_BACKEND', 'threading')
# _START_METHOD = os.environ.get('MLENS_START_METHOD', '')
# _VERBOSE = os.environ.get('MLENS_VERBOSE', 'Y')
# _IVALS = os.environ.get('MLENS_IVALS', '0.01_120').split('_')
# _IVALS = (float(_IVALS[0]), float(_IVALS[1]))
# _PY_VERSION = float(sysconfig._PY_VERSION_SHORT)
# _TMPDIR = tmp
# _PREFIX = prefix
# _DTYPE = dtype
# _BACKEND = backend
# _START_METHOD = method
# _IVALS = (interval, limit)
# _START_METHOD = __get_default_start_method(_START_METHOD)
# def get_ivals():
# def get_dtype():
# def get_prefix():
# def get_backend():
# def get_start_method():
# def get_tmpdir():
# def set_tmpdir(tmp):
# def set_prefix(prefix):
# def set_dtype(dtype):
# def set_backend(backend):
# def set_start_method(method):
# def set_ivals(interval, limit):
# def __get_default_start_method(method):
# def clear_cache(tmp):
# def print_settings():
#
# Path: mlens/utils/utils.py
# def pickled(name):
# def pickle_save(obj, name):
# def pickle_load(name):
# def load(file, enforce_filetype=True):
# def clone_attribute(iterable, attribute):
# def kwarg_parser(func, kwargs):
# def safe_print(*objects, **kwargs):
# def print_time(t0, message='', **kwargs):
# def __init__(self, verbose=False):
# def monitor(self, stop=None, ival=0.1, kill=True):
# def collect(self):
# def _recorder(pid, stop, ival):
# class CMLog(object):
#
# Path: mlens/utils/exceptions.py
# class ParallelProcessingError(AttributeError, RuntimeError):
#
# """Error class for fatal errors related to :class:`ParallelProcessing`.
#
# Can be subclassed for more specific error classes.
# """
, which may include functions, classes, or code. Output only the next line. | ParallelProcessingError, |
Predict the next line for this snippet: <|code_start|>
Parameters
----------
arr : array
Returns
-------
out : list
Examples
--------
>>> import numpy as np
>>> from mlens.index.base import make_tuple
>>> _make_tuple(np.array([0, 1, 2, 5, 6, 8, 9, 10]))
[(0, 3), (5, 7), (8, 11)]
"""
out = list()
t1 = t0 = arr[0]
for i in arr[1:]:
if i - t1 <= 1:
t1 = i
continue
out.append((t0, t1 + 1))
t1 = t0 = i
out.append((t0, t1 + 1))
return out
<|code_end|>
with the help of current file imports:
from abc import abstractmethod
from ..externals.sklearn.base import BaseEstimator
import numpy as np
and context from other files:
# Path: mlens/externals/sklearn/base.py
# class BaseEstimator(object):
# """Base class for all estimators in scikit-learn
# Notes
# -----
# All estimators should specify all the parameters that can be set
# at the class level in their ``__init__`` as explicit keyword
# arguments (no ``*args`` or ``**kwargs``).
# """
#
# @classmethod
# def _get_param_names(cls):
# """Get parameter names for the estimator"""
# # fetch the constructor or the original constructor before
# # deprecation wrapping if any
# init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# if init is object.__init__:
# # No explicit constructor to introspect
# return []
#
# # introspect the constructor arguments to find the model parameters
# # to represent
# init_signature = signature(init)
# # Consider the constructor parameters excluding 'self'
# parameters = [p for p in init_signature.parameters.values()
# if p.name != 'self' and p.kind != p.VAR_KEYWORD]
# for p in parameters:
# if p.kind == p.VAR_POSITIONAL:
# raise RuntimeError("scikit-learn estimators should always "
# "specify their parameters in the signature"
# " of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
# " follow this convention."
# % (cls, init_signature))
# # Extract and sort argument names excluding 'self'
# return sorted([p.name for p in parameters])
#
# def get_params(self, deep=True):
# """Get parameters for this estimator.
# Parameters
# ----------
# deep : boolean, optional
# If True, will return the parameters for this estimator and
# contained subobjects that are estimators.
# Returns
# -------
# params : mapping of string to any
# Parameter names mapped to their values.
# """
# out = dict()
# for key in self._get_param_names():
# value = getattr(self, key, None)
# if deep and hasattr(value, 'get_params'):
# deep_items = value.get_params().items()
# out.update((key + '__' + k, val) for k, val in deep_items)
# out[key] = value
# return out
#
# def set_params(self, **params):
# """Set the parameters of this estimator.
# The method works on simple estimators as well as on nested objects
# (such as pipelines). The latter have parameters of the form
# ``<component>__<parameter>`` so that it's possible to update each
# component of a nested object.
# Returns
# -------
# self
# """
# if not params:
# # Simple optimization to gain speed (inspect is slow)
# return self
# valid_params = self.get_params(deep=True)
#
# nested_params = defaultdict(dict) # grouped by prefix
# for key, value in params.items():
# key, delim, sub_key = key.partition('__')
# if key not in valid_params:
# raise ValueError('Invalid parameter %s for estimator %s. '
# 'Check the list of available parameters '
# 'with `estimator.get_params().keys()`.' %
# (key, self))
#
# if delim:
# nested_params[key][sub_key] = value
# else:
# setattr(self, key, value)
# valid_params[key] = value
#
# for key, sub_params in nested_params.items():
# valid_params[key].set_params(**sub_params)
#
# return self
#
# def __repr__(self):
# class_name = self.__class__.__name__
# return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
# offset=len(class_name),),)
#
# def __getstate__(self):
# try:
# state = super(BaseEstimator, self).__getstate__()
# except AttributeError:
# state = self.__dict__.copy()
#
# if type(self).__module__.startswith('sklearn.'):
# return dict(state.items(), _sklearn_version=__version__)
# else:
# return state
#
# def __setstate__(self, state):
# if type(self).__module__.startswith('sklearn.'):
# pickle_version = state.pop("_sklearn_version", "pre-0.18")
# if pickle_version != __version__:
# warnings.warn(
# "Trying to unpickle estimator {0} from version {1} when "
# "using version {2}. This might lead to breaking code or "
# "invalid results. Use at your own risk.".format(
# self.__class__.__name__, pickle_version, __version__),
# UserWarning)
# try:
# super(BaseEstimator, self).__setstate__(state)
# except AttributeError:
# self.__dict__.update(state)
, which may contain function names, class names, or code. Output only the next line. | class BaseIndex(BaseEstimator): |
Continue the code snippet: <|code_start|> list_of_files = []
names = []
# i am not really sure why we need multiline here
# is it because start of line char is just matching
speakid = re.compile(r'^# %s=(.*)' % re.escape(feature), re.MULTILINE)
# if passed a dir, do it for every file
if os.path.isdir(path):
for (root, dirs, fs) in os.walk(path):
for f in fs:
list_of_files.append(os.path.join(root, f))
elif os.path.isfile(path):
list_of_files.append(path)
for filepath in list_of_files:
res = get_names(filepath, speakid)
if not res:
continue
for i in res:
if i not in names:
names.append(i)
if len(names) > MAX_METADATA_VALUES:
break
return list(sorted(set(names)))
def rename_all_files(dirs_to_do):
"""
Get rid of the inserted dirname in filenames after parsing
"""
<|code_end|>
. Use current file imports:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from time import localtime, strftime
from corpkit.textprogressbar import TextProgressBar
from corpkit.process import animator
from zipfile import BadZipfile
from time import localtime, strftime
from zipfile import BadZipfile
from subprocess import PIPE, STDOUT, Popen
from subprocess import PIPE, STDOUT, Popen
from corpkit.process import get_corenlp_path
from time import localtime, strftime
from corpkit.constants import CORENLP_URL as url
from corpkit.constants import CORENLP_VERSION
from corpkit.constants import CORENLP_VERSION
from corpkit.process import saferead
from corpkit.constants import MAX_SPEAKERNAME_SIZE
from time import localtime, strftime
from corpkit.corpus import Corpus
from corpkit.constants import OPENER, PYTHON_VERSION, MAX_METADATA_FIELDS
from corpkit.process import saferead
from corpkit.process import saferead
from corpkit.constants import MAX_METADATA_VALUES
from glob import glob
from glob import glob
from corpkit.process import makesafe
import os
import shutil
import glob
import zipfile
import __main__ as main
import requests
import traceback
import zipfile
import os
import fnmatch
import os
import corpkit
import subprocess
import subprocess
import os
import sys
import re
import chardet
import time
import shutil
import glob
import importlib
import corpkit
import shutil
import os
import fnmatch
import corpkit
import os
import os
import os
import re
import shutil
import os
import re
import os
import re
import os
import re
import os
import os
import shutil
and context (classes, functions, or code) from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
. Output only the next line. | if isinstance(dirs_to_do, STRINGTYPE): |
Using the snippet: <|code_start|>
try:
shutil.copytree(pth, newpth)
except OSError:
shutil.rmtree(newpth)
shutil.copytree(pth, newpth)
files = get_filepaths(newpth)
names = []
metadata = []
for f in files:
good_data = []
fo, enc = saferead(f)
data = fo.splitlines()
# for each line in the file, remove speaker and metadata
for datum in data:
if speaker_segmentation:
matched = re.search(idregex, datum)
if matched:
names.append(matched.group(1))
datum = matched.group(2)
if metadata_mode:
splitmet = datum.rsplit('<metadata ', 1)
# for the impossibly rare case of a line that is '<metadata '
if not splitmet:
continue
datum = splitmet[0]
if datum:
good_data.append(datum)
with open(f, "w") as fo:
<|code_end|>
, determine the next line of code. You have imports:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from time import localtime, strftime
from corpkit.textprogressbar import TextProgressBar
from corpkit.process import animator
from zipfile import BadZipfile
from time import localtime, strftime
from zipfile import BadZipfile
from subprocess import PIPE, STDOUT, Popen
from subprocess import PIPE, STDOUT, Popen
from corpkit.process import get_corenlp_path
from time import localtime, strftime
from corpkit.constants import CORENLP_URL as url
from corpkit.constants import CORENLP_VERSION
from corpkit.constants import CORENLP_VERSION
from corpkit.process import saferead
from corpkit.constants import MAX_SPEAKERNAME_SIZE
from time import localtime, strftime
from corpkit.corpus import Corpus
from corpkit.constants import OPENER, PYTHON_VERSION, MAX_METADATA_FIELDS
from corpkit.process import saferead
from corpkit.process import saferead
from corpkit.constants import MAX_METADATA_VALUES
from glob import glob
from glob import glob
from corpkit.process import makesafe
import os
import shutil
import glob
import zipfile
import __main__ as main
import requests
import traceback
import zipfile
import os
import fnmatch
import os
import corpkit
import subprocess
import subprocess
import os
import sys
import re
import chardet
import time
import shutil
import glob
import importlib
import corpkit
import shutil
import os
import fnmatch
import corpkit
import os
import os
import os
import re
import shutil
import os
import re
import os
import re
import os
import re
import os
import os
import shutil
and context (class names, function names, or code) available:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
. Output only the next line. | if PYTHON_VERSION == 2: |
Predict the next line after this snippet: <|code_start|> downloaded_dir = os.path.join(home, 'corenlp')
if not os.path.isdir(downloaded_dir):
os.makedirs(downloaded_dir)
else:
poss_zips = glob.glob(os.path.join(downloaded_dir, 'stanford-corenlp-full*.zip'))
if poss_zips:
fullfile = poss_zips[-1]
try:
the_zip_file = zipfile.ZipFile(fullfile)
ret = the_zip_file.testzip()
if ret is None:
return downloaded_dir, fullfile
else:
os.remove(fullfile)
except BadZipfile:
os.remove(fullfile)
#else:
# shutil.rmtree(downloaded_dir)
else:
downloaded_dir = os.path.join(proj_path, 'temp')
try:
os.makedirs(downloaded_dir)
except OSError:
pass
fullfile = os.path.join(downloaded_dir, file_name)
if actually_download:
if not root and not hasattr(main, '__file__'):
txt = 'CoreNLP not found. Download latest version (%s)? (y/n) ' % url
<|code_end|>
using the current file's imports:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from time import localtime, strftime
from corpkit.textprogressbar import TextProgressBar
from corpkit.process import animator
from zipfile import BadZipfile
from time import localtime, strftime
from zipfile import BadZipfile
from subprocess import PIPE, STDOUT, Popen
from subprocess import PIPE, STDOUT, Popen
from corpkit.process import get_corenlp_path
from time import localtime, strftime
from corpkit.constants import CORENLP_URL as url
from corpkit.constants import CORENLP_VERSION
from corpkit.constants import CORENLP_VERSION
from corpkit.process import saferead
from corpkit.constants import MAX_SPEAKERNAME_SIZE
from time import localtime, strftime
from corpkit.corpus import Corpus
from corpkit.constants import OPENER, PYTHON_VERSION, MAX_METADATA_FIELDS
from corpkit.process import saferead
from corpkit.process import saferead
from corpkit.constants import MAX_METADATA_VALUES
from glob import glob
from glob import glob
from corpkit.process import makesafe
import os
import shutil
import glob
import zipfile
import __main__ as main
import requests
import traceback
import zipfile
import os
import fnmatch
import os
import corpkit
import subprocess
import subprocess
import os
import sys
import re
import chardet
import time
import shutil
import glob
import importlib
import corpkit
import shutil
import os
import fnmatch
import corpkit
import os
import os
import os
import re
import shutil
import os
import re
import os
import re
import os
import re
import os
import os
import shutil
and any relevant context from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
. Output only the next line. | selection = INPUTFUNC(txt) |
Here is a snippet: <|code_start|> print("%s: Couldn't find Tregex in %s." % (thetime, ', '.join(possible_paths)))
return False
if not query:
query = 'NP'
# if checking for trees, use the -T option
if check_for_trees:
options = ['-o', '-T']
filenaming = False
if isinstance(options, list):
if '-f' in options:
filenaming = True
# append list of options to query
if options:
if '-s' not in options and '-t' not in options:
options.append('-s')
else:
options = ['-o', '-t']
for opt in options:
tregex_command.append(opt)
if query:
tregex_command.append(query)
# if corpus is string or unicode, and is path, add that
# if it's not string or unicode, it's some kind of corpus obj
# in which case, add its path var
if corpus:
<|code_end|>
. Write the next line using the current file imports:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from subprocess import Popen, PIPE, STDOUT
from time import localtime, strftime
from corpkit.dictionaries.word_transforms import wordlist
from collections import Counter
from corpkit.dictionaries.process_types import Wordlist
from time import localtime, strftime
from corpkit.other import as_regex
from traitlets import TraitError
from ipywidgets import IntProgress, HTML, VBox
from IPython.display import display
from ipywidgets.widgets.widget_box import Box
from corpkit.textprogressbar import TextProgressBar
from corpkit.build import get_speaker_names_from_parsed_corpus
from time import localtime, strftime
from corpkit.process import is_number
from collections import Counter
from pandas import DataFrame
from corpkit.editor import editor
from corpkit.dictionaries import taglemma
from corpkit.dictionaries import taglemma
from nltk.tree import ParentedTree
from nltk.tgrep import tgrep_nodes, tgrep_positions
from cPickle import UnpickleableError as unpick_error
from cPickle import PicklingError as unpick_error_2
from pickle import UnpicklingError as unpick_error
from pickle import PicklingError as unpick_error_2
from corpkit.gui import corpkit_gui
from corpkit.constants import transshow, transobjs
from corpkit.dictionaries.process_types import Wordlist
from corpkit.constants import transshow, transobjs
from corpkit.constants import CONLL_COLUMNS
from corpkit.process import lemmatiser
from corpkit.dictionaries.word_transforms import wordlist, taglemma
from nltk.stem.wordnet import WordNetLemmatizer
from corpkit.corpus import Corpus
from corpkit.build import get_all_metadata_fields, get_speaker_names_from_parsed_corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus, Subcorpus
import corpkit
import subprocess
import re
import os
import sys
import corpkit
import sys
import os
import inspect
import nltk
import os
import inspect
import os
import sys
import os
import os
import re
import traceback
import sys
import re
import inspect
import os
import subprocess
import os
import sys
import re
import glob
import os
import cPickle as pickle
import pickle
import chardet
import sys
import re
import os
import re
import re
import re
import os
import os
import json
import os
import json
import re
and context from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
, which may include functions, classes, or code. Output only the next line. | if isinstance(corpus, STRINGTYPE): |
Next line prediction: <|code_start|> else:
start = ' '.join([w for w, p, i in start])
end = ' '.join([w for w, p, i in end])
return ixs[0], start, middle, end
def tgrep(parse_string, search):
"""
Uses tgrep to search a parse tree string
:param parse_string: A bracketed tree
:type parse_string: `str`
:param search: A search query
:type search: `str` -- Tgrep query
"""
pt = ParentedTree.fromstring(parse_string)
ptrees = [i for i in list(tgrep_nodes(search, [pt])) if i]
return [item for sublist in ptrees for item in sublist]
def canpickle(obj):
"""
Determine if object can be pickled
:returns: `bool`
"""
try:
except ImportError:
<|code_end|>
. Use current file imports:
(from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from subprocess import Popen, PIPE, STDOUT
from time import localtime, strftime
from corpkit.dictionaries.word_transforms import wordlist
from collections import Counter
from corpkit.dictionaries.process_types import Wordlist
from time import localtime, strftime
from corpkit.other import as_regex
from traitlets import TraitError
from ipywidgets import IntProgress, HTML, VBox
from IPython.display import display
from ipywidgets.widgets.widget_box import Box
from corpkit.textprogressbar import TextProgressBar
from corpkit.build import get_speaker_names_from_parsed_corpus
from time import localtime, strftime
from corpkit.process import is_number
from collections import Counter
from pandas import DataFrame
from corpkit.editor import editor
from corpkit.dictionaries import taglemma
from corpkit.dictionaries import taglemma
from nltk.tree import ParentedTree
from nltk.tgrep import tgrep_nodes, tgrep_positions
from cPickle import UnpickleableError as unpick_error
from cPickle import PicklingError as unpick_error_2
from pickle import UnpicklingError as unpick_error
from pickle import PicklingError as unpick_error_2
from corpkit.gui import corpkit_gui
from corpkit.constants import transshow, transobjs
from corpkit.dictionaries.process_types import Wordlist
from corpkit.constants import transshow, transobjs
from corpkit.constants import CONLL_COLUMNS
from corpkit.process import lemmatiser
from corpkit.dictionaries.word_transforms import wordlist, taglemma
from nltk.stem.wordnet import WordNetLemmatizer
from corpkit.corpus import Corpus
from corpkit.build import get_all_metadata_fields, get_speaker_names_from_parsed_corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus, Subcorpus
import corpkit
import subprocess
import re
import os
import sys
import corpkit
import sys
import os
import inspect
import nltk
import os
import inspect
import os
import sys
import os
import os
import re
import traceback
import sys
import re
import inspect
import os
import subprocess
import os
import sys
import re
import glob
import os
import cPickle as pickle
import pickle
import chardet
import sys
import re
import os
import re
import re
import re
import os
import os
import json
import os
import json
import re)
and context including class names, function names, or small code snippets from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
. Output only the next line. | mode = 'w' if PYTHON_VERSION == 2 else 'wb' |
Next line prediction: <|code_start|> else:
filtermode = True
elif hasattr(corpus, 'path'):
tregex_command.append(corpus.path)
if filtermode:
tregex_command.append('-filter')
if not filtermode:
res = subprocess.check_output(tregex_command, stderr=send_stderr_to)
res = res.decode(encoding='UTF-8').splitlines()
else:
p = Popen(tregex_command, stdout=PIPE, stdin=PIPE, stderr=send_stderr_to)
p.stdin.write(corpus.encode('UTF-8', errors='ignore'))
res = p.communicate()[0].decode(encoding='UTF-8').splitlines()
p.stdin.close()
# Fix up the stderr stdout rubbish
if check_query:
# define error searches
tregex_error = re.compile(r'^Error parsing expression')
regex_error = re.compile(r'^Exception in thread.*PatternSyntaxException')
# if tregex error, give general error message
if re.match(tregex_error, res[0]):
if root:
time = strftime("%H:%M:%S", localtime())
print('%s: Error parsing Tregex query.' % time)
return False
time = strftime("%H:%M:%S", localtime())
<|code_end|>
. Use current file imports:
(from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
from subprocess import Popen, PIPE, STDOUT
from time import localtime, strftime
from corpkit.dictionaries.word_transforms import wordlist
from collections import Counter
from corpkit.dictionaries.process_types import Wordlist
from time import localtime, strftime
from corpkit.other import as_regex
from traitlets import TraitError
from ipywidgets import IntProgress, HTML, VBox
from IPython.display import display
from ipywidgets.widgets.widget_box import Box
from corpkit.textprogressbar import TextProgressBar
from corpkit.build import get_speaker_names_from_parsed_corpus
from time import localtime, strftime
from corpkit.process import is_number
from collections import Counter
from pandas import DataFrame
from corpkit.editor import editor
from corpkit.dictionaries import taglemma
from corpkit.dictionaries import taglemma
from nltk.tree import ParentedTree
from nltk.tgrep import tgrep_nodes, tgrep_positions
from cPickle import UnpickleableError as unpick_error
from cPickle import PicklingError as unpick_error_2
from pickle import UnpicklingError as unpick_error
from pickle import PicklingError as unpick_error_2
from corpkit.gui import corpkit_gui
from corpkit.constants import transshow, transobjs
from corpkit.dictionaries.process_types import Wordlist
from corpkit.constants import transshow, transobjs
from corpkit.constants import CONLL_COLUMNS
from corpkit.process import lemmatiser
from corpkit.dictionaries.word_transforms import wordlist, taglemma
from nltk.stem.wordnet import WordNetLemmatizer
from corpkit.corpus import Corpus
from corpkit.build import get_all_metadata_fields, get_speaker_names_from_parsed_corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus
from corpkit.constants import OPENER
from corpkit.corpus import Corpus, Subcorpus
import corpkit
import subprocess
import re
import os
import sys
import corpkit
import sys
import os
import inspect
import nltk
import os
import inspect
import os
import sys
import os
import os
import re
import traceback
import sys
import re
import inspect
import os
import subprocess
import os
import sys
import re
import glob
import os
import cPickle as pickle
import pickle
import chardet
import sys
import re
import os
import re
import re
import re
import os
import os
import json
import os
import json
import re)
and context including class names, function names, or small code snippets from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
#
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
. Output only the next line. | selection = INPUTFUNC('\n%s: Error parsing Tregex expression "%s".'\ |
Given the code snippet: <|code_start|> locs = locals()
try:
get_ipython().getoutput()
except TypeError:
have_ipython = True
except NameError:
have_ipython = False
try:
except ImportError:
pass
# new ipython error
except AttributeError:
have_ipython = False
pass
# to use if we also need to worry about concordance lines
return_conc = False
if interrogation.__class__ == Interrodict:
locs.pop('interrogation', None)
outdict = OrderedDict()
for i, (k, v) in enumerate(interrogation.items()):
# only print the first time around
if i != 0:
locs['print_info'] = False
<|code_end|>
, generate the next line using the imports in this file:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION
from pandas import DataFrame, Series
from time import localtime, strftime
from IPython.display import display, clear_output
from corpkit.interrogation import Interrodict, Interrogation, Concordance
from collections import OrderedDict
from process import checkstack
from corpkit.process import checkstack
from corpkit.dictionaries.process_types import Wordlist
from corpkit.dictionaries.process_types import Wordlist
from nltk.corpus import wordnet as wn
from collections import Counter
from dictionaries.word_transforms import usa_convert
from scipy.stats import linregress
from pandas import Series
from scipy.stats import linregress
from corpkit.keys import keywords
import corpkit
import re
import collections
import pandas as pd
import numpy as np
import warnings
import warnings
import re
import re
import operator
and context (functions, classes, or occasionally code) from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
. Output only the next line. | if isinstance(denominator, STRINGTYPE) and denominator.lower() == 'self': |
Next line prediction: <|code_start|> showing = 'subcorpora'
if getattr(self, 'subcorpora', False):
sclen = len(self.subcorpora)
else:
showing = 'files'
sclen = len(self.files)
show = 'Corpus at %s:\n\nData type: %s\nNumber of %s: %d\n' % (
self.path, self.datatype, showing, sclen)
val = self.symbolic if self.symbolic else 'default'
show += 'Subcorpora: %s\n' % val
if self.singlefile:
show += '\nCorpus is a single file.\n'
#if getattr(self, 'symbolic'):
# show += 'Symbolic subcorpora: %s\n' % str(self.symbolic)
if getattr(self, 'skip'):
show += 'Skip: %s\n' % str(self.skip)
if getattr(self, 'just'):
show += 'Just: %s\n' % str(self.just)
return show
def __repr__(self):
"""
Object representation of corpus
"""
if not self.subcorpora:
ssubcorpora = ''
else:
ssubcorpora = self.subcorpora
return "<%s instance: %s; %d subcorpora>" % (
<|code_end|>
. Use current file imports:
(from lazyprop import lazyprop
from corpkit.process import classname
from corpkit.constants import STRINGTYPE, PYTHON_VERSION
from os.path import join, isfile, isdir, abspath, dirname, basename
from corpkit.process import determine_datatype
from corpkit.other import load
from corpkit.process import makesafe
from os.path import join, isdir
from corpkit.build import get_speaker_names_from_parsed_corpus
from os.path import join, isdir
from corpkit.constants import OPENER
from sklearn.feature_extraction.text import TfidfVectorizer
from corpkit.constants import STRINGTYPE
from corpkit.process import makesafe
from corpkit.constants import STRINGTYPE
from corpkit.process import makesafe
from corpkit.dictionaries.word_transforms import mergetags
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.dictionaries.word_transforms import mergetags
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.configurations import configurations
from corpkit.interrogator import interrogator
from corpkit.interrogation import Interrodict
from corpkit.constants import transshow, transobjs
from corpkit.process import get_corpus_metadata
from corpkit.make import make_corpus
from corpkit.make import make_corpus
from corpkit.other import save
from corpkit.other import load
from corpkit.model import MultiModel
from corpkit.interrogation import Interrogation
from corpkit.annotate import annotator
from corpkit.process import make_dotfile
from corpkit.annotate import annotator
from corpkit.process import makesafe
from corpkit.process import is_number
from os.path import join, isfile, isdir
from corpkit.constants import OPENER
from corpkit.conll import parse_conll
from corpkit.process import saferead
from nltk import Tree
from collections import OrderedDict
from corpkit.constants import STRINGTYPE
from corpkit.constants import STRINGTYPE
from corpkit.interrogator import interrogator
from corpkit.interrogation import Interrodict
from corpkit.interrogator import interrogator
from corpkit.configurations import configurations
from os.path import join, isfile, isdir
from corpkit.corpus import Corpora
from corpkit.interrogation import Interrodict
import re
import operator
import glob
import os
import re
import os
import operator
import re
import os
import operator
import os
import pandas as pd
import pandas as pd
import pandas as pd
import pandas as pd
import random
import os
import os
import os
import os
import os)
and context including class names, function names, or small code snippets from other files:
# Path: corpkit/process.py
# def classname(cls):
# """Create the class name str for __repr__"""
# return '.'.join([cls.__class__.__module__, cls.__class__.__name__])
#
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
. Output only the next line. | classname(self), os.path.basename(self.path), len(ssubcorpora)) |
Continue the code snippet: <|code_start|> can be parsed, and only parsed/tokenised corpora can be interrogated.
"""
def __init__(self, path, **kwargs):
# levels are 'c' for corpus, 's' for subcorpus and 'f' for file. Which
# one is determined automatically below, and processed accordingly. We
# assume it is a full corpus to begin with.
def get_symbolics(self):
return {'skip': self.skip,
'just': self.just,
'symbolic': self.symbolic}
self.data = None
self._dlist = None
self.level = kwargs.pop('level', 'c')
self.datatype = kwargs.pop('datatype', None)
self.print_info = kwargs.pop('print_info', True)
self.symbolic = kwargs.get('subcorpora', False)
self.skip = kwargs.get('skip', False)
self.just = kwargs.get('just', False)
self.kwa = get_symbolics(self)
if isinstance(path, (list, Datalist)):
self.path = abspath(dirname(path[0].path.rstrip('/')))
self.name = basename(self.path)
self.data = path
if self.level == 'd':
self._dlist = path
<|code_end|>
. Use current file imports:
from lazyprop import lazyprop
from corpkit.process import classname
from corpkit.constants import STRINGTYPE, PYTHON_VERSION
from os.path import join, isfile, isdir, abspath, dirname, basename
from corpkit.process import determine_datatype
from corpkit.other import load
from corpkit.process import makesafe
from os.path import join, isdir
from corpkit.build import get_speaker_names_from_parsed_corpus
from os.path import join, isdir
from corpkit.constants import OPENER
from sklearn.feature_extraction.text import TfidfVectorizer
from corpkit.constants import STRINGTYPE
from corpkit.process import makesafe
from corpkit.constants import STRINGTYPE
from corpkit.process import makesafe
from corpkit.dictionaries.word_transforms import mergetags
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.dictionaries.word_transforms import mergetags
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.process import get_corpus_metadata, add_df_to_dotfile, make_df_json_name
from corpkit.interrogation import Interrodict
from corpkit.configurations import configurations
from corpkit.interrogator import interrogator
from corpkit.interrogation import Interrodict
from corpkit.constants import transshow, transobjs
from corpkit.process import get_corpus_metadata
from corpkit.make import make_corpus
from corpkit.make import make_corpus
from corpkit.other import save
from corpkit.other import load
from corpkit.model import MultiModel
from corpkit.interrogation import Interrogation
from corpkit.annotate import annotator
from corpkit.process import make_dotfile
from corpkit.annotate import annotator
from corpkit.process import makesafe
from corpkit.process import is_number
from os.path import join, isfile, isdir
from corpkit.constants import OPENER
from corpkit.conll import parse_conll
from corpkit.process import saferead
from nltk import Tree
from collections import OrderedDict
from corpkit.constants import STRINGTYPE
from corpkit.constants import STRINGTYPE
from corpkit.interrogator import interrogator
from corpkit.interrogation import Interrodict
from corpkit.interrogator import interrogator
from corpkit.configurations import configurations
from os.path import join, isfile, isdir
from corpkit.corpus import Corpora
from corpkit.interrogation import Interrodict
import re
import operator
import glob
import os
import re
import os
import operator
import re
import os
import operator
import os
import pandas as pd
import pandas as pd
import pandas as pd
import pandas as pd
import random
import os
import os
import os
import os
import os
and context (classes, functions, or code) from other files:
# Path: corpkit/process.py
# def classname(cls):
# """Create the class name str for __repr__"""
# return '.'.join([cls.__class__.__module__, cls.__class__.__name__])
#
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
. Output only the next line. | elif isinstance(path, STRINGTYPE): |
Given the code snippet: <|code_start|> rot=rot)
return nplt
def copy(self):
copied = {}
for k, v in self.items():
copied[k] = v
return Interrodict(copied)
# check what environment we're in
tk = checkstack('tkinter')
running_python_tex = checkstack('pythontex')
running_spider = checkstack('spyder')
if not title:
title = ''
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
"""remove extreme values from colourmap --- no pure white"""
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap
def get_savename(imagefolder, save = False, title = False, ext = 'png'):
"""Come up with the savename for the image."""
# name as
if not ext.startswith('.'):
ext = '.' + ext
<|code_end|>
, generate the next line using the imports in this file:
from corpkit.constants import STRINGTYPE, PYTHON_VERSION
from IPython.utils.shimmodule import ShimWarning
from matplotlib import rc
from pandas import DataFrame, Series, MultiIndex
from time import localtime, strftime
from process import checkstack
from mpld3 import plugins, utils
from plugins import InteractiveLegendPlugin, HighlightLines
from mpldatacursor import datacursor, HighlightingDataCursor
from corpkit.interrogation import Interrogation
from corpkit.interrogation import Interrodict
from corpkit.process import urlify
from matplotlib.colors import LinearSegmentedColormap
from corpkit.interrogation import Interrogation
from corpkit.layouts import layouts
from corpkit.process import urlify
import corpkit
import os
import warnings
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt, mpld3
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import pandas
import mpld3
import collections
import matplotlib.pyplot as nplt
import matplotlib.colors as colors
import numpy as np
import os
import warnings
import matplotlib.pyplot as plt
import matplotlib as mpl
import os
and context (functions, classes, or occasionally code) from other files:
# Path: corpkit/constants.py
# STRINGTYPE = str if PYTHON_VERSION == 3 else basestring
#
# PYTHON_VERSION = sys.version_info.major
. Output only the next line. | if isinstance(save, STRINGTYPE): |
Given the following code snippet before the placeholder: <|code_start|> unparsed_corpus_path = os.path.abspath(unparsed_corpus_path)
# move it into project
if fileparse:
datapath = project_path
else:
datapath = join(project_path, 'data')
if isdir(datapath):
newp = join(datapath, basename(unparsed_corpus_path))
else:
os.makedirs(datapath)
if fileparse:
noext = splitext(unparsed_corpus_path)[0]
newp = join(datapath, basename(noext))
else:
newp = join(datapath, basename(unparsed_corpus_path))
if exists(newp):
pass
else:
copier(unparsed_corpus_path, newp)
unparsed_corpus_path = newp
# ask to folderise?
check_do_folderise = False
do_folderise = kwargs.get('folderise', None)
if can_folderise(unparsed_corpus_path):
if do_folderise is None and not hasattr(main, '__file__'):
<|code_end|>
, predict the next line using imports from the current file:
from corpkit.constants import INPUTFUNC, PYTHON_VERSION
from os.path import join, isfile, isdir, basename, splitext, exists
from corpkit.build import folderise, can_folderise
from corpkit.process import saferead, make_dotfile
from corpkit.build import (get_corpus_filepaths,
check_jdk,
rename_all_files,
make_no_id_corpus, parse_corpus, move_parsed_files)
from corpkit.constants import REPEAT_PARSE_ATTEMPTS, OPENER, PYTHON_VERSION
from joblib import Parallel, delayed
from corpkit.constants import OPENER
from corpkit.conll import convert_json_to_conll
from corpkit.tokenise import plaintext_to_conll
import sys
import os
import shutil
import codecs
import __main__ as main
import __main__ as main
import multiprocessing
import shutil
and context including class names, function names, and sometimes code from other files:
# Path: corpkit/constants.py
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
#
# PYTHON_VERSION = sys.version_info.major
. Output only the next line. | check_do_folderise = INPUTFUNC("Your corpus has multiple files, but no subcorpora. "\ |
Predict the next line for this snippet: <|code_start|> def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
if (parse or tokenise) and coref:
# this loop shortens files containing more than 500 lines,
# for corenlp memory's sake. maybe user needs a warning or
# something in case s/he is doing coref?
# try block because it isn't necessarily essential that this works.
# just delete generated files if it fails part way
split_f_names = []
try:
for rootx, dirs, fs in os.walk(unparsed_corpus_path):
for f in fs:
# skip hidden files
if f.startswith('.'):
continue
fp = join(rootx, f)
data, enc = saferead(fp)
data = data.splitlines()
if len(data) > split_texts:
chk = chunks(data, split_texts)
for index, c in enumerate(chk):
newname = fp.replace('.txt', '-%s.txt' % str(index + 1).zfill(3))
split_f_names.append(newname)
data = '\n'.join(c) + '\n'
# does this work?
with OPENER(newname, 'w') as fo:
<|code_end|>
with the help of current file imports:
from corpkit.constants import INPUTFUNC, PYTHON_VERSION
from os.path import join, isfile, isdir, basename, splitext, exists
from corpkit.build import folderise, can_folderise
from corpkit.process import saferead, make_dotfile
from corpkit.build import (get_corpus_filepaths,
check_jdk,
rename_all_files,
make_no_id_corpus, parse_corpus, move_parsed_files)
from corpkit.constants import REPEAT_PARSE_ATTEMPTS, OPENER, PYTHON_VERSION
from joblib import Parallel, delayed
from corpkit.constants import OPENER
from corpkit.conll import convert_json_to_conll
from corpkit.tokenise import plaintext_to_conll
import sys
import os
import shutil
import codecs
import __main__ as main
import __main__ as main
import multiprocessing
import shutil
and context from other files:
# Path: corpkit/constants.py
# INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input
#
# PYTHON_VERSION = sys.version_info.major
, which may contain function names, class names, or code. Output only the next line. | if PYTHON_VERSION == 2: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.