Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>"""Script defined to test the Plan class.""" class TestPlan(BaseTestCase): """Class to test Plans.""" @httpretty.activate def test_create(self): """Method defined to test plan creation.""" httpretty.register_uri( httpretty.POST, self.endpoint_url("/plan"), content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) <|code_end|> using the current file's imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.plan import Plan and any relevant context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/plan.py # class Plan(PayStackBase): # """docstring for Plan.""" # # @classmethod # def create(cls, **kwargs): # """ # Function defined to create a plan. # # Args: # name: plan's name. # description: description of the plan. # amount: amount for the plan in kobo # interval: plan's interval # send_invoices: boolean # send_sms: # hosted_page: # hosted_page_url: url of hosted page # hosted_page_summary: summary of the hosted page # currency: plans currency # # Returns: # Json data from paystack API. # """ # return cls().requests.post('plan', data=kwargs) # # @classmethod # def get(cls, plan_id): # """ # Get a single plan. # # Args: # plan_id: paystack plan id. # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"plan/{plan_id}") # # @classmethod # def list(cls): # """ # Static method defined to list paystack plan. # # Args: # No argument required. # Returns: # Json data from paystack API. # """ # return cls().requests.get('plan') # # @classmethod # def update(cls, plan_id, **kwargs): # """ # Static method defined to update paystack plan. # # Args: # plan_id: plan identity number. # name: name of plan # description: plan description(optional) # amount: plan amount in Naira # interval: plan interval # send_invoice: # send_sms: (optional) # hosted_page: (optional) # hosted_page_url: (optional) # hosted_page_summary: (optional) # currency: Naira # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"plan/{plan_id}", data=kwargs,) . Output only the next line.
response = Plan.create(
Continue the code snippet: <|code_start|>format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ ([Token(Token.LIMIT, '')], InvalidLimit), ([Token(Token.WHERE, ''), Token(Token.IDENTIFIER, '')], InvalidCondition), ]) def test_parse_exceptions(tokens, exception): with pytest.raises(exception): list(parse(tokens)) def test_parse_identifier_with_exception(): with pytest.raises(InvalidIdentifier): _parse_identifier([]) @pytest.mark.parametrize(('tokens', 'expected_value', 'expected_count'), [ ([Token(Token.IDENTIFIER, 'ident')], <|code_end|> . Use current file imports: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
Identifier('ident'),
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ ([Token(Token.LIMIT, '')], InvalidLimit), <|code_end|> , generate the next line using the imports in this file: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context (functions, classes, or occasionally code) from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
([Token(Token.WHERE, ''), Token(Token.IDENTIFIER, '')], InvalidCondition),
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ ([Token(Token.LIMIT, '')], InvalidLimit), ([Token(Token.WHERE, ''), Token(Token.IDENTIFIER, '')], InvalidCondition), ]) def test_parse_exceptions(tokens, exception): with pytest.raises(exception): list(parse(tokens)) def test_parse_identifier_with_exception(): <|code_end|> . Write the next line using the current file imports: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None , which may include functions, classes, or code. Output only the next line.
with pytest.raises(InvalidIdentifier):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ <|code_end|> , predict the next line using imports from the current file: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context including class names, function names, and sometimes code from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
([Token(Token.LIMIT, '')], InvalidLimit),
Next line prediction: <|code_start|>Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ ([Token(Token.LIMIT, '')], InvalidLimit), ([Token(Token.WHERE, ''), Token(Token.IDENTIFIER, '')], InvalidCondition), ]) def test_parse_exceptions(tokens, exception): with pytest.raises(exception): list(parse(tokens)) def test_parse_identifier_with_exception(): with pytest.raises(InvalidIdentifier): _parse_identifier([]) @pytest.mark.parametrize(('tokens', 'expected_value', 'expected_count'), [ ([Token(Token.IDENTIFIER, 'ident')], Identifier('ident'), 1), ([Token(Token.NUMBER, '1')], <|code_end|> . Use current file imports: (import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token) and context including class names, function names, or small code snippets from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
Number('1'),
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ ([Token(Token.LIMIT, '')], InvalidLimit), ([Token(Token.WHERE, ''), Token(Token.IDENTIFIER, '')], InvalidCondition), ]) def test_parse_exceptions(tokens, exception): with pytest.raises(exception): list(parse(tokens)) def test_parse_identifier_with_exception(): with pytest.raises(InvalidIdentifier): <|code_end|> . Write the next line using the current file imports: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None , which may include functions, classes, or code. Output only the next line.
_parse_identifier([])
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): <|code_end|> . Use current file imports: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
parsed_statements = list(parse(tokens1))
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def assert_statements(tokens1, statements2): parsed_statements = list(parse(tokens1)) assert parsed_statements == statements2 @pytest.mark.parametrize(('tokens', 'exception'), [ <|code_end|> , predict the immediate next line with the help of imports: import pytest from format_sql.parser import (Identifier, InvalidCondition, InvalidIdentifier, InvalidLimit, Number, _parse_identifier, parse) from format_sql.tokenizer import Token and context (classes, functions, sometimes code) from other files: # Path: format_sql/parser.py # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class InvalidCondition(InvalidSQL): # pass # # class InvalidIdentifier(InvalidSQL): # pass # # class InvalidLimit(InvalidSQL): # pass # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # def _parse_identifier(toks): # count = 0 # # if _match(toks, [(Token.IDENTIFIER, Token.STR, Token.NUMBER)]): # if toks[0]._type == Token.IDENTIFIER: # cls = Identifier # elif toks[0]._type == Token.NUMBER: # cls = Number # # value = cls(toks[0]._value) # count += 1 # # alias, j = _parse_alias(toks[count:]) # count += j # value.as_ = alias['as'] # value.alias = alias['alias'] # # return value, count # # raise InvalidIdentifier(toks) # # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None . Output only the next line.
([Token(Token.LIMIT, '')], InvalidLimit),
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def _match(toks, types_list): if len(toks) < len(types_list): return False for tok, types in zip(toks, types_list): if types is None: continue if not isinstance(types, tuple): types = (types,) if tok._type not in types: return False return True def _get_simple_object(tok, **kwargs): clazz = { <|code_end|> with the help of current file imports: import attr from format_sql.tokenizer import Token and context from other files: # Path: format_sql/tokenizer.py # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None , which may contain function names, class names, or code. Output only the next line.
Token.IDENTIFIER: Identifier,
Predict the next line for this snippet: <|code_start|> ('<>', (Token.COMPARE, '<>')), ('<', (Token.COMPARE, '<')), ('>', (Token.COMPARE, '>')), ('!=', (Token.COMPARE, '!=')), ('>=', (Token.COMPARE, '>=')), ('<=', (Token.COMPARE, '<=')), ]) def test_tokenize_compare(sql, expected_token): token_type, token_value = expected_token token = Token(token_type, token_value) assert_tokens([token], tokenize(sql)) @pytest.mark.parametrize(('sql', 'expected_token'), [ ('and', (Token.LINK, 'and')), ('Or', (Token.LINK, 'Or')), ]) def test_tokenize_link(sql, expected_token): token_type, token_value = expected_token token = Token(token_type, token_value) assert_tokens([token], tokenize(sql)) @pytest.mark.parametrize('sql', [ '"213', '"s s( ) ss\'', ]) def test_tokenize_str_is_not_terminated(sql): <|code_end|> with the help of current file imports: import pytest from format_sql.tokenizer import StringNotTerminated, Token, tokenize from itertools import zip_longest from itertools import izip_longest as zip_longest and context from other files: # Path: format_sql/tokenizer.py # class StringNotTerminated(Exception): # pass # # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None # # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) , which may contain function names, class names, or code. Output only the next line.
with pytest.raises(StringNotTerminated):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ try: except ImportError: def assert_tokens(tokens1, tokens2): tokens2 = list(tokens2) for tk1, tk2 in zip_longest(tokens1, tokens2): assert tk1._value == tk2._value, ">%s< >%s<" % (tk1, tk2) assert tk1._type == tk2._type, ">%s< >%s<" % (tk1, tk2) @pytest.mark.parametrize(('sql', 'expected_tokens'), [ ('GROUP BY year', [ <|code_end|> using the current file's imports: import pytest from format_sql.tokenizer import StringNotTerminated, Token, tokenize from itertools import zip_longest from itertools import izip_longest as zip_longest and any relevant context from other files: # Path: format_sql/tokenizer.py # class StringNotTerminated(Exception): # pass # # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None # # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) . Output only the next line.
(Token.GROUP_BY, 'GROUP BY'),
Here is a snippet: <|code_start|> ]), ('select count\n(distinct(1)) from my_table', [ (Token.SELECT, 'select'), (Token.FUNC, 'count'), (Token.PARENTHESIS_OPEN, '('), (Token.FUNC, 'distinct'), (Token.PARENTHESIS_OPEN, '('), (Token.NUMBER, '1'), (Token.PARENTHESIS_CLOSE, ')'), (Token.PARENTHESIS_CLOSE, ')'), (Token.FROM, 'from'), (Token.IDENTIFIER, 'my_table'), ]), ('select count(1) as cnt from my_table', [ (Token.SELECT, 'select'), (Token.FUNC, 'count'), (Token.PARENTHESIS_OPEN, '('), (Token.NUMBER, '1'), (Token.PARENTHESIS_CLOSE, ')'), (Token.AS, 'as'), (Token.IDENTIFIER, 'cnt'), (Token.FROM, 'from'), (Token.IDENTIFIER, 'my_table'), ]), ]) def test_tokenize(sql, expected_tokens): tokens = [Token(token_type, token_value) for token_type, token_value in expected_tokens] <|code_end|> . Write the next line using the current file imports: import pytest from format_sql.tokenizer import StringNotTerminated, Token, tokenize from itertools import zip_longest from itertools import izip_longest as zip_longest and context from other files: # Path: format_sql/tokenizer.py # class StringNotTerminated(Exception): # pass # # class Token: # AS = 'AS' # ASC = 'ASC' # COMMA = ',' # COMPARE = 'compare' # DESC = 'DESC' # FROM = 'FROM' # FUNC = 'func' # GROUP_BY = 'GROUP' # IDENTIFIER = 'identifier' # IN = 'IN' # INSERT = 'INSERT' # IS = 'IS' # ON = 'ON' # NULL = 'NULL' # HAVING = 'HAVING' # JOIN = 'join' # LIMIT = 'LIMIT' # LINK = 'link' # NOT = 'NOT' # NUMBER = 'number' # ORDER_BY = 'ORDER' # PARENTHESIS_CLOSE = ')' # PARENTHESIS_OPEN = '(' # SEMICOLON = ';' # SELECT = 'SELECT' # STR = 'str' # WITH_ROLLUP = 'WITH' # WHERE = 'WHERE' # VALUES = 'VALUES' # BETWEEN = 'BETWEEN' # CASE = 'CASE' # WHEN = 'WHEN' # THEN = 'THEN' # ELSE = 'ELSE' # # def __init__(self, token_type, token_value): # self._type = token_type # self._value = token_value # # def __repr__(self): # return '<%s: %s>' % (self._type, self._value) # # @staticmethod # def get_token(value): # normalized = value.split()[0].upper() # # if normalized in TOKEN_RES.keys(): # return normalized # # normalized = value.split()[-1].upper() # if normalized == 'JOIN': # return Token.JOIN # # return None # # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) , which may include functions, classes, or code. Output only the next line.
assert_tokens(tokens, tokenize(sql))
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def format_sql(s, debug=False): tokens = list(tokenize(s)) if debug: print_non_data('Tokens: %s' % tokens) <|code_end|> , continue by predicting the next line. Consider current file imports: from format_sql.parser import parse from format_sql.styler import style from format_sql.tokenizer import tokenize from format_sql.util import print_non_data and context: # Path: format_sql/parser.py # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/styler.py # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines # # Path: format_sql/tokenizer.py # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) # # Path: format_sql/util.py # def print_non_data(msg): # print(msg, file=sys.stderr) which might include code, classes, or functions. Output only the next line.
parsed = list(parse(tokens))
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def format_sql(s, debug=False): tokens = list(tokenize(s)) if debug: print_non_data('Tokens: %s' % tokens) parsed = list(parse(tokens)) if debug: print_non_data('Statements: %s' % parsed) <|code_end|> , predict the immediate next line with the help of imports: from format_sql.parser import parse from format_sql.styler import style from format_sql.tokenizer import tokenize from format_sql.util import print_non_data and context (classes, functions, sometimes code) from other files: # Path: format_sql/parser.py # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/styler.py # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines # # Path: format_sql/tokenizer.py # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) # # Path: format_sql/util.py # def print_non_data(msg): # print(msg, file=sys.stderr) . Output only the next line.
styled = style(parsed)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def format_sql(s, debug=False): <|code_end|> with the help of current file imports: from format_sql.parser import parse from format_sql.styler import style from format_sql.tokenizer import tokenize from format_sql.util import print_non_data and context from other files: # Path: format_sql/parser.py # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/styler.py # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines # # Path: format_sql/tokenizer.py # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) # # Path: format_sql/util.py # def print_non_data(msg): # print(msg, file=sys.stderr) , which may contain function names, class names, or code. Output only the next line.
tokens = list(tokenize(s))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def format_sql(s, debug=False): tokens = list(tokenize(s)) if debug: <|code_end|> . Write the next line using the current file imports: from format_sql.parser import parse from format_sql.styler import style from format_sql.tokenizer import tokenize from format_sql.util import print_non_data and context from other files: # Path: format_sql/parser.py # def parse(toks): # for statement, unused_count in _parse(toks): # yield statement # # Path: format_sql/styler.py # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines # # Path: format_sql/tokenizer.py # def tokenize(s): # last_type = None # for word in cutter(s): # token_type = Token.get_token(word) # if token_type: # last_type = token_type # yield Token(token_type, word) # # elif word[0].isdigit() or word.startswith(('+', '-')): # yield Token(Token.NUMBER, word) # # elif word.endswith('('): # if last_type == Token.INSERT: # token_type = Token.IDENTIFIER # else: # token_type = Token.FUNC # yield Token(token_type, word[:-1].strip()) # yield Token(Token.PARENTHESIS_OPEN, '(') # # elif word.startswith(STR_STARTERS): # yield Token(Token.STR, word) # # elif word in ('=', '<>', '<', '>', '!=', '>=', '<=') or word.upper() == 'LIKE': # yield Token(Token.COMPARE, word) # # elif word.upper() in ('AND', 'OR'): # yield Token(Token.LINK, word) # # else: # yield Token(Token.IDENTIFIER, word) # # Path: format_sql/util.py # def print_non_data(msg): # print(msg, file=sys.stderr) , which may include functions, classes, or code. Output only the next line.
print_non_data('Tokens: %s' % tokens)
Given the following code snippet before the placeholder: <|code_start|> liner.add_to_line(' '.join('%s' % x for x in condition.values)) i += 1 liner.end_line() if types_match(condition, [Not, Func, Operator, Number]): liner.add_to_line('NOT') liner.add_to_line(' ') _style_func(condition.values[1], liner, end_line=False) liner.add_to_line(' ') liner.add_to_line(condition.values[2]) liner.add_to_line(' ') liner.add_to_line(condition.values[3]) i += 1 liner.end_line() def _style_condition(condition, liner, indent): if len(condition.values) == 4 and isinstance(condition.values[0], Not): liner.add_to_line('NOT ') condition.values.pop(0) if types_match(condition, [(Identifier, Number, Str), Operator, (Identifier, Number, Str)]): liner.add_to_line(' '.join('%s' % x for x in condition.values)) elif types_match(condition, [(Identifier, Number, Str), <|code_end|> , predict the next line using imports from the current file: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context including class names, function names, and sometimes code from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
Between,
Using the snippet: <|code_start|> liner.end_line() def _style_insert(insert, liner, indent): liner.add_line('INSERT INTO') liner.add_line(' %s' % insert.table) if insert.cols: liner.add_to_last_line(' (%s)' % ', '.join('%s' % x for x in insert.cols)) if insert.values: liner.add_line('VALUES') for i, values in enumerate(insert.values.values): liner.add_line(' (%s)' % ', '.join('%s' % x for x in values)) if i < len(insert.values.values) - 1: liner.add_to_last_line(',') elif insert.select: style(insert.select, liner=liner, indent=indent) def _style_select(select, liner, indent): liner.add_line(' ' * indent + select.value.upper()) for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) <|code_end|> , determine the next line of code. You have imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (class names, function names, or code) available: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
elif isinstance(value, Case):
Continue the code snippet: <|code_start|> if isinstance(value, Join): liner.add_to_line(' ' * (indent + 1)) liner.add_to_line(value.value.upper()) liner.add_to_line(' ') _style_identifier(from_.values[i + 1], liner, end_line=False) if i + 2 < len(from_.values) and isinstance(from_.values[i + 2], On): liner.add_to_line(' ON') i += 1 elif isinstance(value, Identifier): liner.add_to_line(' ' * (indent + 1)) _style_identifier(value, liner, end_line=False) if i + 1 < len(from_.values) and not isinstance(from_.values[i + 1], Join): liner.add_to_line(',') elif isinstance(value, On): new_line = True for v in value.values: if new_line: liner.add_to_line(' ' * (indent + 2)) if isinstance(v, Link): liner.add_to_line('AND ') new_line = False <|code_end|> . Use current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
elif isinstance(v, Condition):
Continue the code snippet: <|code_start|> def _style_select(select, liner, indent): liner.add_line(' ' * indent + select.value.upper()) for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { <|code_end|> . Use current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
From: _style_from,
Predict the next line for this snippet: <|code_start|> liner.add_to_line(value.value.upper()) liner.add_to_line(' ') _style_identifier(from_.values[i + 1], liner, end_line=False) if i + 2 < len(from_.values) and isinstance(from_.values[i + 2], On): liner.add_to_line(' ON') i += 1 elif isinstance(value, Identifier): liner.add_to_line(' ' * (indent + 1)) _style_identifier(value, liner, end_line=False) if i + 1 < len(from_.values) and not isinstance(from_.values[i + 1], Join): liner.add_to_line(',') elif isinstance(value, On): new_line = True for v in value.values: if new_line: liner.add_to_line(' ' * (indent + 2)) if isinstance(v, Link): liner.add_to_line('AND ') new_line = False elif isinstance(v, Condition): for vv in v.values: <|code_end|> with the help of current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() , which may contain function names, class names, or code. Output only the next line.
if isinstance(vv, Func):
Predict the next line after this snippet: <|code_start|> def _style_select(select, liner, indent): liner.add_line(' ' * indent + select.value.upper()) for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, <|code_end|> using the current file's imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and any relevant context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
GroupBy: _style_group_by,
Using the snippet: <|code_start|>def _style_select(select, liner, indent): liner.add_line(' ' * indent + select.value.upper()) for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, <|code_end|> , determine the next line of code. You have imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (class names, function names, or code) available: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
Having: _style_having,
Predict the next line after this snippet: <|code_start|> if identifier.as_: liner.add_to_line(' AS') if identifier.alias: liner.add_to_line(' ') liner.add_to_line(identifier.alias) if end_line: liner.end_line() def _style_from(from_, liner, indent): liner.add_line(' ' * indent + 'FROM') i = 0 while i < len(from_.values): value = from_.values[i] if isinstance(value, Join): liner.add_to_line(' ' * (indent + 1)) liner.add_to_line(value.value.upper()) liner.add_to_line(' ') _style_identifier(from_.values[i + 1], liner, end_line=False) if i + 2 < len(from_.values) and isinstance(from_.values[i + 2], On): liner.add_to_line(' ON') i += 1 <|code_end|> using the current file's imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and any relevant context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
elif isinstance(value, Identifier):
Predict the next line for this snippet: <|code_start|> liner.add_line(' ' * indent + select.value.upper()) for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, <|code_end|> with the help of current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() , which may contain function names, class names, or code. Output only the next line.
Insert: _style_insert,
Based on the snippet: <|code_start|> if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, Limit: _style_limit, OrderBy: _style_order_by, Select: _style_select, Semicolon: _style_semicolon, Where: _style_where, } for i, statement in enumerate(statements): func = structures[statement.__class__] try: func(statement, liner=liner, indent=indent) except IndexError: <|code_end|> , predict the immediate next line with the help of imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, sometimes code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
raise InvalidSQL()
Predict the next line after this snippet: <|code_start|> liner.add_to_line(' ') liner.add_to_line(condition.values[2]) liner.add_to_line(' ') liner.add_to_line(condition.values[3]) i += 1 liner.end_line() def _style_condition(condition, liner, indent): if len(condition.values) == 4 and isinstance(condition.values[0], Not): liner.add_to_line('NOT ') condition.values.pop(0) if types_match(condition, [(Identifier, Number, Str), Operator, (Identifier, Number, Str)]): liner.add_to_line(' '.join('%s' % x for x in condition.values)) elif types_match(condition, [(Identifier, Number, Str), Between, (Identifier, Number, Str), Link, (Identifier, Number, Str)]): liner.add_to_line('%s BETWEEN %s AND %s' % (condition.values[0], condition.values[2], condition.values[4])) <|code_end|> using the current file's imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and any relevant context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
elif types_match(condition, [(Identifier, Number, Str), Is, Null]):
Continue the code snippet: <|code_start|> self.line = [] def add_to_last_line(self, val): line = self.lines.pop() self.add_to_line(line) self.add_to_line(val) self.end_line() def _style_identifier(identifier, liner, end_line=True): liner.add_to_line(identifier) if identifier.as_: liner.add_to_line(' AS') if identifier.alias: liner.add_to_line(' ') liner.add_to_line(identifier.alias) if end_line: liner.end_line() def _style_from(from_, liner, indent): liner.add_line(' ' * indent + 'FROM') i = 0 while i < len(from_.values): value = from_.values[i] <|code_end|> . Use current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if isinstance(value, Join):
Predict the next line after this snippet: <|code_start|> for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, <|code_end|> using the current file's imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and any relevant context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
Limit: _style_limit,
Given the code snippet: <|code_start|> i = 0 while i < len(from_.values): value = from_.values[i] if isinstance(value, Join): liner.add_to_line(' ' * (indent + 1)) liner.add_to_line(value.value.upper()) liner.add_to_line(' ') _style_identifier(from_.values[i + 1], liner, end_line=False) if i + 2 < len(from_.values) and isinstance(from_.values[i + 2], On): liner.add_to_line(' ON') i += 1 elif isinstance(value, Identifier): liner.add_to_line(' ' * (indent + 1)) _style_identifier(value, liner, end_line=False) if i + 1 < len(from_.values) and not isinstance(from_.values[i + 1], Join): liner.add_to_line(',') elif isinstance(value, On): new_line = True for v in value.values: if new_line: liner.add_to_line(' ' * (indent + 2)) <|code_end|> , generate the next line using the imports in this file: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (functions, classes, or occasionally code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if isinstance(v, Link):
Continue the code snippet: <|code_start|> liner.add_to_line(' ' * (indent + 1) + '%s' % value) if value.sort: sort = value.sort.upper() liner.add_to_line(' %s' % sort) if i + 1 < len(order_by.values): liner.add_to_line(',') liner.end_line() def _style_having(having, liner, indent): liner.add_line(' ' * indent + 'HAVING') i = 0 while i < len(having.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(having.values[i], Link): liner.add_to_line('%s ' % having.values[i].value.upper()) i += 1 condition = having.values[i] if types_match(condition, [Identifier, Operator, Number]): liner.add_to_line(' '.join('%s' % x for x in condition.values)) i += 1 liner.end_line() <|code_end|> . Use current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, or code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if types_match(condition, [Not, Func, Operator, Number]):
Given snippet: <|code_start|> liner.add_to_line(' ') liner.add_to_line(condition.values[2]) liner.add_to_line(' ') liner.add_to_line(condition.values[3]) i += 1 liner.end_line() def _style_condition(condition, liner, indent): if len(condition.values) == 4 and isinstance(condition.values[0], Not): liner.add_to_line('NOT ') condition.values.pop(0) if types_match(condition, [(Identifier, Number, Str), Operator, (Identifier, Number, Str)]): liner.add_to_line(' '.join('%s' % x for x in condition.values)) elif types_match(condition, [(Identifier, Number, Str), Between, (Identifier, Number, Str), Link, (Identifier, Number, Str)]): liner.add_to_line('%s BETWEEN %s AND %s' % (condition.values[0], condition.values[2], condition.values[4])) <|code_end|> , continue by predicting the next line. Consider current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() which might include code, classes, or functions. Output only the next line.
elif types_match(condition, [(Identifier, Number, Str), Is, Null]):
Predict the next line for this snippet: <|code_start|> def _style_order_by(order_by, liner, indent): liner.add_line(' ' * indent + 'ORDER BY') for i, value in enumerate(order_by.values): liner.add_to_line(' ' * (indent + 1) + '%s' % value) if value.sort: sort = value.sort.upper() liner.add_to_line(' %s' % sort) if i + 1 < len(order_by.values): liner.add_to_line(',') liner.end_line() def _style_having(having, liner, indent): liner.add_line(' ' * indent + 'HAVING') i = 0 while i < len(having.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(having.values[i], Link): liner.add_to_line('%s ' % having.values[i].value.upper()) i += 1 condition = having.values[i] <|code_end|> with the help of current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() , which may contain function names, class names, or code. Output only the next line.
if types_match(condition, [Identifier, Operator, Number]):
Given the following code snippet before the placeholder: <|code_start|> def _style_identifier(identifier, liner, end_line=True): liner.add_to_line(identifier) if identifier.as_: liner.add_to_line(' AS') if identifier.alias: liner.add_to_line(' ') liner.add_to_line(identifier.alias) if end_line: liner.end_line() def _style_from(from_, liner, indent): liner.add_line(' ' * indent + 'FROM') i = 0 while i < len(from_.values): value = from_.values[i] if isinstance(value, Join): liner.add_to_line(' ' * (indent + 1)) liner.add_to_line(value.value.upper()) liner.add_to_line(' ') _style_identifier(from_.values[i + 1], liner, end_line=False) <|code_end|> , predict the next line using imports from the current file: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context including class names, function names, and sometimes code from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if i + 2 < len(from_.values) and isinstance(from_.values[i + 2], On):
Next line prediction: <|code_start|> def _style_order_by(order_by, liner, indent): liner.add_line(' ' * indent + 'ORDER BY') for i, value in enumerate(order_by.values): liner.add_to_line(' ' * (indent + 1) + '%s' % value) if value.sort: sort = value.sort.upper() liner.add_to_line(' %s' % sort) if i + 1 < len(order_by.values): liner.add_to_line(',') liner.end_line() def _style_having(having, liner, indent): liner.add_line(' ' * indent + 'HAVING') i = 0 while i < len(having.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(having.values[i], Link): liner.add_to_line('%s ' % having.values[i].value.upper()) i += 1 condition = having.values[i] <|code_end|> . Use current file imports: (from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where)) and context including class names, function names, or small code snippets from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if types_match(condition, [Identifier, Operator, Number]):
Based on the snippet: <|code_start|> for i, value in enumerate(select.values): liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, Limit: _style_limit, <|code_end|> , predict the immediate next line with the help of imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, sometimes code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
OrderBy: _style_order_by,
Based on the snippet: <|code_start|> liner.add_to_line(' ' * (indent + 1)) if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, Limit: _style_limit, OrderBy: _style_order_by, <|code_end|> , predict the immediate next line with the help of imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (classes, functions, sometimes code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
Select: _style_select,
Next line prediction: <|code_start|> if isinstance(value, (Identifier, Str, Number)): _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, Limit: _style_limit, OrderBy: _style_order_by, Select: _style_select, <|code_end|> . Use current file imports: (from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where)) and context including class names, function names, or small code snippets from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
Semicolon: _style_semicolon,
Given the code snippet: <|code_start|> if isinstance(having.values[i], Link): liner.add_to_line('%s ' % having.values[i].value.upper()) i += 1 condition = having.values[i] if types_match(condition, [Identifier, Operator, Number]): liner.add_to_line(' '.join('%s' % x for x in condition.values)) i += 1 liner.end_line() if types_match(condition, [Not, Func, Operator, Number]): liner.add_to_line('NOT') liner.add_to_line(' ') _style_func(condition.values[1], liner, end_line=False) liner.add_to_line(' ') liner.add_to_line(condition.values[2]) liner.add_to_line(' ') liner.add_to_line(condition.values[3]) i += 1 liner.end_line() def _style_condition(condition, liner, indent): if len(condition.values) == 4 and isinstance(condition.values[0], Not): liner.add_to_line('NOT ') condition.values.pop(0) <|code_end|> , generate the next line using the imports in this file: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (functions, classes, or occasionally code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
if types_match(condition, [(Identifier, Number, Str),
Given the code snippet: <|code_start|> elif types_match(condition, [(Identifier, Number, Str), Between, (Identifier, Number, Str), Link, (Identifier, Number, Str)]): liner.add_to_line('%s BETWEEN %s AND %s' % (condition.values[0], condition.values[2], condition.values[4])) elif types_match(condition, [(Identifier, Number, Str), Is, Null]): liner.add_to_line('%s IS NULL' % condition.values[0]) elif types_match(condition, [(Identifier, Number, Str), Is, Not, Null]): liner.add_to_line('%s IS NOT NULL' % condition.values[0]) elif types_match(condition, [(Identifier, Number, Str), Operator, list]): liner.add_to_line('%s IN (' % condition.values[0]) liner.end_line() for j, value in enumerate(condition.values[2]): liner.add_to_line(' ' * (indent + 2)) liner.add_to_line(value) if j + 1 < len(condition.values[2]): liner.add_to_line(',') else: liner.add_to_line(')') liner.end_line() <|code_end|> , generate the next line using the imports in this file: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context (functions, classes, or occasionally code) from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() . Output only the next line.
elif types_match(condition, [Identifier, Operator, SubSelect]):
Here is a snippet: <|code_start|> _style_identifier(value, liner, end_line=False) elif isinstance(value, Case): _style_case(value, liner, indent) elif isinstance(value, Func): _style_func(value, liner, end_line=False) if i + 1 < len(select.values): liner.add_to_line(',') liner.end_line() def _style_semicolon(semicolon, liner, indent): liner.add_to_last_line(semicolon.value) def style(statements, indent=0, keyword_upper=True, liner=None): if not liner: liner = Liner() structures = { From: _style_from, GroupBy: _style_group_by, Having: _style_having, Insert: _style_insert, Limit: _style_limit, OrderBy: _style_order_by, Select: _style_select, Semicolon: _style_semicolon, <|code_end|> . Write the next line using the current file imports: from format_sql.parser import (Between, Case, Condition, Else, From, Func, GroupBy, Having, Identifier, Insert, InvalidSQL, Is, Join, Limit, Link, Not, Null, Number, On, Operator, OrderBy, Select, Semicolon, Str, SubSelect, When, Where) and context from other files: # Path: format_sql/parser.py # class Between(object): # value = attr.ib() # # class Case(object): # value = attr.ib() # when_elses = attr.ib() # # class Condition(object): # values = attr.ib() # # class Else(object): # else_ = attr.ib() # result = attr.ib() # # def __str__(self): # return 'ELSE %s' % self.result # # class From(object): # value = attr.ib() # values = attr.ib() # # class Func(object): # name = attr.ib() # args = attr.ib() # as_ = attr.ib(default=None) # alias = attr.ib(default=None) # # class GroupBy(object): # values = attr.ib() # with_rollup = attr.ib(default=None) # # class Having(object): # value = attr.ib() # values = attr.ib() # # class Identifier(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class Insert(object): # insert = attr.ib() # table = attr.ib() # values = attr.ib(default=[]) # cols = attr.ib(default=[]) # select = attr.ib(default=[]) # # class InvalidSQL(Exception): # pass # # class Is(object): # value = attr.ib() # # class Join(object): # value = attr.ib() # # class Limit(object): # row_count = attr.ib() # offset = attr.ib(default=None) # offset_keyword = attr.ib(default=None) # # class Link(object): # value = attr.ib() # # class Not(object): # value = attr.ib() # # class Null(object): # value = attr.ib() # # class Number(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class On(object): # value = attr.ib() # values = attr.ib(default=[]) # # class Operator(object): # value = attr.ib() # # def __str__(self): # return '%s' % self.value.upper() # # class OrderBy(object): # values = attr.ib() # # class Select(object): # value = attr.ib() # values = attr.ib() # # class Semicolon(object): # value = attr.ib() # # class Str(object): # value = attr.ib() # alias = attr.ib(default=None) # as_ = attr.ib(default=None) # sort = attr.ib(default=None) # # def __str__(self): # return '%s' % self.value # # class SubSelect(object): # values = attr.ib() # # class When(object): # when = attr.ib() # condition = attr.ib() # then = attr.ib() # result = attr.ib() # # def __str__(self): # return 'WHEN %s THEN %s' % (self.condition, self.result) # # class Where(object): # value = attr.ib() # conditions = attr.ib() , which may include functions, classes, or code. Output only the next line.
Where: _style_where,
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ from __future__ import unicode_literals def assert_func_style(statements1, styled2): <|code_end|> with the help of current file imports: from format_sql.styler import Liner, _style_func, style and context from other files: # Path: format_sql/styler.py # class Liner: # # def __init__(self): # self.line = [] # self.lines = [] # # def add_to_line(self, val): # self.line.append('%s' % val) # # def add_line(self, val): # self.add_to_line(val) # self.end_line() # # def add_empty_lines(self, count=1): # self.end_line() # for _ in range(count): # self.lines.append('') # # def end_line(self): # line = ''.join(self.line) # if line: # self.lines.append(line) # self.line = [] # # def add_to_last_line(self, val): # line = self.lines.pop() # self.add_to_line(line) # self.add_to_line(val) # self.end_line() # # def _style_func(func, liner, end_line=True): # liner.add_to_line(func.name.upper()) # liner.add_to_line('(') # # for i, arg in enumerate(func.args): # if isinstance(arg, (Identifier, Str, Number)): # liner.add_to_line(arg) # elif isinstance(arg, Func): # _style_func(arg, liner, end_line=False) # # if i + 1 < len(func.args): # liner.add_to_line(', ') # # liner.add_to_line(')') # if func.as_ and func.alias: # liner.add_to_line(' AS ') # liner.add_to_line(func.alias) # # if end_line: # liner.end_line() # # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines , which may contain function names, class names, or code. Output only the next line.
liner = Liner()
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ from __future__ import unicode_literals def assert_func_style(statements1, styled2): liner = Liner() <|code_end|> , generate the next line using the imports in this file: from format_sql.styler import Liner, _style_func, style and context (functions, classes, or occasionally code) from other files: # Path: format_sql/styler.py # class Liner: # # def __init__(self): # self.line = [] # self.lines = [] # # def add_to_line(self, val): # self.line.append('%s' % val) # # def add_line(self, val): # self.add_to_line(val) # self.end_line() # # def add_empty_lines(self, count=1): # self.end_line() # for _ in range(count): # self.lines.append('') # # def end_line(self): # line = ''.join(self.line) # if line: # self.lines.append(line) # self.line = [] # # def add_to_last_line(self, val): # line = self.lines.pop() # self.add_to_line(line) # self.add_to_line(val) # self.end_line() # # def _style_func(func, liner, end_line=True): # liner.add_to_line(func.name.upper()) # liner.add_to_line('(') # # for i, arg in enumerate(func.args): # if isinstance(arg, (Identifier, Str, Number)): # liner.add_to_line(arg) # elif isinstance(arg, Func): # _style_func(arg, liner, end_line=False) # # if i + 1 < len(func.args): # liner.add_to_line(', ') # # liner.add_to_line(')') # if func.as_ and func.alias: # liner.add_to_line(' AS ') # liner.add_to_line(func.alias) # # if end_line: # liner.end_line() # # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines . Output only the next line.
_style_func(statements1[0], liner)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ from __future__ import unicode_literals def assert_func_style(statements1, styled2): liner = Liner() _style_func(statements1[0], liner) assert styled2 == liner.lines def assert_style(statements1, styled2): <|code_end|> , predict the next line using imports from the current file: from format_sql.styler import Liner, _style_func, style and context including class names, function names, and sometimes code from other files: # Path: format_sql/styler.py # class Liner: # # def __init__(self): # self.line = [] # self.lines = [] # # def add_to_line(self, val): # self.line.append('%s' % val) # # def add_line(self, val): # self.add_to_line(val) # self.end_line() # # def add_empty_lines(self, count=1): # self.end_line() # for _ in range(count): # self.lines.append('') # # def end_line(self): # line = ''.join(self.line) # if line: # self.lines.append(line) # self.line = [] # # def add_to_last_line(self, val): # line = self.lines.pop() # self.add_to_line(line) # self.add_to_line(val) # self.end_line() # # def _style_func(func, liner, end_line=True): # liner.add_to_line(func.name.upper()) # liner.add_to_line('(') # # for i, arg in enumerate(func.args): # if isinstance(arg, (Identifier, Str, Number)): # liner.add_to_line(arg) # elif isinstance(arg, Func): # _style_func(arg, liner, end_line=False) # # if i + 1 < len(func.args): # liner.add_to_line(', ') # # liner.add_to_line(')') # if func.as_ and func.alias: # liner.add_to_line(' AS ') # liner.add_to_line(func.alias) # # if end_line: # liner.end_line() # # def style(statements, indent=0, keyword_upper=True, liner=None): # if not liner: # liner = Liner() # # structures = { # From: _style_from, # GroupBy: _style_group_by, # Having: _style_having, # Insert: _style_insert, # Limit: _style_limit, # OrderBy: _style_order_by, # Select: _style_select, # Semicolon: _style_semicolon, # Where: _style_where, # } # # for i, statement in enumerate(statements): # func = structures[statement.__class__] # try: # func(statement, liner=liner, indent=indent) # except IndexError: # raise InvalidSQL() # # if isinstance(statement, Semicolon) and len(statements) > i + 1: # # statements holds multiple separate statements # liner.add_empty_lines(count=2) # # liner.end_line() # return liner.lines . Output only the next line.
assert style(statements1) == styled2
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def test_(): <|code_end|> . Use current file imports: (import pytest from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql) and context including class names, function names, or small code snippets from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled . Output only the next line.
with pytest.raises(InvalidSQL):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ def test_(): with pytest.raises(InvalidSQL): <|code_end|> , predict the next line using imports from the current file: import pytest from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql and context including class names, function names, and sometimes code from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled . Output only the next line.
format_sql("Select x T K")
Given the code snippet: <|code_start|>def get_statements(lines): regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' queries = re.findall(regex, lines, re.DOTALL) for indent, query_quote_start, query in queries: indent = indent.strip('\n') indent += ' ' * 4 old_query = query query = ' '.join(query.split()) first = query.split() if not first: continue first = first[0].lower() if not first in ['select', 'insert']: continue yield old_query, query, indent def handle_py_file(filename, debug=False): with open(filename) as f: lines = f.read() for old_query, query, indent in get_statements(lines): if debug: print_non_data('Found query: %s' % query) try: fmt = format_sql(query, debug) <|code_end|> , generate the next line using the imports in this file: import os import re import sys from argparse import ArgumentParser from glob import glob from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql from format_sql.util import print_data, print_non_data and context (functions, classes, or occasionally code) from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled # # Path: format_sql/util.py # def print_data(msg): # print(msg) # # def print_non_data(msg): # print(msg, file=sys.stderr) . Output only the next line.
except InvalidSQL as e:
Here is a snippet: <|code_start|> def get_statements(lines): regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' queries = re.findall(regex, lines, re.DOTALL) for indent, query_quote_start, query in queries: indent = indent.strip('\n') indent += ' ' * 4 old_query = query query = ' '.join(query.split()) first = query.split() if not first: continue first = first[0].lower() if not first in ['select', 'insert']: continue yield old_query, query, indent def handle_py_file(filename, debug=False): with open(filename) as f: lines = f.read() for old_query, query, indent in get_statements(lines): if debug: print_non_data('Found query: %s' % query) try: <|code_end|> . Write the next line using the current file imports: import os import re import sys from argparse import ArgumentParser from glob import glob from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql from format_sql.util import print_data, print_non_data and context from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled # # Path: format_sql/util.py # def print_data(msg): # print(msg) # # def print_non_data(msg): # print(msg, file=sys.stderr) , which may include functions, classes, or code. Output only the next line.
fmt = format_sql(query, debug)
Next line prediction: <|code_start|> fmt = format_sql(query, debug) except InvalidSQL as e: print_non_data(e) continue fs = [] for line in fmt: s = '%s%s' % (indent, line) fs.append(s.rstrip()) lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) return lines def handle_sql_file(filename, debug=False): with open(filename) as f: lines = f.read() try: sql = format_sql(lines, debug) except InvalidSQL as e: print_non_data(e) return lines = '\n'.join(sql) return lines def _write_back(filename, lines, dry_run=False): if dry_run: <|code_end|> . Use current file imports: (import os import re import sys from argparse import ArgumentParser from glob import glob from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql from format_sql.util import print_data, print_non_data) and context including class names, function names, or small code snippets from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled # # Path: format_sql/util.py # def print_data(msg): # print(msg) # # def print_non_data(msg): # print(msg, file=sys.stderr) . Output only the next line.
print_data(lines)
Given the following code snippet before the placeholder: <|code_start|> return args def _get_filenames(paths, recursive): filenames = set() for path in paths: path = os.path.abspath(path) if os.path.isfile(path): filenames.add(path) elif os.path.isdir(path): if recursive: for dirpath, dirnames, fnames in os.walk(path): filenames.update(os.path.join(dirpath, fn) for fn in fnames) else: if not path.endswith('/'): path += '/' filenames.update(glob('%s*' % path)) return filenames def main(args=sys.argv[1:]): args = _get_args(args) filenames = _get_filenames(args.paths, args.recursive) if args.types: filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) for filename in filenames: <|code_end|> , predict the next line using imports from the current file: import os import re import sys from argparse import ArgumentParser from glob import glob from format_sql.parser import InvalidSQL from format_sql.shortcuts import format_sql from format_sql.util import print_data, print_non_data and context including class names, function names, and sometimes code from other files: # Path: format_sql/parser.py # class InvalidSQL(Exception): # pass # # Path: format_sql/shortcuts.py # def format_sql(s, debug=False): # tokens = list(tokenize(s)) # if debug: # print_non_data('Tokens: %s' % tokens) # parsed = list(parse(tokens)) # if debug: # print_non_data('Statements: %s' % parsed) # styled = style(parsed) # if debug: # print_non_data('Output: %s' % styled) # return styled # # Path: format_sql/util.py # def print_data(msg): # print(msg) # # def print_non_data(msg): # print(msg, file=sys.stderr) . Output only the next line.
print_non_data(filename)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, Friedrich Paetzke (paetzke@fastmail.fm) All rights reserved. """ try: except ImportError: @pytest.mark.parametrize('args, expected_paths, expected_types', [ ('file1 file2 --types sql --types py', ['file1', 'file2'], ['sql', 'py']), ('file1 --types py --types sql', ['file1'], ['py', 'sql']), ('file1 file2 --types sql', ['file1', 'file2'], ['sql']), ('file1 file2', ['file1', 'file2'], []), ('--types sql file2 file1', ['file2', 'file1'], ['sql']), ('file1.el', ['file1.el'], []), ('file1.el --types el', ['file1.el'], ['el']), ]) def test_get_args(args, expected_paths, expected_types): <|code_end|> , predict the immediate next line with the help of imports: import pytest from format_sql.main import (_get_args, get_statements, handle_py_file, handle_sql_file, main) from mock import call, patch from itertools import zip_longest from itertools import izip_longest as zip_longest and context (classes, functions, sometimes code) from other files: # Path: format_sql/main.py # def _get_args(call_args): # parser = ArgumentParser('format-sql') # # parser.add_argument('--types', dest='types', type=str, # action='append', # help='Only process these given file types.') # parser.add_argument('paths', type=str, nargs='+') # parser.add_argument('-r', '--recursive', dest='recursive', # action='store_true', default=False, # help='Process files found in subdirectories.') # parser.add_argument('--no-semicolon', action='store_true', default=False, # help='Try to detect SQL queries with no trailing semicolon.') # parser.add_argument('--version', action='version', # version='format-sql 0.12.0') # parser.add_argument('--debug', dest='debug', action='store_true', default=False, # help='Print available debug information.') # parser.add_argument('--dry-run', dest='dry_run', action='store_true', default=False, # help='Print the altered output and do not change the file.') # # args, _unused_unknown_args = parser.parse_known_args(call_args) # if not args.types: # args.types = [] # # return args # # def get_statements(lines): # regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' # queries = re.findall(regex, lines, re.DOTALL) # for indent, query_quote_start, query in queries: # indent = indent.strip('\n') # indent += ' ' * 4 # old_query = query # query = ' '.join(query.split()) # # first = query.split() # if not first: # continue # # first = first[0].lower() # if not first in ['select', 'insert']: # continue # # yield old_query, query, indent # # def handle_py_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # for old_query, query, indent in get_statements(lines): # if debug: # print_non_data('Found query: %s' % query) # # try: # fmt = format_sql(query, debug) # except InvalidSQL as e: # print_non_data(e) # continue # # fs = [] # for line in fmt: # s = '%s%s' % (indent, line) # fs.append(s.rstrip()) # # lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) # return lines # # def handle_sql_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # try: # sql = format_sql(lines, debug) # except InvalidSQL as e: # print_non_data(e) # return # # lines = '\n'.join(sql) # return lines # # def main(args=sys.argv[1:]): # args = _get_args(args) # filenames = _get_filenames(args.paths, args.recursive) # # if args.types: # filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) # # for filename in filenames: # print_non_data(filename) # # if filename.lower().endswith('.py'): # lines = handle_py_file(filename, args.debug) # else: # lines = handle_sql_file(filename, args.debug) # # _write_back(filename, lines, args.dry_run) . Output only the next line.
args = _get_args(args.split())
Given snippet: <|code_start|>def test_multiple_statements_per_sql_file(test_data, filename, expected_filename): test_filename = test_data.get_path(filename) expected_filename = test_data.get_path(expected_filename) result = handle_sql_file(test_filename) with open(expected_filename) as f: expected_data = f.read() assert result == expected_data def test_multiple_statements_in_python_string(test_data): test_filename = test_data.get_path('test_04/before.py') expected_filename = test_data.get_path('test_04/after.py') result = handle_py_file(test_filename) with open(expected_filename) as f: expected_data = f.read() assert result == expected_data @pytest.mark.parametrize(('input_', 'expected_output'), [ ('s = """ select x """', ' select x '), ('s = """ select x where t = "1" """', ' select x where t = "1" '), ("s = ''' select x where t = '1' '''", " select x where t = '1' "), ]) def test_query_recognition_in_python_string(input_, expected_output): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from format_sql.main import (_get_args, get_statements, handle_py_file, handle_sql_file, main) from mock import call, patch from itertools import zip_longest from itertools import izip_longest as zip_longest and context: # Path: format_sql/main.py # def _get_args(call_args): # parser = ArgumentParser('format-sql') # # parser.add_argument('--types', dest='types', type=str, # action='append', # help='Only process these given file types.') # parser.add_argument('paths', type=str, nargs='+') # parser.add_argument('-r', '--recursive', dest='recursive', # action='store_true', default=False, # help='Process files found in subdirectories.') # parser.add_argument('--no-semicolon', action='store_true', default=False, # help='Try to detect SQL queries with no trailing semicolon.') # parser.add_argument('--version', action='version', # version='format-sql 0.12.0') # parser.add_argument('--debug', dest='debug', action='store_true', default=False, # help='Print available debug information.') # parser.add_argument('--dry-run', dest='dry_run', action='store_true', default=False, # help='Print the altered output and do not change the file.') # # args, _unused_unknown_args = parser.parse_known_args(call_args) # if not args.types: # args.types = [] # # return args # # def get_statements(lines): # regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' # queries = re.findall(regex, lines, re.DOTALL) # for indent, query_quote_start, query in queries: # indent = indent.strip('\n') # indent += ' ' * 4 # old_query = query # query = ' '.join(query.split()) # # first = query.split() # if not first: # continue # # first = first[0].lower() # if not first in ['select', 'insert']: # continue # # yield old_query, query, indent # # def handle_py_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # for old_query, query, indent in get_statements(lines): # if debug: # print_non_data('Found query: %s' % query) # # try: # fmt = format_sql(query, debug) # except InvalidSQL as e: # print_non_data(e) # continue # # fs = [] # for line in fmt: # s = '%s%s' % (indent, line) # fs.append(s.rstrip()) # # lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) # return lines # # def handle_sql_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # try: # sql = format_sql(lines, debug) # except InvalidSQL as e: # print_non_data(e) # return # # lines = '\n'.join(sql) # return lines # # def main(args=sys.argv[1:]): # args = _get_args(args) # filenames = _get_filenames(args.paths, args.recursive) # # if args.types: # filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) # # for filename in filenames: # print_non_data(filename) # # if filename.lower().endswith('.py'): # lines = handle_py_file(filename, args.debug) # else: # lines = handle_sql_file(filename, args.debug) # # _write_back(filename, lines, args.dry_run) which might include code, classes, or functions. Output only the next line.
old_query, query, indent = next(get_statements(input_))
Continue the code snippet: <|code_start|> assert mocked_write_back.call_count == 2 expected_paths = ['three.py', 'sub_dir/five.py'] for path, expected in zip_longest(arguments, sorted(expected_paths)): assert path.endswith('format-sql/tests/data/test_00/%s' % expected) @pytest.mark.parametrize(('filename', 'expected_sql'), [ ('test_01/test_00.sql', 'SELECT\n x\nFROM\n k'), ('test_01/test_01.sql', 'SELECT\n x\nFROM\n k;'), ]) def test_sql_file_formatting(test_data, filename, expected_sql): test_filename = test_data.get_path(filename) result = handle_sql_file(test_filename) assert result == expected_sql @pytest.mark.parametrize(('filename', 'expected_filename'), [ ('test_02/test_00.py', 'test_02/test_00_expected.py'), ('test_02/test_01.py', 'test_02/test_01_expected.py'), ('test_02/test_02.py', 'test_02/test_02_expected.py'), ('test_02/test_03.py', 'test_02/test_03_expected.py'), ('test_02/test_04.py', 'test_02/test_04_expected.py'), ]) def test_py_file_formatting(test_data, filename, expected_filename): test_filename = test_data.get_path(filename) expected_filename = test_data.get_path(expected_filename) <|code_end|> . Use current file imports: import pytest from format_sql.main import (_get_args, get_statements, handle_py_file, handle_sql_file, main) from mock import call, patch from itertools import zip_longest from itertools import izip_longest as zip_longest and context (classes, functions, or code) from other files: # Path: format_sql/main.py # def _get_args(call_args): # parser = ArgumentParser('format-sql') # # parser.add_argument('--types', dest='types', type=str, # action='append', # help='Only process these given file types.') # parser.add_argument('paths', type=str, nargs='+') # parser.add_argument('-r', '--recursive', dest='recursive', # action='store_true', default=False, # help='Process files found in subdirectories.') # parser.add_argument('--no-semicolon', action='store_true', default=False, # help='Try to detect SQL queries with no trailing semicolon.') # parser.add_argument('--version', action='version', # version='format-sql 0.12.0') # parser.add_argument('--debug', dest='debug', action='store_true', default=False, # help='Print available debug information.') # parser.add_argument('--dry-run', dest='dry_run', action='store_true', default=False, # help='Print the altered output and do not change the file.') # # args, _unused_unknown_args = parser.parse_known_args(call_args) # if not args.types: # args.types = [] # # return args # # def get_statements(lines): # regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' # queries = re.findall(regex, lines, re.DOTALL) # for indent, query_quote_start, query in queries: # indent = indent.strip('\n') # indent += ' ' * 4 # old_query = query # query = ' '.join(query.split()) # # first = query.split() # if not first: # continue # # first = first[0].lower() # if not first in ['select', 'insert']: # continue # # yield old_query, query, indent # # def handle_py_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # for old_query, query, indent in get_statements(lines): # if debug: # print_non_data('Found query: %s' % query) # # try: # fmt = format_sql(query, debug) # except InvalidSQL as e: # print_non_data(e) # continue # # fs = [] # for line in fmt: # s = '%s%s' % (indent, line) # fs.append(s.rstrip()) # # lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) # return lines # # def handle_sql_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # try: # sql = format_sql(lines, debug) # except InvalidSQL as e: # print_non_data(e) # return # # lines = '\n'.join(sql) # return lines # # def main(args=sys.argv[1:]): # args = _get_args(args) # filenames = _get_filenames(args.paths, args.recursive) # # if args.types: # filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) # # for filename in filenames: # print_non_data(filename) # # if filename.lower().endswith('.py'): # lines = handle_py_file(filename, args.debug) # else: # lines = handle_sql_file(filename, args.debug) # # _write_back(filename, lines, args.dry_run) . Output only the next line.
result = handle_py_file(test_filename)
Continue the code snippet: <|code_start|> def test_find_py_in_directory(test_data): args = '%s -r --types py' % test_data.get_path('test_00') args = args.split() with patch('format_sql.main.handle_py_file') as mocked_handle_py_file, \ patch('format_sql.main._write_back') as mocked_write_back: main(args) assert mocked_handle_py_file.call_count == 2 arguments = sorted([ mocked_handle_py_file.call_args_list[0][0][0], mocked_handle_py_file.call_args_list[1][0][0], ]) assert mocked_write_back.call_count == 2 expected_paths = ['three.py', 'sub_dir/five.py'] for path, expected in zip_longest(arguments, sorted(expected_paths)): assert path.endswith('format-sql/tests/data/test_00/%s' % expected) @pytest.mark.parametrize(('filename', 'expected_sql'), [ ('test_01/test_00.sql', 'SELECT\n x\nFROM\n k'), ('test_01/test_01.sql', 'SELECT\n x\nFROM\n k;'), ]) def test_sql_file_formatting(test_data, filename, expected_sql): test_filename = test_data.get_path(filename) <|code_end|> . Use current file imports: import pytest from format_sql.main import (_get_args, get_statements, handle_py_file, handle_sql_file, main) from mock import call, patch from itertools import zip_longest from itertools import izip_longest as zip_longest and context (classes, functions, or code) from other files: # Path: format_sql/main.py # def _get_args(call_args): # parser = ArgumentParser('format-sql') # # parser.add_argument('--types', dest='types', type=str, # action='append', # help='Only process these given file types.') # parser.add_argument('paths', type=str, nargs='+') # parser.add_argument('-r', '--recursive', dest='recursive', # action='store_true', default=False, # help='Process files found in subdirectories.') # parser.add_argument('--no-semicolon', action='store_true', default=False, # help='Try to detect SQL queries with no trailing semicolon.') # parser.add_argument('--version', action='version', # version='format-sql 0.12.0') # parser.add_argument('--debug', dest='debug', action='store_true', default=False, # help='Print available debug information.') # parser.add_argument('--dry-run', dest='dry_run', action='store_true', default=False, # help='Print the altered output and do not change the file.') # # args, _unused_unknown_args = parser.parse_known_args(call_args) # if not args.types: # args.types = [] # # return args # # def get_statements(lines): # regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' # queries = re.findall(regex, lines, re.DOTALL) # for indent, query_quote_start, query in queries: # indent = indent.strip('\n') # indent += ' ' * 4 # old_query = query # query = ' '.join(query.split()) # # first = query.split() # if not first: # continue # # first = first[0].lower() # if not first in ['select', 'insert']: # continue # # yield old_query, query, indent # # def handle_py_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # for old_query, query, indent in get_statements(lines): # if debug: # print_non_data('Found query: %s' % query) # # try: # fmt = format_sql(query, debug) # except InvalidSQL as e: # print_non_data(e) # continue # # fs = [] # for line in fmt: # s = '%s%s' % (indent, line) # fs.append(s.rstrip()) # # lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) # return lines # # def handle_sql_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # try: # sql = format_sql(lines, debug) # except InvalidSQL as e: # print_non_data(e) # return # # lines = '\n'.join(sql) # return lines # # def main(args=sys.argv[1:]): # args = _get_args(args) # filenames = _get_filenames(args.paths, args.recursive) # # if args.types: # filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) # # for filename in filenames: # print_non_data(filename) # # if filename.lower().endswith('.py'): # lines = handle_py_file(filename, args.debug) # else: # lines = handle_sql_file(filename, args.debug) # # _write_back(filename, lines, args.dry_run) . Output only the next line.
result = handle_sql_file(test_filename)
Here is a snippet: <|code_start|> try: except ImportError: @pytest.mark.parametrize('args, expected_paths, expected_types', [ ('file1 file2 --types sql --types py', ['file1', 'file2'], ['sql', 'py']), ('file1 --types py --types sql', ['file1'], ['py', 'sql']), ('file1 file2 --types sql', ['file1', 'file2'], ['sql']), ('file1 file2', ['file1', 'file2'], []), ('--types sql file2 file1', ['file2', 'file1'], ['sql']), ('file1.el', ['file1.el'], []), ('file1.el --types el', ['file1.el'], ['el']), ]) def test_get_args(args, expected_paths, expected_types): args = _get_args(args.split()) assert args.paths == expected_paths assert args.types == expected_types assert not args.recursive assert not args.dry_run def test_find_sql_in_directory(test_data): args = '%s -r --types sql' % test_data.get_path('test_00') args = args.split() with patch('format_sql.main.handle_sql_file') as mocked_handle_sql_file, \ patch('format_sql.main._write_back') as mocked_write_back: <|code_end|> . Write the next line using the current file imports: import pytest from format_sql.main import (_get_args, get_statements, handle_py_file, handle_sql_file, main) from mock import call, patch from itertools import zip_longest from itertools import izip_longest as zip_longest and context from other files: # Path: format_sql/main.py # def _get_args(call_args): # parser = ArgumentParser('format-sql') # # parser.add_argument('--types', dest='types', type=str, # action='append', # help='Only process these given file types.') # parser.add_argument('paths', type=str, nargs='+') # parser.add_argument('-r', '--recursive', dest='recursive', # action='store_true', default=False, # help='Process files found in subdirectories.') # parser.add_argument('--no-semicolon', action='store_true', default=False, # help='Try to detect SQL queries with no trailing semicolon.') # parser.add_argument('--version', action='version', # version='format-sql 0.12.0') # parser.add_argument('--debug', dest='debug', action='store_true', default=False, # help='Print available debug information.') # parser.add_argument('--dry-run', dest='dry_run', action='store_true', default=False, # help='Print the altered output and do not change the file.') # # args, _unused_unknown_args = parser.parse_known_args(call_args) # if not args.types: # args.types = [] # # return args # # def get_statements(lines): # regex = r'(\s*)[_\w\d\.]*\s*=*\s*[_\w\d\.]*\s*\(*("""|\'\'\')(\s*.*?;*\s*)\2' # queries = re.findall(regex, lines, re.DOTALL) # for indent, query_quote_start, query in queries: # indent = indent.strip('\n') # indent += ' ' * 4 # old_query = query # query = ' '.join(query.split()) # # first = query.split() # if not first: # continue # # first = first[0].lower() # if not first in ['select', 'insert']: # continue # # yield old_query, query, indent # # def handle_py_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # for old_query, query, indent in get_statements(lines): # if debug: # print_non_data('Found query: %s' % query) # # try: # fmt = format_sql(query, debug) # except InvalidSQL as e: # print_non_data(e) # continue # # fs = [] # for line in fmt: # s = '%s%s' % (indent, line) # fs.append(s.rstrip()) # # lines = lines.replace(old_query, '\n%s ' % '\n'.join(fs)) # return lines # # def handle_sql_file(filename, debug=False): # with open(filename) as f: # lines = f.read() # # try: # sql = format_sql(lines, debug) # except InvalidSQL as e: # print_non_data(e) # return # # lines = '\n'.join(sql) # return lines # # def main(args=sys.argv[1:]): # args = _get_args(args) # filenames = _get_filenames(args.paths, args.recursive) # # if args.types: # filenames = filter(lambda fn: fn.endswith(tuple(args.types)), filenames) # # for filename in filenames: # print_non_data(filename) # # if filename.lower().endswith('.py'): # lines = handle_py_file(filename, args.debug) # else: # lines = handle_sql_file(filename, args.debug) # # _write_back(filename, lines, args.dry_run) , which may include functions, classes, or code. Output only the next line.
main(args)
Here is a snippet: <|code_start|> "gamma": ("alpha",), "gaussian": ("sigma",), "negativebinomial": ("alpha",), "t": ("sigma", "nu"), "vonmises": ("kappa",), "wald": ("lam",), } def _extract_family_prior(family, priors): """Extract priors for a given family If a key in the priors dictionary matches the name of a nuisance parameter of the response distribution for the given family, this function extracts and returns the prior for that nuisance parameter. The result of this function can be safely used to update the ``Prior`` of the response term. Parameters ---------- family: str or ``bambi.families.Family`` The family for which we want to extract priors. priors: dict A dictionary where keys represent parameter/term names and values represent prior distributions. """ if isinstance(family, str) and family in FAMILY_PARAMS: names = FAMILY_PARAMS[family] priors = {name: priors.pop(name) for name in names if priors.get(name) is not None} if priors: return priors <|code_end|> . Write the next line using the current file imports: from .family import Family and context from other files: # Path: bambi/families/family.py # class Family: # """A specification of model family. # # Parameters # ---------- # name : str # The name of the family. It can be any string. # likelihood: Likelihood # A ``bambi.families.Likelihood`` instace specifying the model likelihood function. # link : str or Link # The name of the link function or a ``bambi.families.Link`` instance. The link function # transforms the linear model prediction to the mean parameter of the likelihood funtion. # # Examples # -------- # # >>> import bambi as bmb # # Replicate the Gaussian built-in family. # # >>> sigma_prior = bmb.Prior("HalfNormal", sigma=1) # >>> likelihood = bmb.Likelihood("Gaussian", parent="mu", sigma=sigma_prior) # >>> family = bmb.Family("gaussian", likelihood, "identity") # >>> # Then you can do # >>> # bmb.Model("y ~ x", data, family=family) # # Replicate the Bernoulli built-in family. # # >>> likelihood = bmb.Likelihood("Bernoulli", parent="p") # >>> family = bmb.Family("bernoulli", likelihood, "logit") # """ # # SUPPORTED_LINKS = [ # "cloglog", # "identity", # "inverse_squared", # "inverse", # "log", # "logit", # "probit", # "softmax", # "tan_2", # ] # # def __init__(self, name, likelihood, link): # self.name = name # self.likelihood = likelihood # self.link = link # self.smfamily = STATSMODELS_FAMILIES.get(name, None) # self.aliases = {} # # @property # def link(self): # return self._link # # @link.setter # def link(self, x): # if isinstance(x, str): # self.check_string_link(x) # self._link = Link(x) # self.smlink = STATSMODELS_LINKS.get(x, None) # elif isinstance(x, Link): # self.link = x # else: # raise ValueError(".link must be set to a string or a Link instance.") # # def check_string_link(self, link): # if not link in self.SUPPORTED_LINKS: # raise ValueError(f"Link '{link}' cannot be used with family '{self.name}'") # # def set_alias(self, name, alias): # """Set alias for an auxiliary variable of the family # # Parameters # ---------- # name: str # The name of the variable # alias: str # The new name for the variable # """ # self.aliases.update({name: alias}) # # def __str__(self): # msg_list = [f"Response distribution: {self.likelihood.name}", f"Link: {self.link.name}"] # if self.likelihood.priors: # priors_msg = "\n ".join([f"{k} ~ {v}" for k, v in self.likelihood.priors.items()]) # msg_list += [f"Priors:\n {priors_msg}"] # msg = "\n".join(msg_list) # return msg # # def __repr__(self): # return self.__str__() , which may include functions, classes, or code. Output only the next line.
elif isinstance(family, Family):
Given the following code snippet before the placeholder: <|code_start|> def test_listify(): assert listify(None) == [] assert listify([1, 2, 3]) == [1, 2, 3] assert listify("giraffe") == ["giraffe"] def test_probit(): <|code_end|> , predict the next line using imports from the current file: import numpy as np from bambi.utils import listify from bambi.backend.pymc import probit, cloglog and context including class names, function names, and sometimes code from other files: # Path: bambi/utils.py # def listify(obj): # """Wrap all non-list or tuple objects in a list. # # Provides a simple way to accept flexible arguments. # """ # if obj is None: # return [] # else: # return obj if isinstance(obj, (list, tuple, type(None))) else [obj] # # Path: bambi/backend/pymc.py # class PyMC3Model: # INVLINKS = { # "cloglog": cloglog, # "identity": identity, # "inverse_squared": inverse_squared, # "inverse": tt.inv, # "log": tt.exp, # "logit": logit, # "probit": probit, # "tan_2": arctan_2, # "softmax": tt.nnet.softmax, # } # X = self._design_matrix_without_intercept # def __init__(self): # def build(self, spec): # def run( # self, # draws=1000, # tune=1000, # discard_tuned_samples=True, # omit_offsets=True, # include_mean=False, # method="mcmc", # init="auto", # n_init=50000, # chains=None, # cores=None, # random_seed=None, # **kwargs, # ): # def _build_intercept(self, spec): # def _build_common_terms(self, spec): # def _build_group_specific_terms(self, spec): # def _build_response(self, spec): # def _build_potentials(self, spec): # def _run_mcmc( # self, # draws=1000, # tune=1000, # discard_tuned_samples=True, # omit_offsets=True, # include_mean=False, # init="auto", # n_init=50000, # chains=None, # cores=None, # random_seed=None, # **kwargs, # ): # def _clean_mcmc_results(self, idata, omit_offsets, include_mean): # def _run_advi(self, **kwargs): # def _run_laplace(self): # def add_lkj(backend, terms, eta=1): . Output only the next line.
x = probit(np.random.normal(scale=10000, size=100)).eval()
Given the code snippet: <|code_start|> def test_listify(): assert listify(None) == [] assert listify([1, 2, 3]) == [1, 2, 3] assert listify("giraffe") == ["giraffe"] def test_probit(): x = probit(np.random.normal(scale=10000, size=100)).eval() assert (x > 0).all() and (x < 1).all() def test_cloglog(): <|code_end|> , generate the next line using the imports in this file: import numpy as np from bambi.utils import listify from bambi.backend.pymc import probit, cloglog and context (functions, classes, or occasionally code) from other files: # Path: bambi/utils.py # def listify(obj): # """Wrap all non-list or tuple objects in a list. # # Provides a simple way to accept flexible arguments. # """ # if obj is None: # return [] # else: # return obj if isinstance(obj, (list, tuple, type(None))) else [obj] # # Path: bambi/backend/pymc.py # class PyMC3Model: # INVLINKS = { # "cloglog": cloglog, # "identity": identity, # "inverse_squared": inverse_squared, # "inverse": tt.inv, # "log": tt.exp, # "logit": logit, # "probit": probit, # "tan_2": arctan_2, # "softmax": tt.nnet.softmax, # } # X = self._design_matrix_without_intercept # def __init__(self): # def build(self, spec): # def run( # self, # draws=1000, # tune=1000, # discard_tuned_samples=True, # omit_offsets=True, # include_mean=False, # method="mcmc", # init="auto", # n_init=50000, # chains=None, # cores=None, # random_seed=None, # **kwargs, # ): # def _build_intercept(self, spec): # def _build_common_terms(self, spec): # def _build_group_specific_terms(self, spec): # def _build_response(self, spec): # def _build_potentials(self, spec): # def _run_mcmc( # self, # draws=1000, # tune=1000, # discard_tuned_samples=True, # omit_offsets=True, # include_mean=False, # init="auto", # n_init=50000, # chains=None, # cores=None, # random_seed=None, # **kwargs, # ): # def _clean_mcmc_results(self, idata, omit_offsets, include_mean): # def _run_advi(self, **kwargs): # def _run_laplace(self): # def add_lkj(backend, terms, eta=1): . Output only the next line.
x = cloglog(np.random.normal(scale=10000, size=100)).eval()
Predict the next line for this snippet: <|code_start|> full_model = self.mle # Get log-likelihood values from beta=0 to beta=MLE beta_mle = full_model.params[name].item() beta_seq = np.linspace(0, beta_mle, points) log_likelihood = get_llh(self.model, exog, full_model, name, values, beta_seq) coef_a, coef_b = get_llh_coeffs(log_likelihood, beta_mle, beta_seq) p, q = shape_params(sigma_corr) # Evaluate the derivatives of beta = f(correlation). # dict 'point' gives points about which to Taylor expand. # We want to expand about the mean (generally 0), but some of the derivatives # do not exist at 0. Evaluating at a point very close to 0 (e.g., .001) # generally gives good results, but the higher order the expansion, the # further from 0 we need to evaluate the derivatives, or they blow up. point = dict(zip(range(1, 14), 2 ** np.linspace(-1, 5, 13) / 100)) vals = dict(a=coef_a, b=coef_b, n=len(self.model.response.data), r=point[self.taylor]) deriv = [eval(x, globals(), vals) for x in self.deriv] # pylint: disable=eval-used terms = [ compute_sigma(deriv, p, q, i, j) for i in range(1, self.taylor + 1) for j in range(1, self.taylor + 1) ] return np.array(terms).sum() ** 0.5 def scale_response(self): # Add cases for other families priors = self.model.family.likelihood.priors <|code_end|> with the help of current file imports: import sys import numpy as np import pandas as pd from os.path import dirname, join from scipy.special import hyp2f1 from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.tools.sm_exceptions import PerfectSeparationError from bambi.families.univariate import Gaussian, StudentT from .prior import Prior and context from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() , which may contain function names, class names, or code. Output only the next line.
if isinstance(self.model.family, (Gaussian, StudentT)):
Continue the code snippet: <|code_start|> full_model = self.mle # Get log-likelihood values from beta=0 to beta=MLE beta_mle = full_model.params[name].item() beta_seq = np.linspace(0, beta_mle, points) log_likelihood = get_llh(self.model, exog, full_model, name, values, beta_seq) coef_a, coef_b = get_llh_coeffs(log_likelihood, beta_mle, beta_seq) p, q = shape_params(sigma_corr) # Evaluate the derivatives of beta = f(correlation). # dict 'point' gives points about which to Taylor expand. # We want to expand about the mean (generally 0), but some of the derivatives # do not exist at 0. Evaluating at a point very close to 0 (e.g., .001) # generally gives good results, but the higher order the expansion, the # further from 0 we need to evaluate the derivatives, or they blow up. point = dict(zip(range(1, 14), 2 ** np.linspace(-1, 5, 13) / 100)) vals = dict(a=coef_a, b=coef_b, n=len(self.model.response.data), r=point[self.taylor]) deriv = [eval(x, globals(), vals) for x in self.deriv] # pylint: disable=eval-used terms = [ compute_sigma(deriv, p, q, i, j) for i in range(1, self.taylor + 1) for j in range(1, self.taylor + 1) ] return np.array(terms).sum() ** 0.5 def scale_response(self): # Add cases for other families priors = self.model.family.likelihood.priors <|code_end|> . Use current file imports: import sys import numpy as np import pandas as pd from os.path import dirname, join from scipy.special import hyp2f1 from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.tools.sm_exceptions import PerfectSeparationError from bambi.families.univariate import Gaussian, StudentT from .prior import Prior and context (classes, functions, or code) from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() . Output only the next line.
if isinstance(self.model.family, (Gaussian, StudentT)):
Given the following code snippet before the placeholder: <|code_start|> beta_mle = full_model.params[name].item() beta_seq = np.linspace(0, beta_mle, points) log_likelihood = get_llh(self.model, exog, full_model, name, values, beta_seq) coef_a, coef_b = get_llh_coeffs(log_likelihood, beta_mle, beta_seq) p, q = shape_params(sigma_corr) # Evaluate the derivatives of beta = f(correlation). # dict 'point' gives points about which to Taylor expand. # We want to expand about the mean (generally 0), but some of the derivatives # do not exist at 0. Evaluating at a point very close to 0 (e.g., .001) # generally gives good results, but the higher order the expansion, the # further from 0 we need to evaluate the derivatives, or they blow up. point = dict(zip(range(1, 14), 2 ** np.linspace(-1, 5, 13) / 100)) vals = dict(a=coef_a, b=coef_b, n=len(self.model.response.data), r=point[self.taylor]) deriv = [eval(x, globals(), vals) for x in self.deriv] # pylint: disable=eval-used terms = [ compute_sigma(deriv, p, q, i, j) for i in range(1, self.taylor + 1) for j in range(1, self.taylor + 1) ] return np.array(terms).sum() ** 0.5 def scale_response(self): # Add cases for other families priors = self.model.family.likelihood.priors if isinstance(self.model.family, (Gaussian, StudentT)): if priors["sigma"].auto_scale: sigma = np.std(self.model.response.data) <|code_end|> , predict the next line using imports from the current file: import sys import numpy as np import pandas as pd from os.path import dirname, join from scipy.special import hyp2f1 from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.tools.sm_exceptions import PerfectSeparationError from bambi.families.univariate import Gaussian, StudentT from .prior import Prior and context including class names, function names, and sometimes code from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() . Output only the next line.
priors["sigma"] = Prior("HalfStudentT", nu=4, sigma=sigma)
Given the code snippet: <|code_start|> >>> family = bmb.Family("bernoulli", likelihood, "logit") """ SUPPORTED_LINKS = [ "cloglog", "identity", "inverse_squared", "inverse", "log", "logit", "probit", "softmax", "tan_2", ] def __init__(self, name, likelihood, link): self.name = name self.likelihood = likelihood self.link = link self.smfamily = STATSMODELS_FAMILIES.get(name, None) self.aliases = {} @property def link(self): return self._link @link.setter def link(self, x): if isinstance(x, str): self.check_string_link(x) <|code_end|> , generate the next line using the imports in this file: from statsmodels.genmod import families as sm_families from bambi.families.link import Link and context (functions, classes, or occasionally code) from other files: # Path: bambi/families/link.py # class Link: # """Representation of link function. # # This object contains two main functions. One is the link function itself, the function # that maps values in the response scale to the linear predictor, and the other is the inverse # of the link function, that maps values of the linear predictor to the response scale. # # The great majority of users will never interact with this class unless they want to create # a custom ``Family`` with a custom ``Link``. This is automatically handled for all the built-in # families. # # Parameters # ---------- # name: str # The name of the link function. If it is a known name, it's not necessary to pass any # other arguments because functions are already defined internally. If not known, all of # ``link``, ``linkinv`` and ``linkinv_backend`` must be specified. # link: function # A function that maps the response to the linear predictor. Known as the :math:`g` function # in GLM jargon. Does not need to be specified when ``name`` is a known name. # linkinv: function # A function that maps the linear predictor to the response. Known as the :math:`g^{-1}` # function in GLM jargon. Does not need to be specified when ``name`` is a known name. # linkinv_backend: function # Same than ``linkinv`` but must be something that works with PyMC3 backend (i.e. it must # work with Theano tensors). Does not need to be specified when ``name`` is a known # name. # # """ # # def __init__(self, name, link=None, linkinv=None, linkinv_backend=None): # self.name = name # self.link = link # self.linkinv = linkinv # self.linkinv_backend = linkinv_backend # # if name in LINKS: # self.link = LINKS[name]["link"] # self.linkinv = LINKS[name]["linkinv"] # else: # if not link or not linkinv or not linkinv_backend: # raise ValueError( # f"Link name '{name}' is not supported and at least one of 'link', " # "'linkinv' or 'linkinv_backend' are unespecified." # ) # # def __str__(self): # args = [f"name: {self.name}", f"link: {self.link}", f"linkinv: {self.linkinv}"] # return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)" # # def __repr__(self): # return self.__str__() . Output only the next line.
self._link = Link(x)
Given snippet: <|code_start|> A function that maps the response to the linear predictor. Known as the :math:`g` function in GLM jargon. Does not need to be specified when ``name`` is a known name. linkinv: function A function that maps the linear predictor to the response. Known as the :math:`g^{-1}` function in GLM jargon. Does not need to be specified when ``name`` is a known name. linkinv_backend: function Same than ``linkinv`` but must be something that works with PyMC3 backend (i.e. it must work with Theano tensors). Does not need to be specified when ``name`` is a known name. """ def __init__(self, name, link=None, linkinv=None, linkinv_backend=None): self.name = name self.link = link self.linkinv = linkinv self.linkinv_backend = linkinv_backend if name in LINKS: self.link = LINKS[name]["link"] self.linkinv = LINKS[name]["linkinv"] else: if not link or not linkinv or not linkinv_backend: raise ValueError( f"Link name '{name}' is not supported and at least one of 'link', " "'linkinv' or 'linkinv_backend' are unespecified." ) def __str__(self): args = [f"name: {self.name}", f"link: {self.link}", f"linkinv: {self.linkinv}"] <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from scipy import special from bambi.utils import multilinify, spacify and context: # Path: bambi/utils.py # def multilinify(sequence, sep=","): # """Make a multi-line string out of a sequence of strings.""" # sep += "\n" # return "\n" + sep.join(sequence) # # def spacify(string): # """Add 2 spaces to the beginning of each line in a multi-line string.""" # return " " + " ".join(string.splitlines(True)) which might include code, classes, or functions. Output only the next line.
return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)"
Given the following code snippet before the placeholder: <|code_start|> A function that maps the response to the linear predictor. Known as the :math:`g` function in GLM jargon. Does not need to be specified when ``name`` is a known name. linkinv: function A function that maps the linear predictor to the response. Known as the :math:`g^{-1}` function in GLM jargon. Does not need to be specified when ``name`` is a known name. linkinv_backend: function Same than ``linkinv`` but must be something that works with PyMC3 backend (i.e. it must work with Theano tensors). Does not need to be specified when ``name`` is a known name. """ def __init__(self, name, link=None, linkinv=None, linkinv_backend=None): self.name = name self.link = link self.linkinv = linkinv self.linkinv_backend = linkinv_backend if name in LINKS: self.link = LINKS[name]["link"] self.linkinv = LINKS[name]["linkinv"] else: if not link or not linkinv or not linkinv_backend: raise ValueError( f"Link name '{name}' is not supported and at least one of 'link', " "'linkinv' or 'linkinv_backend' are unespecified." ) def __str__(self): args = [f"name: {self.name}", f"link: {self.link}", f"linkinv: {self.linkinv}"] <|code_end|> , predict the next line using imports from the current file: import numpy as np from scipy import special from bambi.utils import multilinify, spacify and context including class names, function names, and sometimes code from other files: # Path: bambi/utils.py # def multilinify(sequence, sep=","): # """Make a multi-line string out of a sequence of strings.""" # sep += "\n" # return "\n" + sep.join(sequence) # # def spacify(string): # """Add 2 spaces to the beginning of each line in a multi-line string.""" # return " " + " ".join(string.splitlines(True)) . Output only the next line.
return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)"
Based on the snippet: <|code_start|> if priors and args: difference = set(args) - set(priors) if len(difference) > 0: raise ValueError(f"'{self.name}' misses priors for the parameters {difference}") # And check priors passed are in fact of class Prior check_all_are_priors(priors) return priors def __str__(self): args = [f"name: {self.name}", f"parent: {self.parent}", f"priors: {self.priors}"] return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)" def __repr__(self): return self.__str__() def check_all_are_priors(priors): """Checks if values in the supplied dictionary are all valid prior objects An object is a valid prior if * It is an instance of bambi.priors.Prior * It is a number Parameters ---------- priors: dict A dictionary whose values are tested to be valid priors """ <|code_end|> , predict the immediate next line with the help of imports: from bambi.priors import Prior from bambi.utils import multilinify, spacify and context (classes, functions, sometimes code) from other files: # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() # # Path: bambi/utils.py # def multilinify(sequence, sep=","): # """Make a multi-line string out of a sequence of strings.""" # sep += "\n" # return "\n" + sep.join(sequence) # # def spacify(string): # """Add 2 spaces to the beginning of each line in a multi-line string.""" # return " " + " ".join(string.splitlines(True)) . Output only the next line.
if any(not isinstance(prior, (Prior, int, float)) for prior in priors.values()):
Given the following code snippet before the placeholder: <|code_start|> x = self.DISTRIBUTIONS[self.name]["parent"] elif x not in self.DISTRIBUTIONS[self.name]["params"]: raise ValueError(f"'{x}' is not a valid parameter for the likelihood '{self.name}'") # Otherwise, no check is done. At your own risk! self._parent = x def _check_priors(self, priors): args = self.DISTRIBUTIONS[self.name]["args"] # The function requires priors but none were passed if priors == {} and args is not None: raise ValueError(f"'{self.name}' requires priors for the parameters {args}.") # The function does not require priors, but at least one was passed if priors != {} and args is None: raise ValueError(f"'{self.name}' does not require any additional prior.") # The function requires priors, priors were passed, but they differ from the required if priors and args: difference = set(args) - set(priors) if len(difference) > 0: raise ValueError(f"'{self.name}' misses priors for the parameters {difference}") # And check priors passed are in fact of class Prior check_all_are_priors(priors) return priors def __str__(self): args = [f"name: {self.name}", f"parent: {self.parent}", f"priors: {self.priors}"] <|code_end|> , predict the next line using imports from the current file: from bambi.priors import Prior from bambi.utils import multilinify, spacify and context including class names, function names, and sometimes code from other files: # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() # # Path: bambi/utils.py # def multilinify(sequence, sep=","): # """Make a multi-line string out of a sequence of strings.""" # sep += "\n" # return "\n" + sep.join(sequence) # # def spacify(string): # """Add 2 spaces to the beginning of each line in a multi-line string.""" # return " " + " ".join(string.splitlines(True)) . Output only the next line.
return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)"
Given the following code snippet before the placeholder: <|code_start|> x = self.DISTRIBUTIONS[self.name]["parent"] elif x not in self.DISTRIBUTIONS[self.name]["params"]: raise ValueError(f"'{x}' is not a valid parameter for the likelihood '{self.name}'") # Otherwise, no check is done. At your own risk! self._parent = x def _check_priors(self, priors): args = self.DISTRIBUTIONS[self.name]["args"] # The function requires priors but none were passed if priors == {} and args is not None: raise ValueError(f"'{self.name}' requires priors for the parameters {args}.") # The function does not require priors, but at least one was passed if priors != {} and args is None: raise ValueError(f"'{self.name}' does not require any additional prior.") # The function requires priors, priors were passed, but they differ from the required if priors and args: difference = set(args) - set(priors) if len(difference) > 0: raise ValueError(f"'{self.name}' misses priors for the parameters {difference}") # And check priors passed are in fact of class Prior check_all_are_priors(priors) return priors def __str__(self): args = [f"name: {self.name}", f"parent: {self.parent}", f"priors: {self.priors}"] <|code_end|> , predict the next line using imports from the current file: from bambi.priors import Prior from bambi.utils import multilinify, spacify and context including class names, function names, and sometimes code from other files: # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() # # Path: bambi/utils.py # def multilinify(sequence, sep=","): # """Make a multi-line string out of a sequence of strings.""" # sep += "\n" # return "\n" + sep.join(sequence) # # def spacify(string): # """Add 2 spaces to the beginning of each line in a multi-line string.""" # return " " + " ".join(string.splitlines(True)) . Output only the next line.
return f"{self.__class__.__name__}({spacify(multilinify(args))}\n)"
Here is a snippet: <|code_start|> class PriorScaler: """Scale prior distributions parameters.""" # Standard deviation multiplier. STD = 2.5 def __init__(self, model): self.model = model self.has_intercept = model.intercept_term is not None self.priors = {} # Compute mean and std of the response <|code_end|> . Write the next line using the current file imports: import numpy as np from bambi.families.univariate import Gaussian, StudentT, VonMises from .prior import Prior and context from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # class VonMises(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "tan_2"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # kappa = posterior[model.response.name + "_kappa"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # kappa = kappa[:, idxs, np.newaxis] # # return np.random.vonmises(mean, kappa) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() , which may include functions, classes, or code. Output only the next line.
if isinstance(self.model.family, (Gaussian, StudentT)):
Given snippet: <|code_start|> class PriorScaler: """Scale prior distributions parameters.""" # Standard deviation multiplier. STD = 2.5 def __init__(self, model): self.model = model self.has_intercept = model.intercept_term is not None self.priors = {} # Compute mean and std of the response <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from bambi.families.univariate import Gaussian, StudentT, VonMises from .prior import Prior and context: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # class VonMises(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "tan_2"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # kappa = posterior[model.response.name + "_kappa"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # kappa = kappa[:, idxs, np.newaxis] # # return np.random.vonmises(mean, kappa) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() which might include code, classes, or functions. Output only the next line.
if isinstance(self.model.family, (Gaussian, StudentT)):
Given the code snippet: <|code_start|> # Compute mean and std of the response if isinstance(self.model.family, (Gaussian, StudentT)): self.response_mean = np.mean(model.response.data) self.response_std = np.std(self.model.response.data) else: self.response_mean = 0 self.response_std = 1 def get_intercept_stats(self): mu = self.response_mean sigma = self.STD * self.response_std # Only adjust mu and sigma if there is at least one Normal prior for a common term. if self.priors: sigmas = np.hstack([prior["sigma"] for prior in self.priors.values()]) x_mean = np.hstack([self.model.terms[term].data.mean(axis=0) for term in self.priors]) sigma = (sigma**2 + np.dot(sigmas**2, x_mean**2)) ** 0.5 return mu, sigma def get_slope_sigma(self, x): return self.STD * (self.response_std / np.std(x)) def scale_response(self): # Add cases for other families priors = self.model.family.likelihood.priors if isinstance(self.model.family, (Gaussian, StudentT)): if priors["sigma"].auto_scale: priors["sigma"] = Prior("HalfStudentT", nu=4, sigma=self.response_std) <|code_end|> , generate the next line using the imports in this file: import numpy as np from bambi.families.univariate import Gaussian, StudentT, VonMises from .prior import Prior and context (functions, classes, or occasionally code) from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # class VonMises(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "tan_2"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # kappa = posterior[model.response.name + "_kappa"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # kappa = kappa[:, idxs, np.newaxis] # # return np.random.vonmises(mean, kappa) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() . Output only the next line.
elif isinstance(self.model.family, VonMises):
Next line prediction: <|code_start|> self.priors = {} # Compute mean and std of the response if isinstance(self.model.family, (Gaussian, StudentT)): self.response_mean = np.mean(model.response.data) self.response_std = np.std(self.model.response.data) else: self.response_mean = 0 self.response_std = 1 def get_intercept_stats(self): mu = self.response_mean sigma = self.STD * self.response_std # Only adjust mu and sigma if there is at least one Normal prior for a common term. if self.priors: sigmas = np.hstack([prior["sigma"] for prior in self.priors.values()]) x_mean = np.hstack([self.model.terms[term].data.mean(axis=0) for term in self.priors]) sigma = (sigma**2 + np.dot(sigmas**2, x_mean**2)) ** 0.5 return mu, sigma def get_slope_sigma(self, x): return self.STD * (self.response_std / np.std(x)) def scale_response(self): # Add cases for other families priors = self.model.family.likelihood.priors if isinstance(self.model.family, (Gaussian, StudentT)): if priors["sigma"].auto_scale: <|code_end|> . Use current file imports: (import numpy as np from bambi.families.univariate import Gaussian, StudentT, VonMises from .prior import Prior) and context including class names, function names, or small code snippets from other files: # Path: bambi/families/univariate.py # class Gaussian(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # "Sample from posterior predictive distribution" # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return np.random.normal(mean, sigma) # # class StudentT(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "log", "inverse"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # sigma = posterior[model.response.name + "_sigma"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # if isinstance(self.likelihood.priors["nu"], (int, float)): # nu = self.likelihood.priors["nu"] # else: # nu = posterior[model.response.name + "_nu"].values[:, idxs, np.newaxis] # # mean = mean[:, idxs, :] # sigma = sigma[:, idxs, np.newaxis] # # return stats.t.rvs(nu, mean, sigma) # # class VonMises(UnivariateFamily): # SUPPORTED_LINKS = ["identity", "tan_2"] # # def posterior_predictive(self, model, posterior, linear_predictor, draws, draw_n): # mean = self.link.linkinv(linear_predictor) # kappa = posterior[model.response.name + "_kappa"].values # # idxs = np.random.randint(low=0, high=draw_n, size=draws) # mean = mean[:, idxs, :] # kappa = kappa[:, idxs, np.newaxis] # # return np.random.vonmises(mean, kappa) # # Path: bambi/priors/prior.py # class Prior: # """Abstract specification of a term prior. # # Parameters # ---------- # name : str # Name of prior distribution. Must be the name of a PyMC3 distribution # (e.g., ``"Normal"``, ``"Bernoulli"``, etc.) # auto_scale: bool # Whether to adjust the parameters of the prior or use them as passed. Default to ``True``. # scale: num or str # How to scale the prior. If a number, must be within 0 and 1. If a string, must be one of # ``"narrow"``, ``"medium"``, ``"wide"``, or ``"superwide"``. Only used when the model was # created with ``automatic_priors="mle"``. # kwargs : dict # Optional keywords specifying the parameters of the named distribution. # """ # # def __init__(self, name, auto_scale=True, scale=None, **kwargs): # self.name = name # self.auto_scale = auto_scale # self.scale = scale # self.args = {} # self.update(**kwargs) # # def update(self, **kwargs): # """Update the arguments of the prior with additional arguments. # # Parameters # ---------- # kwargs : dict # Optional keyword arguments to add to prior args. # """ # # The backend expect numpy arrays, so make sure all numeric values are represented as such. # kwargs_ = {} # for key, val in kwargs.items(): # if isinstance(val, (int, float)): # val = np.array(val) # elif isinstance(val, np.ndarray): # val = val.squeeze() # kwargs_[key] = val # self.args.update(kwargs_) # # def __eq__(self, other): # if not isinstance(other, type(self)): # return False # else: # return self.__dict__ == other.__dict__ # # def __str__(self): # args = ", ".join( # [ # f"{k}: {np.round_(v, 4)}" if not isinstance(v, type(self)) else f"{k}: {v}" # for k, v in self.args.items() # ] # ) # return f"{self.name}({args})" # # def __repr__(self): # return self.__str__() . Output only the next line.
priors["sigma"] = Prior("HalfStudentT", nu=4, sigma=self.response_std)
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class OutputType(Enum): PLAIN_TEXT = 1 JSON = 2 VERBOSE = 3 BINARY = 4 def parse_http_response(response: Response, resources_info: Dict, scar_info: Dict) -> None: '''Process the response generated by an API Gateway invocation.''' output_type = scar_info.get('cli_output') function_name = resources_info.get('lambda').get('name') asynch = resources_info.get('lambda').get('asynchronous') text_message = "" if response.ok: if output_type == OutputType.BINARY.value: output_file = scar_info.get('output_file', '') with open(output_file, "wb") as out: <|code_end|> using the current file's imports: import json import scar.logger as logger from typing import Dict from enum import Enum from tabulate import tabulate from scar.utils import StrUtils from requests import Response and any relevant context from other files: # Path: scar/utils.py # class StrUtils: # # """Common methods for string management.""" # # @staticmethod # def decode_base64(value: Union[bytes, str]) -> bytes: # """Decode a Base64 encoded bytes-like object or # ASCII string and return the decoded bytes""" # return base64.b64decode(value) # # @staticmethod # def encode_base64(value: bytes) -> bytes: # """Encode a bytes-like object using Base64 # and return the encoded bytes.""" # return base64.b64encode(value) # # @staticmethod # def base64_to_utf8_string(value: Union[bytes, str]) -> str: # """Decode a Base64 encoded bytes-like object or ASCII # string and return the decoded value as a string.""" # return StrUtils.decode_base64(value).decode('utf-8') # # @staticmethod # def utf8_to_base64_string(value: str) -> str: # """Encode a 'utf-8' string using Base64 and return # the encoded value as a string.""" # return StrUtils.encode_base64(bytes(value, 'utf-8')).decode('utf-8') # # @staticmethod # def bytes_to_base64str(value, encoding='utf-8') -> str: # """Encode a 'utf-8' string using Base64 and return # the encoded value as a string.""" # return StrUtils.encode_base64(value).decode(encoding) # # @staticmethod # def dict_to_base64_string(value: Dict) -> str: # """Encodes a dictionary to base64 and returns a string.""" # return StrUtils.utf8_to_base64_string(json.dumps(value)) # # @staticmethod # def find_expression(string_to_search: str, rgx_pattern: str) -> Optional[str]: # """Returns the first group that matches the rgx_pattern in the string_to_search.""" # if string_to_search: # pattern = re.compile(rgx_pattern) # match = pattern.search(string_to_search) # if match: # return match.group() # return None # # @staticmethod # def get_random_uuid4_str() -> str: # """Returns a random generated uuid4 string.""" # return str(uuid.uuid4()) # # @staticmethod # def compare_versions(ver1: str, ver2: str) -> int: # """Returns value < 0 to indicate that ver1 is less than ver2. # Returns value > 0 to indicate that ver1 is greater than ver2. # Returns value == 0 to indicate that ver1 is equal to ver2.""" # res = 0 # if version.parse(ver1) < version.parse(ver2): # res = -1 # elif version.parse(ver1) > version.parse(ver2): # res = 1 # return res . Output only the next line.
out.write(StrUtils.decode_base64(response.text))
Given snippet: <|code_start|># Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Load readme with open('README.md', mode='r', encoding='utf-8') as f: readme = f.read() setup(name='scar', <|code_end|> , continue by predicting the next line. Consider current file imports: from setuptools import setup, find_namespace_packages from scar.version import __version__ and context: # Path: scar/version.py which might include code, classes, or functions. Output only the next line.
version=__version__,
Predict the next line after this snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestOSCARController(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) @patch('scar.providers.oscar.controller.OSCARClient') @patch('scar.providers.aws.controller.FileUtils.load_tmp_config_file') def test_init(self, load_tmp_config_file, oscar_client): tmpfile = tempfile.NamedTemporaryFile(delete=False) tmpfile.write(b'Hello world!') tmpfile.close() load_tmp_config_file.return_value = {"functions": {"oscar": [{"my_oscar": {"name": "oname", "script": tmpfile.name}}]}} ocli = MagicMock(['create_service']) oscar_client.return_value = ocli <|code_end|> using the current file's imports: import unittest import sys import os import tempfile from mock import MagicMock from mock import patch from scar.providers.oscar.controller import OSCAR and any relevant context from other files: # Path: scar/providers/oscar/controller.py # class OSCAR(): # # def __init__(self, func_call: Dict): # self.raw_args = FileUtils.load_tmp_config_file() # # Flatten the list of services # self.oscar_resources = [] # nested_resources = self.raw_args.get('functions', {}).get('oscar', []) # for resources in nested_resources: # for cluster_id, resources_info in resources.items(): # if ('name' in resources[cluster_id] and # resources[cluster_id]['name']): # resources_info['cluster_id'] = cluster_id # self.oscar_resources.append(resources_info) # # Store the storage_providers dict independently # self.storage_providers = self.raw_args.get('storage_providers', {}) # self.scar_info = self.raw_args.get('scar', {}) # add_output(self.scar_info) # # Call the user's command # getattr(self, func_call)() # # @excp.exception(logger) # def init(self): # for resources_info in self.oscar_resources: # resources_info = deepcopy(resources_info) # self._create_oscar_service(resources_info) # response_parser.parse_service_creation(resources_info, self.scar_info.get('cli_output')) # # @excp.exception(logger) # def rm(self): # for resources_info in self.oscar_resources: # resources_info = deepcopy(resources_info) # credentials_info = _get_credentials_info(resources_info) # OSCARClient(credentials_info, resources_info.get('cluster_id', '')).delete_service(resources_info['name']) # response_parser.parse_service_deletion(resources_info, self.scar_info.get('cli_output')) # # def _create_oscar_service(self, resources_info: Dict): # credentials_info = _get_credentials_info(resources_info) # creation_args = _get_creation_args(resources_info, self.storage_providers) # OSCARClient(credentials_info, resources_info.get('cluster_id', '')).create_service(**creation_args) # # @excp.exception(logger) # def ls(self): # clusters = self.raw_args.get('functions', {}).get('oscar', [{}])[0] # for cluster_id, resources_info in clusters.items(): # credentials_info = _get_credentials_info(resources_info) # if _are_credentials_defined(credentials_info): # oscar_resources = OSCARClient(credentials_info, cluster_id).list_services() # response_parser.parse_ls_response(oscar_resources, # credentials_info['endpoint'], # cluster_id, # self.scar_info.get('cli_output')) . Output only the next line.
OSCAR('init')
Given the code snippet: <|code_start|>#! /usr/bin/python # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestIAM(unittest.TestCase): def __init__(self, *args): os.environ["AWS_DEFAULT_REGION"] = "us-east-1" unittest.TestCase.__init__(self, *args) def test_init(self): <|code_end|> , generate the next line using the imports in this file: import unittest import sys import os from mock import MagicMock from mock import patch from scar.providers.aws.iam import IAM and context (functions, classes, or occasionally code) from other files: # Path: scar/providers/aws/iam.py # class IAM(GenericClient): # # def __init__(self, resources_info) -> None: # super().__init__(resources_info.get('iam')) # # def get_user_name_or_id(self): # user = self.client.get_user_info() # if user: # return user.get('UserName', user['User']['UserId']) . Output only the next line.
ecr = IAM({})
Continue the code snippet: <|code_start|>#! /usr/bin/python # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestCloudWatchLogs(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) def test_init(self): <|code_end|> . Use current file imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.aws.cloudwatchlogs import CloudWatchLogs and context (classes, functions, or code) from other files: # Path: scar/providers/aws/cloudwatchlogs.py # class CloudWatchLogs(GenericClient): # """Manages the AWS CloudWatch Logs functionality""" # # def __init__(self, resources_info: Dict): # super().__init__(resources_info.get('cloudwatch')) # self.resources_info = resources_info # self.cloudwatch = resources_info.get('cloudwatch') # # def get_log_group_name(self, function_name: str=None) -> str: # """Returns the log group matching the # current lambda function being parsed.""" # if function_name: # return f'/aws/lambda/{function_name}' # return f'/aws/lambda/{self.resources_info.get("lambda").get("name")}' # # def _get_log_group_name_arg(self, function_name: str=None) -> Dict: # return {'logGroupName' : self.get_log_group_name(function_name)} # # def _is_end_line(self, line: str) -> bool: # return line.startswith('REPORT') and self.cloudwatch.get('request_id') in line # # def _is_start_line(self, line: str) -> bool: # return line.startswith('START') and self.cloudwatch.get('request_id') in line # # def _parse_logs_with_requestid(self, function_logs: str) -> str: # parsed_msg = "" # if function_logs: # in_req_id_logs = False # for line in function_logs.split('\n'): # if self._is_start_line(line): # parsed_msg += f'{line}\n' # in_req_id_logs = True # elif self._is_end_line(line): # parsed_msg += line # break # elif in_req_id_logs: # parsed_msg += f'{line}\n' # return parsed_msg # # def _get_lambda_logs(self): # """Returns Lambda logs for an specific lambda function.""" # function_logs = "" # try: # kwargs = self._get_log_group_name_arg() # if self.cloudwatch.get("log_stream_name", False): # kwargs["logStreamNames"] = [self.cloudwatch.get("log_stream_name")] # function_logs = _parse_events_in_message(self.client.get_log_events(**kwargs)) # if self.cloudwatch.get("request_id", False): # function_logs = self._parse_logs_with_requestid(function_logs) # except ClientError as cerr: # logger.warning("Error getting the function logs: %s" % cerr) # return function_logs # # def _get_batch_job_log(self, jobs_info: List) -> str: # """Returns Batch logs for an specific job.""" # batch_logs = "" # if jobs_info: # job = jobs_info[0] # batch_logs += f"Batch job status: {job.get('status', '')}\n" # kwargs = {'logGroupName': "/aws/batch/job"} # if job.get("status", "") == "SUCCEEDED": # kwargs['logStreamNames'] = [job.get("container", {}).get("logStreamName", "")] # batch_events = self.client.get_log_events(**kwargs) # msgs = [event.get('message', '') # for event in batch_events] # batch_logs += '\n'.join(msgs) # return batch_logs # # def create_log_group(self) -> Dict: # """Creates a CloudWatch Log Group.""" # creation_args = self._get_log_group_name_arg() # creation_args['tags'] = self.resources_info.get('lambda').get('tags') # response = self.client.create_log_group(**creation_args) # # Set retention policy into the log group # retention_args = self._get_log_group_name_arg() # retention_args['retentionInDays'] = self.cloudwatch.get('log_retention_policy_in_days') # self.client.set_log_retention_policy(**retention_args) # return response # # def delete_log_group(self, log_group_name: str) -> Dict: # """Deletes a CloudWatch Log Group.""" # return self.client.delete_log_group(log_group_name) # # def get_aws_logs(self) -> str: # """Returns Cloudwatch logs for an specific lambda function and batch job (if any).""" # aws_logs = self._get_lambda_logs() # batch_logs = "" # if self.resources_info.get('cloudwatch').get('request_id', False): # batch_jobs = Batch(self.resources_info).get_jobs_with_request_id() # batch_logs = self._get_batch_job_log(batch_jobs["jobs"]) # return aws_logs + batch_logs if batch_logs else aws_logs . Output only the next line.
cwl = CloudWatchLogs({})
Based on the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Test(unittest.TestCase): def testFDL(self): ''' Expected return value (except random ids): [{'env_vars':{ 'STORAGE_AUTH_MINIO_PASS_TMPXCMCNA9S': 'mpass', 'STORAGE_AUTH_MINIO_USER_TMPXCMCNA9S': 'muser', 'STORAGE_PATH_INPUT_TMPOTOWSDYE': 's3-bucket/test1', 'STORAGE_PATH_INPUT_TMPXCMCNA9S': 'my-bucket/test', 'STORAGE_PATH_OUTPUT_TMPOTOWSDYE': 's3-bucket/test1-output', 'STORAGE_PATH_OUTPUT_TMPXCMCNA9S': 'my-bucket/test-output', 'STORAGE_PATH_SUFIX_TMPOTOWSDYE': 'avi', 'STORAGE_PATH_SUFIX_TMPXCMCNA9S': 'wav:srt'}, 'name': 'function1'}, {'env_vars': { 'STORAGE_AUTH_MINIO_PASS_TMPXCMCNA9S': 'mpass', 'STORAGE_AUTH_MINIO_USER_TMPXCMCNA9S': 'muser', 'STORAGE_PATH_INPUT_TMPXCMCNA9S': 'my-bucket2/test', 'STORAGE_PATH_OUTPUT_TMPXCMCNA9S': 'my-bucket2/test-output', 'STORAGE_PATH_PREFIX_TMPXCMCNA9S': 'my_file'}, 'name': 'function2'}] ''' <|code_end|> , predict the immediate next line with the help of imports: import unittest from scar.parser.fdl import FDLParser and context (classes, functions, sometimes code) from other files: # Path: scar/parser/fdl.py # FAAS_PROVIDERS = ["aws", "oscar"] # def merge_conf(conf: Dict, yaml: Dict) -> Dict: # def merge_cmd_yaml(cmd: Dict, yaml: Dict) -> Dict: . Output only the next line.
result = FDLParser().parse_yaml('fdl.yaml')
Next line prediction: <|code_start|>#! /usr/bin/python # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestECR(unittest.TestCase): def __init__(self, *args): os.environ["AWS_DEFAULT_REGION"] = "us-east-1" unittest.TestCase.__init__(self, *args) def test_init(self): <|code_end|> . Use current file imports: (import unittest import sys import os from mock import MagicMock from mock import patch, call from scar.providers.aws.ecr import ECR) and context including class names, function names, or small code snippets from other files: # Path: scar/providers/aws/ecr.py # class ECR(GenericClient): # """Manages the AWS ElasticContainerRegistry functionality""" # # def __init__(self, resources_info: Dict): # super().__init__() # self.resources_info = resources_info # # def get_authorization_token(self) -> str: # """Retrieves an authorization token.""" # return self.client.get_authorization_token() # # def get_registry_url(self) -> str: # """Retrieves the registry URL.""" # registry_id = self.client.get_registry_id() # return "%s.dkr.ecr.us-east-1.amazonaws.com" % registry_id # # def get_repository_uri(self, repository_name: str) -> str: # """Check if a repository exists.""" # response = self.client.describe_repositories(repositoryNames=[repository_name]) # if response: # return response["repositories"][0]["repositoryUri"] # else: # return None # # def create_repository(self, repository_name: str) -> str: # """Creates a repository.""" # response = self.client.create_repository(repository_name) # return response["repository"]["repositoryUri"] # # def delete_repository(self, repository_name: str): # self.client.delete_repository(repository_name) . Output only the next line.
ecr = ECR({})
Predict the next line for this snippet: <|code_start|> text_message = f'Service \'{resources_info["name"]}\' successfully created on cluster \'{resources_info.get("cluster_id")}\'.' _print_generic_response(resources_info, output_type, text_message, result) def parse_service_deletion(resources_info: Dict, output_type: int) -> None: result = _parse_service_info(resources_info) text_message = f'Service \'{resources_info.get("name")}\' successfully deleted from cluster \'{resources_info.get("cluster_id")}\'.' _print_generic_response(resources_info, output_type, text_message, result) def _parse_service_info(resources_info: Dict) -> Dict: return {'Name': resources_info.get('name', '-'), 'Memory': resources_info.get('memory', '-'), 'CPU': resources_info.get('cpu', '-'), 'Image_id': resources_info.get('image', '-')} def _get_table(services_info: List) -> str: headers = ['NAME', 'MEMORY', 'CPU', 'IMAGE_ID'] table = [] for function in services_info: table.append([function['Name'], function['Memory'], function['CPU'], function['Image_id']]) return tabulate(table, headers) def _print_generic_response(resources_info: Dict, output_type: int, text_message: str, json_output: Dict) -> None: # Support 'PLAIN_TEXT', 'JSON' and 'VERBOSE' output types <|code_end|> with the help of current file imports: from typing import Dict, List from tabulate import tabulate from scar.providers.aws.response import OutputType import scar.logger as logger and context from other files: # Path: scar/providers/aws/response.py # class OutputType(Enum): # PLAIN_TEXT = 1 # JSON = 2 # VERBOSE = 3 # BINARY = 4 , which may contain function names, class names, or code. Output only the next line.
if output_type == OutputType.PLAIN_TEXT.value:
Continue the code snippet: <|code_start|> # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestOSCARClient(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) @patch('requests.post') def test_create_serviced(self, post): response = MagicMock(["status_code", "text"]) response.status_code = 201 post.return_value = response <|code_end|> . Use current file imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.oscar.client import OSCARClient from scar.exceptions import ServiceCreationError, ServiceDeletionError, ServiceNotFoundError, ListServicesError and context (classes, functions, or code) from other files: # Path: scar/providers/oscar/client.py # class OSCARClient(): # _SERVICES_PATH = '/system/services' # # def __init__(self, credentials_info: Dict, cluster_id: str): # self.cluster_id = cluster_id # self.endpoint = credentials_info['endpoint'] # self.auth_user = credentials_info['auth_user'] # self.auth_password = credentials_info['auth_password'] # self.ssl_verify = credentials_info['ssl_verify'] # # def create_service(self, **kwargs: Dict) -> Dict: # """Creates a new OSCAR service.""" # logger.debug('Creating OSCAR service.') # res = requests.post( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify, # json=kwargs # ) # # Raise a ServiceCreationError if the return code is not 201 # if res.status_code != 201: # raise excp.ServiceCreationError(service_name=kwargs['name'], error_msg=_get_error_msg(res)) # # def delete_service(self, service_name: str) -> None: # """Deletes an OSCAR service.""" # logger.debug('Deleting OSCAR service.') # res = requests.delete( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceDeletionError if the return code is not 204 # if res.status_code != 204: # raise excp.ServiceDeletionError(service_name=service_name, error_msg=_get_error_msg(res)) # # def get_service(self, service_name: str) -> Dict: # """Get the properties of the specified service.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceNotFoundError if the return code is not 200 # if res.status_code != 200: # raise excp.ServiceNotFoundError(service_name=service_name, error_msg=_get_error_msg(res)) # return res.json() # # def list_services(self) -> List: # """Get all the services registered in the cluster.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ListServicesError if the return code is not 200 # if res.status_code != 200: # raise excp.ListServicesError(cluster_id=self.cluster_id, error_msg=_get_error_msg(res)) # return res.json() # # Path: scar/exceptions.py # class ServiceCreationError(ScarError): # """ # There was an error creating the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to create the service '{service_name}': {error_msg}" # # class ServiceDeletionError(ScarError): # """ # There was an error deleting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to delete the service '{service_name}': {error_msg}" # # class ServiceNotFoundError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "The service '{service_name}' does not exist: {error_msg}" # # class ListServicesError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to list services from OSCAR cluster '{cluster_id}': {error_msg}" . Output only the next line.
oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid")
Using the snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestOSCARClient(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) @patch('requests.post') def test_create_serviced(self, post): response = MagicMock(["status_code", "text"]) response.status_code = 201 post.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") oscar.create_service(key="value") self.assertEqual(post.call_args_list[0][0][0], "url/system/services") self.assertEqual(post.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False, 'json': {'key': 'value'}}) response.status_code = 401 response.text = "Some error" <|code_end|> , determine the next line of code. You have imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.oscar.client import OSCARClient from scar.exceptions import ServiceCreationError, ServiceDeletionError, ServiceNotFoundError, ListServicesError and context (class names, function names, or code) available: # Path: scar/providers/oscar/client.py # class OSCARClient(): # _SERVICES_PATH = '/system/services' # # def __init__(self, credentials_info: Dict, cluster_id: str): # self.cluster_id = cluster_id # self.endpoint = credentials_info['endpoint'] # self.auth_user = credentials_info['auth_user'] # self.auth_password = credentials_info['auth_password'] # self.ssl_verify = credentials_info['ssl_verify'] # # def create_service(self, **kwargs: Dict) -> Dict: # """Creates a new OSCAR service.""" # logger.debug('Creating OSCAR service.') # res = requests.post( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify, # json=kwargs # ) # # Raise a ServiceCreationError if the return code is not 201 # if res.status_code != 201: # raise excp.ServiceCreationError(service_name=kwargs['name'], error_msg=_get_error_msg(res)) # # def delete_service(self, service_name: str) -> None: # """Deletes an OSCAR service.""" # logger.debug('Deleting OSCAR service.') # res = requests.delete( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceDeletionError if the return code is not 204 # if res.status_code != 204: # raise excp.ServiceDeletionError(service_name=service_name, error_msg=_get_error_msg(res)) # # def get_service(self, service_name: str) -> Dict: # """Get the properties of the specified service.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceNotFoundError if the return code is not 200 # if res.status_code != 200: # raise excp.ServiceNotFoundError(service_name=service_name, error_msg=_get_error_msg(res)) # return res.json() # # def list_services(self) -> List: # """Get all the services registered in the cluster.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ListServicesError if the return code is not 200 # if res.status_code != 200: # raise excp.ListServicesError(cluster_id=self.cluster_id, error_msg=_get_error_msg(res)) # return res.json() # # Path: scar/exceptions.py # class ServiceCreationError(ScarError): # """ # There was an error creating the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to create the service '{service_name}': {error_msg}" # # class ServiceDeletionError(ScarError): # """ # There was an error deleting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to delete the service '{service_name}': {error_msg}" # # class ServiceNotFoundError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "The service '{service_name}' does not exist: {error_msg}" # # class ListServicesError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to list services from OSCAR cluster '{cluster_id}': {error_msg}" . Output only the next line.
with self.assertRaises(ServiceCreationError) as ex:
Continue the code snippet: <|code_start|> def test_create_serviced(self, post): response = MagicMock(["status_code", "text"]) response.status_code = 201 post.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") oscar.create_service(key="value") self.assertEqual(post.call_args_list[0][0][0], "url/system/services") self.assertEqual(post.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False, 'json': {'key': 'value'}}) response.status_code = 401 response.text = "Some error" with self.assertRaises(ServiceCreationError) as ex: oscar.create_service(name="sname") self.assertEqual( "Unable to create the service 'sname': Some error", str(ex.exception) ) @patch('requests.delete') def test_delete_service(self, delete): response = MagicMock(["status_code", "text"]) response.status_code = 204 delete.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") oscar.delete_service("sname") self.assertEqual(delete.call_args_list[0][0][0], "url/system/services/sname") self.assertEqual(delete.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False}) response.status_code = 401 response.text = "Some error" <|code_end|> . Use current file imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.oscar.client import OSCARClient from scar.exceptions import ServiceCreationError, ServiceDeletionError, ServiceNotFoundError, ListServicesError and context (classes, functions, or code) from other files: # Path: scar/providers/oscar/client.py # class OSCARClient(): # _SERVICES_PATH = '/system/services' # # def __init__(self, credentials_info: Dict, cluster_id: str): # self.cluster_id = cluster_id # self.endpoint = credentials_info['endpoint'] # self.auth_user = credentials_info['auth_user'] # self.auth_password = credentials_info['auth_password'] # self.ssl_verify = credentials_info['ssl_verify'] # # def create_service(self, **kwargs: Dict) -> Dict: # """Creates a new OSCAR service.""" # logger.debug('Creating OSCAR service.') # res = requests.post( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify, # json=kwargs # ) # # Raise a ServiceCreationError if the return code is not 201 # if res.status_code != 201: # raise excp.ServiceCreationError(service_name=kwargs['name'], error_msg=_get_error_msg(res)) # # def delete_service(self, service_name: str) -> None: # """Deletes an OSCAR service.""" # logger.debug('Deleting OSCAR service.') # res = requests.delete( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceDeletionError if the return code is not 204 # if res.status_code != 204: # raise excp.ServiceDeletionError(service_name=service_name, error_msg=_get_error_msg(res)) # # def get_service(self, service_name: str) -> Dict: # """Get the properties of the specified service.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceNotFoundError if the return code is not 200 # if res.status_code != 200: # raise excp.ServiceNotFoundError(service_name=service_name, error_msg=_get_error_msg(res)) # return res.json() # # def list_services(self) -> List: # """Get all the services registered in the cluster.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ListServicesError if the return code is not 200 # if res.status_code != 200: # raise excp.ListServicesError(cluster_id=self.cluster_id, error_msg=_get_error_msg(res)) # return res.json() # # Path: scar/exceptions.py # class ServiceCreationError(ScarError): # """ # There was an error creating the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to create the service '{service_name}': {error_msg}" # # class ServiceDeletionError(ScarError): # """ # There was an error deleting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to delete the service '{service_name}': {error_msg}" # # class ServiceNotFoundError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "The service '{service_name}' does not exist: {error_msg}" # # class ListServicesError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to list services from OSCAR cluster '{cluster_id}': {error_msg}" . Output only the next line.
with self.assertRaises(ServiceDeletionError) as ex:
Here is a snippet: <|code_start|> response = MagicMock(["status_code", "text"]) response.status_code = 204 delete.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") oscar.delete_service("sname") self.assertEqual(delete.call_args_list[0][0][0], "url/system/services/sname") self.assertEqual(delete.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False}) response.status_code = 401 response.text = "Some error" with self.assertRaises(ServiceDeletionError) as ex: oscar.delete_service("sname") self.assertEqual( "Unable to delete the service 'sname': Some error", str(ex.exception) ) @patch('requests.get') def test_get_service(self, get): response = MagicMock(["status_code", "json"]) response.status_code = 200 response.json.return_value = {"key": "value"} get.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") self.assertEqual(oscar.get_service("sname"), {"key": "value"}) self.assertEqual(get.call_args_list[0][0][0], "url/system/services/sname") self.assertEqual(get.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False}) response.status_code = 401 response.text = "Some error" <|code_end|> . Write the next line using the current file imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.oscar.client import OSCARClient from scar.exceptions import ServiceCreationError, ServiceDeletionError, ServiceNotFoundError, ListServicesError and context from other files: # Path: scar/providers/oscar/client.py # class OSCARClient(): # _SERVICES_PATH = '/system/services' # # def __init__(self, credentials_info: Dict, cluster_id: str): # self.cluster_id = cluster_id # self.endpoint = credentials_info['endpoint'] # self.auth_user = credentials_info['auth_user'] # self.auth_password = credentials_info['auth_password'] # self.ssl_verify = credentials_info['ssl_verify'] # # def create_service(self, **kwargs: Dict) -> Dict: # """Creates a new OSCAR service.""" # logger.debug('Creating OSCAR service.') # res = requests.post( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify, # json=kwargs # ) # # Raise a ServiceCreationError if the return code is not 201 # if res.status_code != 201: # raise excp.ServiceCreationError(service_name=kwargs['name'], error_msg=_get_error_msg(res)) # # def delete_service(self, service_name: str) -> None: # """Deletes an OSCAR service.""" # logger.debug('Deleting OSCAR service.') # res = requests.delete( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceDeletionError if the return code is not 204 # if res.status_code != 204: # raise excp.ServiceDeletionError(service_name=service_name, error_msg=_get_error_msg(res)) # # def get_service(self, service_name: str) -> Dict: # """Get the properties of the specified service.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceNotFoundError if the return code is not 200 # if res.status_code != 200: # raise excp.ServiceNotFoundError(service_name=service_name, error_msg=_get_error_msg(res)) # return res.json() # # def list_services(self) -> List: # """Get all the services registered in the cluster.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ListServicesError if the return code is not 200 # if res.status_code != 200: # raise excp.ListServicesError(cluster_id=self.cluster_id, error_msg=_get_error_msg(res)) # return res.json() # # Path: scar/exceptions.py # class ServiceCreationError(ScarError): # """ # There was an error creating the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to create the service '{service_name}': {error_msg}" # # class ServiceDeletionError(ScarError): # """ # There was an error deleting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to delete the service '{service_name}': {error_msg}" # # class ServiceNotFoundError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "The service '{service_name}' does not exist: {error_msg}" # # class ListServicesError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to list services from OSCAR cluster '{cluster_id}': {error_msg}" , which may include functions, classes, or code. Output only the next line.
with self.assertRaises(ServiceNotFoundError) as ex:
Predict the next line after this snippet: <|code_start|> response.status_code = 200 response.json.return_value = {"key": "value"} get.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") self.assertEqual(oscar.get_service("sname"), {"key": "value"}) self.assertEqual(get.call_args_list[0][0][0], "url/system/services/sname") self.assertEqual(get.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False}) response.status_code = 401 response.text = "Some error" with self.assertRaises(ServiceNotFoundError) as ex: oscar.get_service("sname"), {"key": "value"} self.assertEqual( "The service 'sname' does not exist: Some error", str(ex.exception) ) @patch('requests.get') def test_list_services(self, get): response = MagicMock(["status_code", "json"]) response.status_code = 200 response.json.return_value = {"key": "value"} get.return_value = response oscar = OSCARClient({"endpoint": "url", "auth_user": "user", "auth_password": "pass", "ssl_verify": False}, "cid") self.assertEqual(oscar.list_services(), {"key": "value"}) self.assertEqual(get.call_args_list[0][0][0], "url/system/services") self.assertEqual(get.call_args_list[0][1], {'auth': ('user', 'pass'), 'verify': False}) response.status_code = 401 response.text = "Some error" <|code_end|> using the current file's imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.oscar.client import OSCARClient from scar.exceptions import ServiceCreationError, ServiceDeletionError, ServiceNotFoundError, ListServicesError and any relevant context from other files: # Path: scar/providers/oscar/client.py # class OSCARClient(): # _SERVICES_PATH = '/system/services' # # def __init__(self, credentials_info: Dict, cluster_id: str): # self.cluster_id = cluster_id # self.endpoint = credentials_info['endpoint'] # self.auth_user = credentials_info['auth_user'] # self.auth_password = credentials_info['auth_password'] # self.ssl_verify = credentials_info['ssl_verify'] # # def create_service(self, **kwargs: Dict) -> Dict: # """Creates a new OSCAR service.""" # logger.debug('Creating OSCAR service.') # res = requests.post( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify, # json=kwargs # ) # # Raise a ServiceCreationError if the return code is not 201 # if res.status_code != 201: # raise excp.ServiceCreationError(service_name=kwargs['name'], error_msg=_get_error_msg(res)) # # def delete_service(self, service_name: str) -> None: # """Deletes an OSCAR service.""" # logger.debug('Deleting OSCAR service.') # res = requests.delete( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceDeletionError if the return code is not 204 # if res.status_code != 204: # raise excp.ServiceDeletionError(service_name=service_name, error_msg=_get_error_msg(res)) # # def get_service(self, service_name: str) -> Dict: # """Get the properties of the specified service.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}/{service_name}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ServiceNotFoundError if the return code is not 200 # if res.status_code != 200: # raise excp.ServiceNotFoundError(service_name=service_name, error_msg=_get_error_msg(res)) # return res.json() # # def list_services(self) -> List: # """Get all the services registered in the cluster.""" # res = requests.get( # f'{self.endpoint}{self._SERVICES_PATH}', # auth=(self.auth_user, self.auth_password), # verify=self.ssl_verify # ) # # Raise a ListServicesError if the return code is not 200 # if res.status_code != 200: # raise excp.ListServicesError(cluster_id=self.cluster_id, error_msg=_get_error_msg(res)) # return res.json() # # Path: scar/exceptions.py # class ServiceCreationError(ScarError): # """ # There was an error creating the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to create the service '{service_name}': {error_msg}" # # class ServiceDeletionError(ScarError): # """ # There was an error deleting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to delete the service '{service_name}': {error_msg}" # # class ServiceNotFoundError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "The service '{service_name}' does not exist: {error_msg}" # # class ListServicesError(ScarError): # """ # There was an error getting the OSCAR service # # :ivar service_name: Name of the function # :ivar error_msg: General error message # """ # fmt = "Unable to list services from OSCAR cluster '{cluster_id}': {error_msg}" . Output only the next line.
with self.assertRaises(ListServicesError) as ex:
Predict the next line for this snippet: <|code_start|>#! /usr/bin/python # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestResourceGroups(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) def test_init(self): <|code_end|> with the help of current file imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.aws.resourcegroups import ResourceGroups and context from other files: # Path: scar/providers/aws/resourcegroups.py # class ResourceGroups(GenericClient): # """Class to manage AWS Resource Groups""" # # def __init__(self, resources_info) -> None: # super().__init__(resources_info.get('lambda')) # # def get_resource_arn_list(self, iam_user_id: str, resource_type: str = 'lambda') -> List: # """Returns a list of ARNs filtered by the resource_type # passed and the tags created by scar.""" # try: # # Creation of a function_info filter by tags # tag_filters = [{'Key': 'owner', 'Values': [iam_user_id]}, # {'Key': 'createdby', 'Values': ['scar']}] # resource_type_filters = [resource_type] # tagged_resources = self.client.get_tagged_resources(tag_filters, resource_type_filters) # return [function_info['ResourceARN'] for function_info in tagged_resources] # except ClientError as cerr: # logger.error("Error getting function_info arn by tag", # f"Error getting function_info arn by tag: {cerr}") # raise cerr , which may contain function names, class names, or code. Output only the next line.
rg = ResourceGroups({})
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. FAAS_PROVIDERS = ["aws", "oscar"] def merge_conf(conf: Dict, yaml: Dict) -> Dict: result = yaml.copy() # We have to merge the default config with all the defined functions for provider in FAAS_PROVIDERS: for index, function in enumerate(result.get('functions', {}).get(provider, {})): result['functions'][provider][index] = \ <|code_end|> , predict the next line using imports from the current file: from typing import Dict from scar.utils import DataTypesUtils and context including class names, function names, and sometimes code from other files: # Path: scar/utils.py # class DataTypesUtils: # # """Common methods for data types management.""" # # @staticmethod # def merge_dicts(dict1: Dict, dict2: Dict) -> Dict: # """Merge 'dict1' and 'dict2' dicts into 'dict1'. # 'dict2' has precedence over 'dict1'. # """ # for key, val in dict2.items(): # if val is not None: # if isinstance(val, dict) and key in dict1: # dict1[key] = DataTypesUtils.merge_dicts(dict1[key], val) # elif isinstance(val, list) and key in dict1: # dict1[key] += val # else: # dict1[key] = val # return dict1 # # @staticmethod # def merge_dicts_with_copy(dict1: Dict, dict2: Dict) -> Dict: # """Merge 'dict1' and 'dict2' dicts into a new Dict. # 'dict2' has precedence over 'dict1'.""" # result = deepcopy(dict1) # for key, val in dict2.items(): # if val is not None: # if isinstance(val, dict) and key in result: # result[key] = DataTypesUtils.merge_dicts_with_copy(result[key], val) # elif isinstance(val, list) and key in result: # result[key] += val # else: # result[key] = val # return result # # @staticmethod # def divide_list_in_chunks(elements: List, chunk_size: int) -> Generator[List, None, None]: # """Yield successive n-sized chunks from th elements list.""" # if not elements: # yield [] # for i in range(0, len(elements), chunk_size): # yield elements[i:i + chunk_size] # # @staticmethod # def parse_arg_list(arg_keys: List, cmd_args: Dict) -> Dict: # """Parse an argument dictionary filtering by the names specified in a list.""" # result = {} # for key in arg_keys: # if isinstance(key, tuple): # if key[0] in cmd_args and cmd_args[key[0]]: # result[key[1]] = cmd_args[key[0]] # else: # if key in cmd_args and cmd_args[key]: # result[key] = cmd_args[key] # return result . Output only the next line.
DataTypesUtils.merge_dicts_with_copy(conf.get(provider,{}), function)
Using the snippet: <|code_start|>#! /usr/bin/python # Copyright (C) GRyCAP - I3M - UPV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. sys.path.append("..") sys.path.append(".") sys.path.append("../..") class TestAPIGateway(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) def test_init(self): <|code_end|> , determine the next line of code. You have imports: import unittest import sys from mock import MagicMock from mock import patch from scar.providers.aws.apigateway import APIGateway and context (class names, function names, or code) available: # Path: scar/providers/aws/apigateway.py # class APIGateway(GenericClient): # """Manage the calls to the ApiGateway client.""" # # def __init__(self, resources_info: Dict): # super().__init__(resources_info.get('api_gateway', {})) # self.resources_info = resources_info # self.api = self.resources_info.get('api_gateway', {}) # # def _get_common_args(self) -> Dict: # return {'restApiId' : self.api.get('id', ''), # 'resourceId' : self.api.get('resource_id', ''), # 'httpMethod' : self.api.get('http_method', '')} # # def _get_method_args(self) -> Dict: # args = self._get_common_args() # args.update(self.api.get('method', {})) # return args # # def _get_integration_args(self) -> Dict: # integration_args = self.api.get('integration', {}) # uri_args = {'api_region': self.api.get('region', ''), # 'lambda_region': self.resources_info.get('lambda', {}).get('region', ''), # 'account_id': self.resources_info.get('iam', {}).get('account_id', ''), # 'function_name': self.resources_info.get('lambda', {}).get('name', '')} # integration_args['uri'] = integration_args['uri'].format(**uri_args) # args = self._get_common_args() # args.update(integration_args) # return args # # def _get_resource_id(self) -> str: # res_id = "" # resources_info = self.client.get_resources(self.api.get('id', '')) # for resource in resources_info['items']: # if resource['path'] == '/': # res_id = resource['id'] # break # return res_id # # def _set_api_gateway_id(self, api_info: Dict) -> None: # self.api['id'] = api_info.get('id', '') # # We store the parameter in the lambda configuration that # # is going to be uploaded to the Lambda service # self.resources_info['lambda']['environment']['Variables']['API_GATEWAY_ID'] = api_info.get('id', '') # # def _set_resource_info_id(self, resource_info: Dict) -> None: # self.api['resource_id'] = resource_info.get('id', '') # # def _get_endpoint(self) -> str: # endpoint_args = {'api_id': self.api.get('id', ''), # 'api_region': self.api.get('region', ''), # 'stage_name': self.api.get('stage_name', '')} # return self.api.get('endpoint', '').format(**endpoint_args) # # def create_api_gateway(self) -> None: # """Creates an Api Gateway endpoint.""" # api_info = self.client.create_rest_api(self.api.get('name', '')) # self._set_api_gateway_id(api_info) # resource_info = self.client.create_resource(self.api.get('id', ''), # self._get_resource_id(), # self.api.get('path_part', '')) # self._set_resource_info_id(resource_info) # self.client.create_method(**self._get_method_args()) # self.client.set_integration(**self._get_integration_args()) # self.client.create_deployment(self.api.get('id', ''), self.api.get('stage_name', '')) # logger.info(f'API Gateway endpoint: {self._get_endpoint()}') # # def delete_api_gateway(self) -> None: # """Deletes an Api Gateway endpoint.""" # return self.client.delete_rest_api(self.resources_info['lambda']['environment']['Variables']['API_GATEWAY_ID']) . Output only the next line.
ecr = APIGateway({})
Given the code snippet: <|code_start|> url = f'https://api.github.com/repos/{user}/{project}/releases/latest' response = request.get_file(url) if response: response = json.loads(response) return response.get('tag_name', '') else: return None @staticmethod def exists_release_in_repo(user: str, project: str, tag_name: str) -> bool: """Check if a tagged release exists in a repository.""" url = f'https://api.github.com/repos/{user}/{project}/releases/tags/{tag_name}' response = request.get_file(url) if not response: return False response = json.loads(response) if 'message' in response and response['message'] == 'Not Found': return False return True @staticmethod def get_asset_url(user: str, project: str, asset_name: str, tag_name: str='latest') -> Optional[str]: """Get the download asset url from the specified github tagged project.""" if tag_name == 'latest': url = f'https://api.github.com/repos/{user}/{project}/releases/latest' else: if GitHubUtils.exists_release_in_repo(user, project, tag_name): url = f'https://api.github.com/repos/{user}/{project}/releases/tags/{tag_name}' else: <|code_end|> , generate the next line using the imports in this file: import base64 import json import os import re import shutil import subprocess import tarfile import tempfile import uuid import sys import yaml import scar.logger as logger import scar.http.request as request from copy import deepcopy from zipfile import ZipFile from io import BytesIO from typing import Optional, Dict, List, Generator, Union, Any, Tuple from distutils import dir_util from packaging import version from scar.exceptions import GitHubTagNotFoundError, YamlFileNotFoundError and context (functions, classes, or occasionally code) from other files: # Path: scar/exceptions.py # class GitHubTagNotFoundError(ScarError): # """ # The specified tag was not found in the GitHub repository # # :ivar version: Tag used for the search # """ # # fmt = "The tag '{tag}' was not found in the GitHub repository." # # class YamlFileNotFoundError(ScarError): # """ # The yaml configuration file does not exist # # :ivar file_path: Path of the file # """ # fmt = "Unable to find the yaml file '{file_path}'" . Output only the next line.
raise GitHubTagNotFoundError(tag=tag_name)
Given the following code snippet before the placeholder: <|code_start|> tar.extractall(path=destination_path) @staticmethod def unzip_folder(zip_path: str, folder_where_unzip_path: str, msg: str='') -> None: """Must use the unzip binary to preserve the file properties and the symlinks.""" zip_exe = '/usr/bin/unzip' SysUtils.execute_command_with_msg([zip_exe, zip_path], cmd_wd=folder_where_unzip_path, cli_msg=msg) @staticmethod def zip_folder(zip_path: str, folder_to_zip_path: str, msg: str='') -> None: """Must use the zip binary to preserve the file properties and the symlinks.""" zip_exe = '/usr/bin/zip' SysUtils.execute_command_with_msg([zip_exe, '-r9y', zip_path, '.'], cmd_wd=folder_to_zip_path, cli_msg=msg) @staticmethod def is_file(file_path: str): """Test whether a path is a regular file.""" return os.path.isfile(file_path) @staticmethod def load_yaml(file_path: str) -> Dict: """Returns the content of a YAML file as a Dict.""" if os.path.isfile(file_path): with open(file_path) as cfg_file: return yaml.safe_load(cfg_file) else: <|code_end|> , predict the next line using imports from the current file: import base64 import json import os import re import shutil import subprocess import tarfile import tempfile import uuid import sys import yaml import scar.logger as logger import scar.http.request as request from copy import deepcopy from zipfile import ZipFile from io import BytesIO from typing import Optional, Dict, List, Generator, Union, Any, Tuple from distutils import dir_util from packaging import version from scar.exceptions import GitHubTagNotFoundError, YamlFileNotFoundError and context including class names, function names, and sometimes code from other files: # Path: scar/exceptions.py # class GitHubTagNotFoundError(ScarError): # """ # The specified tag was not found in the GitHub repository # # :ivar version: Tag used for the search # """ # # fmt = "The tag '{tag}' was not found in the GitHub repository." # # class YamlFileNotFoundError(ScarError): # """ # The yaml configuration file does not exist # # :ivar file_path: Path of the file # """ # fmt = "Unable to find the yaml file '{file_path}'" . Output only the next line.
raise YamlFileNotFoundError(file_path=file_path)
Next line prediction: <|code_start|> sys.path.append('..') class DataItem: def __init__(self, x, y, block, code_id): self.x = x self.y = y self.block = block self.code_id = code_id <|code_end|> . Use current file imports: (import numpy as np import random import torch.nn as nn import torch.autograd as autograd import torch.optim as optim import torch import matplotlib.pyplot as plt import statistics import pandas as pd import xml.etree.ElementTree as ET import itertools import sys import common_libs.utilities as ut from tqdm import tqdm from .data import Data) and context including class names, function names, or small code snippets from other files: # Path: learning/pytorch/data/data.py # class Data(object): # # """ # Main data object which extracts data from a database, partition it and gives out batches. # # """ # # # def __init__(self): #copy constructor # self.percentage = 80 # self.costs = dict() # # def extract_data(self, cnx, format, fields): # print 'extracting data' # self.raw_data = ut.get_data(cnx, format, fields) # self.fields = fields # # def read_meta_data(self): # # self.sym_dict,_ = ut.get_sym_dict() # self.offsets = ut.read_offsets() # # self.opcode_start = self.offsets[0] # self.operand_start = self.offsets[1] # self.int_immed = self.offsets[2] # self.float_immed = self.offsets[3] # self.mem_start = self.offsets[4] # # for i in range(self.opcode_start, self.mem_start): # self.costs[i] = 1 # # # def generate_costdict(self, maxnum): # for i in range(self.opcode_start, self.mem_start): # self.costs[i] = np.random.randint(1,maxnum) # # def prepare_data(self): # pass # # def generate_datasets(self): # size = len(self.data) # split = (size * self.percentage) // 100 # self.train = self.data[:split] # self.test = self.data[(split + 1):] # print 'train ' + str(len(self.train)) + ' test ' + str(len(self.test)) # # # def generate_batch(self, batch_size, partition=None): # if partition is None: # partition = (0, len(self.train)) # # # TODO: this seems like it would be expensive for a large data set # (start, end) = partition # population = range(start, end) # selected = random.sample(population,batch_size) # # self.batch = [] # for index in selected: # self.batch.append(self.train[index]) # # def plot_histogram(self, data): # # ys = list() # for item in data: # ys.append(item.y) # # plt.hist(ys, min(max(ys), 1000)) # plt.show() . Output only the next line.
class DataInstructionEmbedding(Data):
Given the code snippet: <|code_start|> DATA = dict( subject='Re: Saying Hello', from_='jdoe@machine.example', to=('smith@home.example',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(1997, 11, 21, 11, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 64800))), date_str='Fri, 21 Nov 1997 11:00:00 -0600', text='This is a reply to your reply.\r\n', html='', headers={'to': ('"Mary Smith: Personal Account" <smith@home.example>',), 'from': ('John Doe <jdoe@machine.example>',), 'subject': ('Re: Saying Hello',), 'date': ('Fri, 21 Nov 1997 11:00:00 -0600',), 'message-id': ('<abcd.1234@local.machine.tld>',), 'in-reply-to': ('<3456@example.net>',), 'references': ('<1234@local.machine.example> <3456@example.net>',)}, attachments=[], <|code_end|> , generate the next line using the imports in this file: import datetime from imap_tools import EmailAddress and context (functions, classes, or occasionally code) from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('John Doe', 'jdoe@machine.example', 'John Doe <jdoe@machine.example>'),
Given snippet: <|code_start|> DATA = dict( subject='Daily Data: D09.ZPH (Averaged data)', from_='status@sender.com', to=('data@email.com',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(2020, 11, 9, 14, 49, 7, tzinfo=datetime.timezone(datetime.timedelta(-1, 57600))), date_str='Mon, 09 Nov 2020 14:49:07 -0800 (PST)', text='Daily Data: D09.ZPH (Averaged data)\nEmail generated: 10/11/2020 00:04:03.765\nEmail sent: 10/11/2020 00:49:03.125', html='', headers={'message-id': ('<5fa9c763.1c69fb81.76d95.43d7@mx.google.com>',), 'date': ('Mon, 09 Nov 2020 14:49:07 -0800 (PST)',), 'mime-version': ('1.0',), 'from': ('"Sender" <status@sender.com>',), 'to': ('"Data Email" <data@email.com>',), 'subject': ('Daily Data: D09.ZPH (Averaged data)',), 'content-type': ('multipart/mixed; boundary=--boundary_20_d4727d16-8454-4fa4-9da0-950a95b2c962',)}, attachments=[ dict( filename='D09.ZPH.txt', content_id='', content_disposition='', content_type='application/octet-stream', payload=b'123', ), ], <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime from imap_tools import EmailAddress and context: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) which might include code, classes, or functions. Output only the next line.
from_values=EmailAddress('Sender', 'status@sender.com', 'Sender <status@sender.com>'),
Given the following code snippet before the placeholder: <|code_start|> DATA = dict( subject='Redacted', from_='redacted@flashmail.net', to=('redacted@Enron.com',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(1900, 1, 1, 0, 0), date_str='', text='', html='<p>foo</p>\n', headers={'from': ('<redacted@flashmail.net>',), 'subject': ('Redacted',), 'to': ('<redacted@Enron.com>',), 'message-id': ('<105647271315.NCV17523@x263.net>',), 'mime-version': ('1.0',), 'content-type': ('text/html;\n charset=utf-8',), 'content-disposition': ('=?utf-8?Q?invalid?=', '=?utf-8?Q?invalid?='), 'content-transfer-encoding': ('quoted-printable',)}, attachments=[], <|code_end|> , predict the next line using imports from the current file: import datetime from imap_tools import EmailAddress and context including class names, function names, and sometimes code from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('', 'redacted@flashmail.net', 'redacted@flashmail.net'),
Given snippet: <|code_start|> DATA = dict( subject='', from_='xxx@xxxx.xxx', to=('xxxxxxxxxxx@xxxx.xxxx.xxx',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(2005, 5, 10, 15, 27, 3, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400))), date_str='Tue, 10 May 2005 15:27:03 -0500', text="Test test. Hi. Waving. m\r\n\r\n----------------------------------------------------------------\r\nSent via Bell Mobility's Text Messaging service. \r\nEnvoy par le service de messagerie texte de Bell Mobilit.\r\n----------------------------------------------------------------\r\n", html='', headers={'return-path': ('<xxx@xxxx.xxx>',), 'received': ('from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx@Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500', 'from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx@Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500', 'from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx@Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500'), 'date': ('Tue, 10 May 2005 15:27:03 -0500',), 'from': ('xxx@xxxx.xxx',), 'sender': ('xxx@xxxx.xxx',), 'to': ('xxxxxxxxxxx@xxxx.xxxx.xxx',), 'message-id': ('<xxx@xxxx.xxx>',), 'x-original-to': ('xxxxxxxxxxx@xxxx.xxxx.xxx',), 'delivered-to': ('xxx@xxxx.xxx',), 'importance': ('normal',), 'content-type': ('text/plain; charset=us-ascii',)}, attachments=[], <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime from imap_tools import EmailAddress and context: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) which might include code, classes, or functions. Output only the next line.
from_values=EmailAddress('', 'xxx@xxxx.xxx', 'xxx@xxxx.xxx'),
Based on the snippet: <|code_start|> DATA = dict( subject='Saying Hello', from_='jdoe@machine.example', to=('mary@example.net',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(1997, 11, 21, 9, 55, 6, tzinfo=datetime.timezone(datetime.timedelta(-1, 64800))), date_str='Fri, 21 Nov 1997 09:55:06 -0600', text='This is a message just to say hello.\r\nSo, "Hello".\r\n', html='', headers={'from': ('John Doe <jdoe@machine.example>',), 'to': ('Mary Smith <mary@example.net>',), 'subject': ('Saying Hello',), 'date': ('Fri, 21 Nov 1997 09:55:06 -0600',), 'message-id': ('<1234@local.machine.example>',)}, attachments=[], <|code_end|> , predict the immediate next line with the help of imports: import datetime from imap_tools import EmailAddress and context (classes, functions, sometimes code) from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('John Doe', 'jdoe@machine.example', 'John Doe <jdoe@machine.example>'),
Based on the snippet: <|code_start|> DATA = dict( subject='', from_='john.q.public@example.com', to=('mary@example.net', 'jdoe@test.example'), cc=(), bcc=(), reply_to=(), date=datetime.datetime(2003, 7, 1, 10, 52, 37, tzinfo=datetime.timezone(datetime.timedelta(0, 7200))), date_str='Tue, 1 Jul 2003 10:52:37 +0200', text='Hi everyone.\r\n', html='', headers={'from': ('Joe Q. Public <john.q.public@example.com>',), 'to': ('Mary Smith <@machine.tld:mary@example.net>, , jdoe@test . example',), 'date': ('Tue, 1 Jul 2003 10:52:37 +0200',), 'message-id': ('<5678.21-Nov-1997@example.com>',)}, attachments=[], <|code_end|> , predict the immediate next line with the help of imports: import datetime from imap_tools import EmailAddress and context (classes, functions, sometimes code) from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('Joe Q. Public', 'john.q.public@example.com', 'Joe Q. Public <john.q.public@example.com>'),
Given the code snippet: <|code_start|> DATA = dict( subject='testing', from_='foo@example.com', to=('blah@example.com',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(2005, 6, 6, 22, 21, 22, tzinfo=datetime.timezone(datetime.timedelta(0, 7200))), date_str='Mon, 6 Jun 2005 22:21:22 +0200', text='This is the first part.\r\n', html='', headers={'mime-version': ('1.0 (Apple Message framework v730)',), 'content-type': ('multipart/mixed; boundary=Apple-Mail-13-196941151',), 'message-id': ('<9169D984-4E0B-45EF-82D4-8F5E53AD7012@example.com>',), 'from': ('foo@example.com',), 'subject': ('testing',), 'date': ('Mon, 6 Jun 2005 22:21:22 +0200',), 'to': ('blah@example.com',)}, attachments=[ dict( filename='', content_id='qbFGyPQAS8', content_disposition='inline', content_type='image/jpeg', payload=b"\x8d\xa9\xa2\xb1*\x86H\x86\xf7\r\x01\x07\x02\xa0\x800\x88\xda\x9a+1\x0b0\t\x06\x05+\x0e\x03\x02\x1a\x05\x000\x80\x06\t*\x86J6\xa6\x8a\xc1\x07\x01\x00\x00\xa0\x82\x05J0\x82\x05F0\x82\x04.\x8d\xa9\xa2\xb1\x02\x02\x04?\xbe\xbaD0\r\x06\t*\x88\xda\x9a+\r\x01\x01\x05\x05\x00011\x0b0\t\x06\x03U\x04\x06\x13\x02F6\xa6\x8a\xc0\n\x06\x03U\x04\n\x13\x03TDC1\x140\x12\x06\x8d\xa9\xa2\xb3\x13\x0bTDC OCES CH\xda\x9a+\r040229115901Z\x17\r06026\xa6\x8a\xc22901Z0\x81\x801\x0b0\t\x06\x03U\x04\x8d\xa9\xa2\xb0K1)0'\x06\x03U\x04\n\x13 H\xda\x9a+. organisatorisk tin6\xa6\x8a\xc4nin", ), ], <|code_end|> , generate the next line using the imports in this file: import datetime from imap_tools import EmailAddress and context (functions, classes, or occasionally code) from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('', 'foo@example.com', 'foo@example.com'),
Given the code snippet: <|code_start|> DATA = dict( subject='Impress your clients with a business phone��� ', from_='info@here2there-travelers-msgs.net', to=('anyone@YAHOO.COM',), cc=(), bcc=(), reply_to=('44.41.17.14.11.2010.1139.1.328.1477949.614@reply.here2there-travelers-msgs.net',), date=datetime.datetime(2010, 11, 14, 17, 41, 44, tzinfo=datetime.timezone.utc), date_str='Sun, 14 Nov 2010 17:41:44 +0000', text='', html='', headers={'x-ymail-umid': ('1_132725_AEe3iGIAAGS4TOAfWQ3foSiBC54',), 'x-apparently-to': ('anyone@yahoo.com via 98.136.183.71; Sun, 14 Nov 2010 09:41:45 -0800',), 'message-id': ('<201011141741.oAEHfiKs020181@app9.msg2u.net>',), 'mime-version': ('1.0',), 'content-transfer-encoding': ('binary',), 'content-type': ('multipart/alternative; boundary="_----------=_128975650412616235"',), 'x-mailer': ('MIME::Lite 3.020 (F2.73; T1.21; A1.77; B3.01; Q3.01)',), 'date': ('Sun, 14 Nov 2010 17:41:44 +0000',), 'from': ('Biz Phone Systems from EclipseMediaOnline\udcef\udcbf\udcbd\udcef\udcbf\udcbd <info@here2there-travelers-msgs.net>',), 'to': ('anyone@YAHOO.COM',), 'subject': ('Impress your clients with a business phone\udcef\udcbf\udcbd\udcef\udcbf\udcbd\udcef\udcbf\udcbd ',), 'reply-to': ('Biz Phone Systems from EclipseMediaOnline\udcef\udcbf\udcbd\udcef\udcbf\udcbd <44.41.17.14.11.2010.1139.1.328.1477949.614@reply.here2there-travelers-msgs.net>',)}, attachments=[], <|code_end|> , generate the next line using the imports in this file: import datetime from imap_tools import EmailAddress and context (functions, classes, or occasionally code) from other files: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) . Output only the next line.
from_values=EmailAddress('Biz Phone Systems from EclipseMediaOnline��', 'info@here2there-travelers-msgs.net', 'Biz Phone Systems from EclipseMediaOnline�� <info@here2there-travelers-msgs.net>'),
Given snippet: <|code_start|> DATA = dict( subject='Saying Hello', from_='jdoe@machine.example', to=('mary@example.net',), cc=(), bcc=(), reply_to=(), date=datetime.datetime(1997, 11, 21, 9, 55, 6, tzinfo=datetime.timezone(datetime.timedelta(-1, 64800))), date_str='Fri, 21 Nov 1997 09:55:06 -0600', text='This is a message just to say hello.\r\nSo, "Hello".\r\n', html='', headers={'received': ('from x.y.test\r\n by example.net\r\n via TCP\r\n with ESMTP\r\n id ABC12345\r\n for <mary@example.net>; 21 Nov 1997 10:05:43 -0600', 'from machine.example by x.y.test; 21 Nov 1997 10:01:22 -0600'), 'from': ('John Doe <jdoe@machine.example>',), 'to': ('Mary Smith <mary@example.net>',), 'subject': ('Saying Hello',), 'date': ('Fri, 21 Nov 1997 09:55:06 -0600',), 'message-id': ('<1234@local.machine.example>',)}, attachments=[], <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime from imap_tools import EmailAddress and context: # Path: imap_tools/utils.py # class EmailAddress: # """Parsed email address info""" # __slots__ = 'name', 'email', 'full' # # def __init__(self, name: str, email: str, full: str): # self.name = name # self.email = email # self.full = full # # def __repr__(self): # return "{}(name={}, email={}, full={})".format( # self.__class__.__name__, repr(self.name), repr(self.email), repr(self.full)) # # def __eq__(self, other): # return all(getattr(self, i) == getattr(other, i) for i in self.__slots__) which might include code, classes, or functions. Output only the next line.
from_values=EmailAddress('John Doe', 'jdoe@machine.example', 'John Doe <jdoe@machine.example>'),