Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
. Use current file imports:
(from estrategias.jogadores import Jogador)
and context including class names, function names, or small code snippets from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Continue the code snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
. Use current file imports:
from estrategias.jogadores import Jogador
and context (classes, functions, or code) from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Next line prediction: <|code_start|>
class Teste_Jogador(unittest.TestCase):
def setUp(self):
jogadores = [importlib.import_module("estrategias.{}".format(name)).MeuJogador() for _,name,_ in pkgutil.iter_modules(['estrategias'])]
<|code_end|>
. Use current file imports:
(import unittest
import pkgutil
import importlib
from estrategias.jogadores import Jogador, JogadorMaisEspertinho)
and context including class names, function names, or small code snippets from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
#
# class JogadorMaisEspertinho(Jogador):
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# escolhas = ['c' if x>0.8 else 'd' for x in reputacoes_dos_jogadores]
# return escolhas
. Output only the next line. | self.Jogadores = [JogadorMaisEspertinho(), Jogador()] + jogadores |
Predict the next line for this snippet: <|code_start|>
class Teste_Jogador(unittest.TestCase):
def setUp(self):
jogadores = [importlib.import_module("estrategias.{}".format(name)).MeuJogador() for _,name,_ in pkgutil.iter_modules(['estrategias'])]
<|code_end|>
with the help of current file imports:
import unittest
import pkgutil
import importlib
from estrategias.jogadores import Jogador, JogadorMaisEspertinho
and context from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
#
# class JogadorMaisEspertinho(Jogador):
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# escolhas = ['c' if x>0.8 else 'd' for x in reputacoes_dos_jogadores]
# return escolhas
, which may contain function names, class names, or code. Output only the next line. | self.Jogadores = [JogadorMaisEspertinho(), Jogador()] + jogadores |
Given snippet: <|code_start|>#-*- coding:utf-8 -*-
u"""
Created on 21/01/14
by fccoelho
license: GPL V3 or Later
"""
__docformat__ = 'restructuredtext en'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from estrategias.jogadores import Jogador
import random
and context:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
which might include code, classes, or functions. Output only the next line. | class MeuJogador(Jogador): |
Next line prediction: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
. Use current file imports:
(from .jogadores import Jogador)
and context including class names, function names, or small code snippets from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Using the snippet: <|code_start|># coding: utf8
"""
Jogador básico
O seu Jogador deve ser implementado como uma subclasse de Jogador,
porem com o seu nome (p.ex. JoseSilva) como nome a classe. A subclasse deve
reimplementar os métodos escolha_de_cacada, resultado_da_cacada e
"""
<|code_end|>
, determine the next line of code. You have imports:
from estrategias.jogadores import Jogador
import numpy as np
and context (class names, function names, or code) available:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Predict the next line after this snippet: <|code_start|>def somar(*valores):
soma = 0
for v in valores:
soma += v
return soma
def media(*valores):
soma = somar(*valores)
qtd_elementos = len(valores)
media = soma / float(qtd_elementos)
return media
def variancia(*valores):
_media = media(*valores)
soma = 0
_variancia = 0
for valor in valores:
soma += math.pow( (valor - _media), 2)
_variancia = soma / float( len(valores) )
return _variancia
def desvio_padrao(*valores):
return math.sqrt( variancia(*valores) )
<|code_end|>
using the current file's imports:
import math
from .jogadores import Jogador
and any relevant context from other files:
# Path: estrategias/jogadores.py
# class Jogador:
# def __init__(self):
# """
# Este metodo é executado quando o seu jogador for instanciado no início do jogo.
#
# Você pode adicionar outras variáveis a seu critério.
#
# Você não precisa definir comida ou reputação pois o Controlador do jogo vai manter o registro
# destas variáveis para cada jogador informando-as aos jogadores a cada rodada, através do método
# escolha_de_cacada.
#
#
# """
# self.comida = 0
# self.reputacao = 0
#
#
#
# def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
# """
# Método principal que executa a cada rodada.
# você precisa criar uma lista de escolhas onde 'c' significa escolher caçar e 'd' representa descansar
# as decisãoes podem usar todas as informações disponíveis, por exemplo, as reputações dos outros jogadores.
# rodada: inteiro que é a rodada em que você está
# comida_atual: inteiro com a comida que você tem
# reputacao_atual: float representando sua reputação atual
# m: inteiro que é um limiarde cooperação/caçada desta rodada.
# reputacoes_dos_jogadores: lista de floats com as reputações dos outros jogadores
# """
# escolhas = ['c' for x in reputacoes_dos_jogadores] # modifique com a sua próprio estratégia
# return escolhas
#
# def resultado_da_cacada(self, comida_ganha):
# """
# este método é chamado depois que todas as cacadas da rodada forem terminadas.
# comida_ganha é uma lista com inteiros representando a comida ganha em cada uma das caçadas feitas na rodada.
# Estes números podem ser negativos.
#
# Sua comida total é a soma destes números e a comida atual.
#
# adicione código para atualizar suas variáveis internas
# """
# pass
#
# def fim_da_rodada(self, recompensa, m, numero_de_cacadores):
# """
# Adicione código para alterar suas variaveis com base na cooperação que ocorreu na última rodada
# recompensa: Comida total que você recebeu de jogadores que cooperaram na ultima rodada.
# numero_de_cacadores: inteiro que é o numero de caçadores que cooperou com você na última rodada.
# """
# pass
. Output only the next line. | class MeuJogador(Jogador): |
Given snippet: <|code_start|>#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def pbkdf2(password, salt, count, key_length, prf):
'''Returns the result of the Password-Based Key Derivation Function 2.
prf - a psuedorandom function
See http://en.wikipedia.org/wiki/PBKDF2
'''
def f(block_number):
'''The function "f".'''
U = prf(password, salt + struct.pack('>L', block_number))
if count > 1:
U = [ c for c in U ]
for i in xrange(2, 1 + count):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import struct
from .util import block_xor
and context:
# Path: pycoind/util/pyscrypt/util.py
# def block_xor(source, source_start, dest, dest_start, length):
# '''Performs xor on arrays source and dest, storing the result back in dest.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = chr(ord(dest[dest_start + i]) ^ ord(source[source_start + i]))
which might include code, classes, or functions. Output only the next line. | block_xor(prf(password, ''.join(U)), 0, U, 0, len(U)) |
Based on the snippet: <|code_start|> # total sets of required keys
keys = [get_keys(i) for i in xrange(0, total)]
# create linearly independent immutable sets of keys
groups = []
for i in xrange(0, total):
group = []
for j in xrange(0, required):
group.append(keys[(i + j) % total][j])
groups.append(frozenset(group))
return tuple(groups)
def partial_combine_private_keys(private_keys, ignore_errors = False):
'''Returns the combined private key from the relevant private keys in
private_keys, or None if insufficient private keys are provided.
If ignore_errors (default is False), then any key that does not fit
with the rest of the keys will raise a ValueError.
This is EXPERIMENTAL, and may change in the future.'''
parts = dict()
required = None
checksum = None
# for each key...
for key in private_keys:
# ...convert private keys to binary form
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context (classes, functions, sometimes code) from other files:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
. Output only the next line. | private_key = decode_check(key) |
Based on the snippet: <|code_start|># level.
# Valid prefix is in the range [0x0ff7, 0x1002] for prefix 6C
# Valid prefix is in the range [0x113c, 0x1148] for prefix 6c
def partial_split_private_key(private_key, required, total):
'''Returns a partial split set of addresses, which needs required of the
total keys to recreate the original key.
The result is a list of sets of private keys, such that:
len(result) = total
len(result[n]) = required
result[n][i].startswith('6C') # (ie. each key has the prefix 6C)
To recreate the original key, the keys from the required number of sets
must be passed into partial_combine_private_keys.
This is EXPERIMENTAL, and may change in the future.'''
if required > total:
raise ValueError('required cannot be larger than total')
# calculate a checksum
checksum = sha256d(privkey_from_wif(private_key))[:4]
# encode the private key with extra information embedded
# (ie. this key's index, the required number of keys and a checksum)
def partial_encode_key(k, index):
pk = privkey_from_wif(k)
pk = '\x10\x01' + chr(index) + chr(required) + checksum + pk
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context (classes, functions, sometimes code) from other files:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
. Output only the next line. | return encode_check(pk) |
Using the snippet: <|code_start|># checksum, to maintain the length.
#
# Future Consideration - Compressed key-sets
#
# For the above Easter Egg Hunt example, a new format could be used to more
# efficiently encode a key-set into a QR code, since the checksum and required
# are identical for all keys within it. This could be done at the application
# level.
# Valid prefix is in the range [0x0ff7, 0x1002] for prefix 6C
# Valid prefix is in the range [0x113c, 0x1148] for prefix 6c
def partial_split_private_key(private_key, required, total):
'''Returns a partial split set of addresses, which needs required of the
total keys to recreate the original key.
The result is a list of sets of private keys, such that:
len(result) = total
len(result[n]) = required
result[n][i].startswith('6C') # (ie. each key has the prefix 6C)
To recreate the original key, the keys from the required number of sets
must be passed into partial_combine_private_keys.
This is EXPERIMENTAL, and may change in the future.'''
if required > total:
raise ValueError('required cannot be larger than total')
# calculate a checksum
<|code_end|>
, determine the next line of code. You have imports:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context (class names, function names, or code) available:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
. Output only the next line. | checksum = sha256d(privkey_from_wif(private_key))[:4] |
Using the snippet: <|code_start|># vanity address farm
# 3. Bob then uses his farm to find a private key PrivKeyB such that:
# get_address(PubKeyA, PrivKeyB).startswith('1Alice')
# 4. Bob can then give PrivKeyB to Alice
# 5. Alice computes the new private key PrivKeyVanity:
# combine_private_keys(PrivKeyA, PrivKeyB)
#
# The new private key PrivKeyVanity has an address beginning 1Alice, without
# Bob knowing what the new private key is. Only Alice, with PrivKeyVanity, can
# spend the address' funds.
__all__ = ['get_address', 'combine_private_keys']
def get_address(public_key, private_key, version = chr(0)):
'Returns the address generated by combiningn a public key and private key.'
# valid public key?
if len(public_key) != 65 or public_key[0] != chr(0x04):
raise ValueError('public key must be decompressed')
# the public key's elliptic curve point
x = string_to_number(public_key[1:1 + curve.baselen])
y = string_to_number(public_key[1 + curve.baselen:])
public_point = ellipticcurve.Point(curve.curve, x, y, curve.order)
# the private key's public key's elliptic curve point
<|code_end|>
, determine the next line of code. You have imports:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context (class names, function names, or code) available:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
. Output only the next line. | private_key = privkey_from_wif(private_key) |
Predict the next line for this snippet: <|code_start|> private_key = privkey_from_wif(private_key)
secexp = string_to_number(private_key)
private_point = curve.generator * secexp
# add them together
combined = public_point + private_point
# compute the new public key
x = number_to_string(combined.x(), curve.order)
y = number_to_string(combined.y(), curve.order)
key_combined = chr(0x04) + x + y
# return the public key's address
return publickey_to_address(key_combined, version = version)
def combine_private_keys(private_keys):
'Returns the private key generated by combining two private keys.'
# convert private keys to binary form
private_keys = [privkey_from_wif(k) for k in private_keys]
# decode the secret exponents
secexps = [string_to_number(k) for k in private_keys]
# add_mod them together
combined = sum(secexps) % curve.order
# convert into a wif encode key
private_key = number_to_string(combined, curve.order)
<|code_end|>
with the help of current file imports:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context from other files:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
, which may contain function names, class names, or code. Output only the next line. | return privkey_to_wif(private_key) |
Given the following code snippet before the placeholder: <|code_start|>
__all__ = ['get_address', 'combine_private_keys']
def get_address(public_key, private_key, version = chr(0)):
'Returns the address generated by combiningn a public key and private key.'
# valid public key?
if len(public_key) != 65 or public_key[0] != chr(0x04):
raise ValueError('public key must be decompressed')
# the public key's elliptic curve point
x = string_to_number(public_key[1:1 + curve.baselen])
y = string_to_number(public_key[1 + curve.baselen:])
public_point = ellipticcurve.Point(curve.curve, x, y, curve.order)
# the private key's public key's elliptic curve point
private_key = privkey_from_wif(private_key)
secexp = string_to_number(private_key)
private_point = curve.generator * secexp
# add them together
combined = public_point + private_point
# compute the new public key
x = number_to_string(combined.x(), curve.order)
y = number_to_string(combined.y(), curve.order)
key_combined = chr(0x04) + x + y
# return the public key's address
<|code_end|>
, predict the next line using imports from the current file:
import base64
from .base58 import decode_check, encode_check
from .hash import sha256d
from .ecdsa import SECP256k1 as curve
from .ecdsa import ellipticcurve
from .ecdsa.util import randrange, string_to_number, number_to_string
from .key import privkey_from_wif, privkey_to_wif, publickey_to_address
and context including class names, function names, and sometimes code from other files:
# Path: pycoind/util/base58.py
# def decode_check(payload):
# 'Returns the base58 decoded value, verifying the checksum.'
# payload = b58decode(payload, None)
# if payload and sha256d(payload[:-4])[:4] == payload[-4:]:
# return payload[:-4]
# return None
#
# def encode_check(payload):
# 'Returns the base58 encoding with a 4-byte checksum.'
#
# checksum = sha256d(payload)[:4]
# return b58encode(payload + checksum)
#
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
#
# Path: pycoind/util/key.py
# def privkey_from_wif(privkey, prefix = chr(0x80)):
# key = base58.decode_check(privkey)
# if prefix != key[0]:
# raise ValueError('wif private key has does not match prefix')
# if len(key) == 33:
# if privkey[0] != '5':
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:]
# elif len(key) == 34:
# if key[-1] != chr(0x01):
# raise ValueError('compressed wif private key missing compression bit')
# if privkey[0] not in ('L', 'K'):
# raise ValueError('uncompressed wif private key does not begin with 5')
# return key[1:-1]
# raise ValueError('invalid wif private key')
#
# def privkey_to_wif(privkey, prefix = chr(0x80)):
# return base58.encode_check(prefix + privkey)
#
# def publickey_to_address(publickey, version = chr(0)):
# return pubkeyhash_to_address(hash160(publickey), version)
. Output only the next line. | return publickey_to_address(key_combined, version = version) |
Given the following code snippet before the placeholder: <|code_start|># THE SOFTWARE.
# First we inject three functions to each of the modes of operations
#
# _can_consume(size)
# - Given a size, determine how many bytes could be consumed in
# a single call to either the decrypt or encrypt method
#
# _final_encrypt(data)
# - call and return encrypt on this (last) chunk of data,
# padding as necessary; this will always be at least 16
# bytes unless the total incoming input was less than 16
# bytes
#
# _final_decrypt(data)
# - same as _final_encrypt except for decrypt, for
# stripping off padding
#
# ECB and CBC are block-only ciphers
def _block_can_consume(self, size):
if size >= 16: return 16
return 0
# After padding, we may have more than one block
def _block_final_encrypt(self, data):
<|code_end|>
, predict the next line using imports from the current file:
from .aes import AESBlockModeOfOperation, AESSegmentModeOfOperation, AESStreamModeOfOperation
from .util import append_PKCS7_padding, strip_PKCS7_padding
and context including class names, function names, and sometimes code from other files:
# Path: pycoind/util/pyaes/util.py
# def append_PKCS7_padding(data):
# pad = 16 - (len(data) % 16)
# return data + pad * chr(pad)
#
# def strip_PKCS7_padding(data):
# if len(data) % 16 != 0:
# raise ValueError("invalid length")
#
# pad = ord(data[-1])
#
# if pad > 16:
# raise ValueError("invalid padding byte")
#
# return data[:-pad]
. Output only the next line. | data = append_PKCS7_padding(data) |
Given the code snippet: <|code_start|># _can_consume(size)
# - Given a size, determine how many bytes could be consumed in
# a single call to either the decrypt or encrypt method
#
# _final_encrypt(data)
# - call and return encrypt on this (last) chunk of data,
# padding as necessary; this will always be at least 16
# bytes unless the total incoming input was less than 16
# bytes
#
# _final_decrypt(data)
# - same as _final_encrypt except for decrypt, for
# stripping off padding
#
# ECB and CBC are block-only ciphers
def _block_can_consume(self, size):
if size >= 16: return 16
return 0
# After padding, we may have more than one block
def _block_final_encrypt(self, data):
data = append_PKCS7_padding(data)
if len(data) == 32:
return self.encrypt(data[:16]) + self.encrypt(data[16:])
return self.encrypt(data)
def _block_final_decrypt(self, data):
<|code_end|>
, generate the next line using the imports in this file:
from .aes import AESBlockModeOfOperation, AESSegmentModeOfOperation, AESStreamModeOfOperation
from .util import append_PKCS7_padding, strip_PKCS7_padding
and context (functions, classes, or occasionally code) from other files:
# Path: pycoind/util/pyaes/util.py
# def append_PKCS7_padding(data):
# pad = 16 - (len(data) % 16)
# return data + pad * chr(pad)
#
# def strip_PKCS7_padding(data):
# if len(data) % 16 != 0:
# raise ValueError("invalid length")
#
# pad = ord(data[-1])
#
# if pad > 16:
# raise ValueError("invalid padding byte")
#
# return data[:-pad]
. Output only the next line. | return strip_PKCS7_padding(self.decrypt(data)) |
Given the following code snippet before the placeholder: <|code_start|> "decode v into a string of len bytes"
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base ** i)
result = ''
while long_value >= 256:
(div, mod) = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]:
nPad += 1
else:
break
result = chr(0) * nPad + result
if length is not None and len(result) != length:
return None
return result
def encode_check(payload):
'Returns the base58 encoding with a 4-byte checksum.'
<|code_end|>
, predict the next line using imports from the current file:
from .hash import sha256d
and context including class names, function names, and sometimes code from other files:
# Path: pycoind/util/hash.py
# def sha256d(data):
# return sha256(sha256(data))
. Output only the next line. | checksum = sha256d(payload)[:4] |
Based on the snippet: <|code_start|>
for i in xrange(0, N): # ROMix - 2
array_overwrite(X, 0, V, i * (128 * r), 128 * r) # ROMix - 3
blockmix_salsa8(X, 0, 128 * r, r) # ROMix - 4
for i in xrange(0, N): # ROMix - 6
j = integerify(X, 0, r) & (N - 1) # ROMix - 7
block_xor(V, j * (128 * r), X, 0, 128 * r) # ROMix - 8(inner)
blockmix_salsa8(X, 0, 128 * r, r) # ROMix - 9(outer)
array_overwrite(X, 0, B, Bi, 128 * r) # ROMix - 10
def hash(password, salt, N, r, p, dkLen):
"""Returns the result of the scrypt password-based key derivation function.
Constraints:
r * p < (2 ** 30)
dkLen <= (((2 ** 32) - 1) * 32
N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...)
N, r, p must be positive
"""
# Scrypt implementation. Significant thanks to https://github.com/wg/scrypt
if N < 2 or (N & (N - 1)): raise ValueError('Scrypt N must be a power of 2 greater than 1')
# A psuedorandom function
prf = lambda k, m: hmac.new(key = k, msg = m, digestmod = hashlib.sha256).digest()
<|code_end|>
, predict the immediate next line with the help of imports:
import hashlib
import hmac
from .pbkdf2 import pbkdf2
from .util import array_overwrite, block_xor
and context (classes, functions, sometimes code) from other files:
# Path: pycoind/util/pyscrypt/pbkdf2.py
# def pbkdf2(password, salt, count, key_length, prf):
# '''Returns the result of the Password-Based Key Derivation Function 2.
# prf - a psuedorandom function
#
# See http://en.wikipedia.org/wiki/PBKDF2
# '''
#
# def f(block_number):
# '''The function "f".'''
#
# U = prf(password, salt + struct.pack('>L', block_number))
#
# if count > 1:
# U = [ c for c in U ]
# for i in xrange(2, 1 + count):
# block_xor(prf(password, ''.join(U)), 0, U, 0, len(U))
# U = ''.join(U)
#
# return U
#
# size = 0
#
# block_number = 0
# blocks = [ ]
#
# # The iterations
# while size < key_length:
# block_number += 1
# block = f(block_number)
#
# blocks.append(block)
# size += len(block)
#
# return ''.join(blocks)[:key_length]
#
# Path: pycoind/util/pyscrypt/util.py
# def array_overwrite(source, source_start, dest, dest_start, length):
# '''Overwrites the dest array with the source array.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = source[source_start + i]
#
# def block_xor(source, source_start, dest, dest_start, length):
# '''Performs xor on arrays source and dest, storing the result back in dest.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = chr(ord(dest[dest_start + i]) ^ ord(source[source_start + i]))
. Output only the next line. | B = [ c for c in pbkdf2(password, salt, 1, p * 128 * r, prf) ] |
Continue the code snippet: <|code_start|> for i in xrange(8, 0, -2):
R(x, 4, 0, 12, 7); R(x, 8, 4, 0, 9); R(x, 12, 8, 4, 13); R(x, 0, 12, 8, 18)
R(x, 9, 5, 1, 7); R(x, 13, 9, 5, 9); R(x, 1, 13, 9, 13); R(x, 5, 1, 13, 18)
R(x, 14, 10, 6, 7); R(x, 2, 14, 10, 9); R(x, 6, 2, 14, 13); R(x, 10, 6, 2, 18)
R(x, 3, 15, 11, 7); R(x, 7, 3, 15, 9); R(x, 11, 7, 3, 13); R(x, 15, 11, 7, 18)
R(x, 1, 0, 3, 7); R(x, 2, 1, 0, 9); R(x, 3, 2, 1, 13); R(x, 0, 3, 2, 18)
R(x, 6, 5, 4, 7); R(x, 7, 6, 5, 9); R(x, 4, 7, 6, 13); R(x, 5, 4, 7, 18)
R(x, 11, 10, 9, 7); R(x, 8, 11, 10, 9); R(x, 9, 8, 11, 13); R(x, 10, 9, 8, 18)
R(x, 12, 15, 14, 7); R(x, 13, 12, 15, 9); R(x, 14, 13, 12, 13); R(x, 15, 14, 13, 18)
# Coerce into nice happy 32-bit integers
B32 = [ make_int32(x[i] + B32[i]) for i in xrange(0, 16) ]
# Convert back to bytes
for i in xrange(0, 16):
B[i * 4 + 0] = chr((B32[i] >> 0) & 0xff)
B[i * 4 + 1] = chr((B32[i] >> 8) & 0xff)
B[i * 4 + 2] = chr((B32[i] >> 16) & 0xff)
B[i * 4 + 3] = chr((B32[i] >> 24) & 0xff)
def blockmix_salsa8(BY, Bi, Yi, r):
'''Blockmix; Used by SMix.'''
start = Bi + (2 * r - 1) * 64
X = [ BY[i] for i in xrange(start, start + 64) ] # BlockMix - 1
for i in xrange(0, 2 * r): # BlockMix - 2
block_xor(BY, i * 64, X, 0, 64) # BlockMix - 3(inner)
salsa20_8(X) # BlockMix - 3(outer)
<|code_end|>
. Use current file imports:
import hashlib
import hmac
from .pbkdf2 import pbkdf2
from .util import array_overwrite, block_xor
and context (classes, functions, or code) from other files:
# Path: pycoind/util/pyscrypt/pbkdf2.py
# def pbkdf2(password, salt, count, key_length, prf):
# '''Returns the result of the Password-Based Key Derivation Function 2.
# prf - a psuedorandom function
#
# See http://en.wikipedia.org/wiki/PBKDF2
# '''
#
# def f(block_number):
# '''The function "f".'''
#
# U = prf(password, salt + struct.pack('>L', block_number))
#
# if count > 1:
# U = [ c for c in U ]
# for i in xrange(2, 1 + count):
# block_xor(prf(password, ''.join(U)), 0, U, 0, len(U))
# U = ''.join(U)
#
# return U
#
# size = 0
#
# block_number = 0
# blocks = [ ]
#
# # The iterations
# while size < key_length:
# block_number += 1
# block = f(block_number)
#
# blocks.append(block)
# size += len(block)
#
# return ''.join(blocks)[:key_length]
#
# Path: pycoind/util/pyscrypt/util.py
# def array_overwrite(source, source_start, dest, dest_start, length):
# '''Overwrites the dest array with the source array.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = source[source_start + i]
#
# def block_xor(source, source_start, dest, dest_start, length):
# '''Performs xor on arrays source and dest, storing the result back in dest.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = chr(ord(dest[dest_start + i]) ^ ord(source[source_start + i]))
. Output only the next line. | array_overwrite(X, 0, BY, Yi + (i * 64), 64) # BlockMix - 4 |
Given the following code snippet before the placeholder: <|code_start|>
# Salsa... Time to dance.
for i in xrange(8, 0, -2):
R(x, 4, 0, 12, 7); R(x, 8, 4, 0, 9); R(x, 12, 8, 4, 13); R(x, 0, 12, 8, 18)
R(x, 9, 5, 1, 7); R(x, 13, 9, 5, 9); R(x, 1, 13, 9, 13); R(x, 5, 1, 13, 18)
R(x, 14, 10, 6, 7); R(x, 2, 14, 10, 9); R(x, 6, 2, 14, 13); R(x, 10, 6, 2, 18)
R(x, 3, 15, 11, 7); R(x, 7, 3, 15, 9); R(x, 11, 7, 3, 13); R(x, 15, 11, 7, 18)
R(x, 1, 0, 3, 7); R(x, 2, 1, 0, 9); R(x, 3, 2, 1, 13); R(x, 0, 3, 2, 18)
R(x, 6, 5, 4, 7); R(x, 7, 6, 5, 9); R(x, 4, 7, 6, 13); R(x, 5, 4, 7, 18)
R(x, 11, 10, 9, 7); R(x, 8, 11, 10, 9); R(x, 9, 8, 11, 13); R(x, 10, 9, 8, 18)
R(x, 12, 15, 14, 7); R(x, 13, 12, 15, 9); R(x, 14, 13, 12, 13); R(x, 15, 14, 13, 18)
# Coerce into nice happy 32-bit integers
B32 = [ make_int32(x[i] + B32[i]) for i in xrange(0, 16) ]
# Convert back to bytes
for i in xrange(0, 16):
B[i * 4 + 0] = chr((B32[i] >> 0) & 0xff)
B[i * 4 + 1] = chr((B32[i] >> 8) & 0xff)
B[i * 4 + 2] = chr((B32[i] >> 16) & 0xff)
B[i * 4 + 3] = chr((B32[i] >> 24) & 0xff)
def blockmix_salsa8(BY, Bi, Yi, r):
'''Blockmix; Used by SMix.'''
start = Bi + (2 * r - 1) * 64
X = [ BY[i] for i in xrange(start, start + 64) ] # BlockMix - 1
for i in xrange(0, 2 * r): # BlockMix - 2
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
import hmac
from .pbkdf2 import pbkdf2
from .util import array_overwrite, block_xor
and context including class names, function names, and sometimes code from other files:
# Path: pycoind/util/pyscrypt/pbkdf2.py
# def pbkdf2(password, salt, count, key_length, prf):
# '''Returns the result of the Password-Based Key Derivation Function 2.
# prf - a psuedorandom function
#
# See http://en.wikipedia.org/wiki/PBKDF2
# '''
#
# def f(block_number):
# '''The function "f".'''
#
# U = prf(password, salt + struct.pack('>L', block_number))
#
# if count > 1:
# U = [ c for c in U ]
# for i in xrange(2, 1 + count):
# block_xor(prf(password, ''.join(U)), 0, U, 0, len(U))
# U = ''.join(U)
#
# return U
#
# size = 0
#
# block_number = 0
# blocks = [ ]
#
# # The iterations
# while size < key_length:
# block_number += 1
# block = f(block_number)
#
# blocks.append(block)
# size += len(block)
#
# return ''.join(blocks)[:key_length]
#
# Path: pycoind/util/pyscrypt/util.py
# def array_overwrite(source, source_start, dest, dest_start, length):
# '''Overwrites the dest array with the source array.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = source[source_start + i]
#
# def block_xor(source, source_start, dest, dest_start, length):
# '''Performs xor on arrays source and dest, storing the result back in dest.'''
#
# for i in xrange(0, length):
# dest[dest_start + i] = chr(ord(dest[dest_start + i]) ^ ord(source[source_start + i]))
. Output only the next line. | block_xor(BY, i * 64, X, 0, 64) # BlockMix - 3(inner) |
Given the following code snippet before the placeholder: <|code_start|>
Args:
grid: The bilateral grid with shape (gh, gw, gd, gc).
guide: The guide image with shape (h, w).
codomain_tangent: The codomain tangent with shape (gh, gw, gc).
Returns:
The vector-Jacobian product codomain_tangent * J^T(grid, guide) with shape
(h, w) (the same as that of the primal `guide`).
"""
ii, jj = jnp.meshgrid(
jnp.arange(guide.shape[0]), jnp.arange(guide.shape[1]), indexing='ij')
scale_i = grid.shape[0] / guide.shape[0]
scale_j = grid.shape[1] / guide.shape[1]
grid_depth = grid.shape[2]
gif = (ii + 0.5) * scale_i
gjf = (jj + 0.5) * scale_j
gkf = guide * grid.shape[2]
# Compute trilinear interpolation weights without clamping.
gi0 = jnp.floor(gif - 0.5).astype(jnp.int32)
gj0 = jnp.floor(gjf - 0.5).astype(jnp.int32)
gk0 = jnp.floor(gkf - 0.5).astype(jnp.int32)
gi1 = gi0 + 1
gj1 = gj0 + 1
gk1 = gk0 + 1
<|code_end|>
, predict the next line using imports from the current file:
import jax
import jax.numpy as jnp
from .numerics import lerp_weight
from .numerics import smoothed_lerp_weight
from .numerics import smoothed_lerp_weight_grad
and context including class names, function names, and sometimes code from other files:
# Path: jax/numerics.py
# def lerp_weight(x, xs):
# """Linear interpolation weight from a sample at x to xs.
#
# Returns the linear interpolation weight of a "query point" at coordinate `x`
# with respect to a "sample" at coordinate `xs`.
#
# The integer coordinates `x` are at pixel centers.
# The floating point coordinates `xs` are at pixel edges.
# (OpenGL convention).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
#
# Returns:
# - 1 when x = xs.
# - 0 when |x - xs| > 1.
# """
# dx = x - xs
# abs_dx = abs(dx)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight(x, xs, eps=1e-8):
# """Smoothed version of `LerpWeight` with gradients more suitable for backprop.
#
# Let f(x, xs) = LerpWeight(x, xs)
# = max(1 - |x - xs|, 0)
# = max(1 - |dx|, 0)
#
# f is not smooth when:
# - |dx| is close to 0. We smooth this by replacing |dx| with
# SmoothedAbs(dx, eps) = sqrt(dx * dx + eps), which has derivative
# dx / sqrt(dx * dx + eps).
# - |dx| = 1. When smoothed, this happens when dx = sqrt(1 - eps). Like ReLU,
# We just ignore this (in the implementation below, when the floats are
# exactly equal, we choose the SmoothedAbsGrad path since it is more useful
# than returning a 0 gradient).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
# eps: a small number.
#
# Returns:
# max(1 - |dx|, 0) where |dx| is smoothed_abs(dx).
# """
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight_grad(x, xs, eps=1e-8):
# """Gradient of smoothed_lerp_weight."""
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# grad = smoothed_abs_grad(dx, eps)
# return jnp.where(abs_dx > 1, 0, grad)
. Output only the next line. | wi0 = lerp_weight(gi0 + 0.5, gif) |
Given the following code snippet before the placeholder: <|code_start|> Args:
guide: The guide image with shape (h, w).
grid_shape: The grid shape, an array-like containing [gh, gw, gd, gc].
Returns:
An (image_extent, grid_extent) array with the spatial weight for each
spatial and grid position.
"""
guide_padded = _symmetric_pad_ij(guide, grid_shape)
# Rescale `image` from [0, 1] to [0, grid_depth].
# These are the floating point k coordinates of each sample.
grid_depth = grid_shape[2]
gk_float = guide_padded * grid_depth
# Each sample with float value kf can splat onto locations:
# k0 = floor(kf - 0.5)
# k1 = ceil(kf - 0.5)
#
# The subtraction by 0.5 is necessary:
# - Grid samples are located at half-integer coordinates:
# k = 0 places its sample at kf = 0.5.
# - If kf = 1.4, the tent weight function is nonzero in the range [0.4, 1.4].
# Therefore, we need to splat to k0 = 0 and k1 = 1.
# - If kf = 1.9, the tent weight function is nonzero in the range [0.9, 1.9].
# Therefore, we need to splat to k0 = 1 and k1 = 2.
gk_floor = jnp.floor(gk_float - 0.5)
gk_ceil = jnp.ceil(gk_float - 0.5)
# Compute tent weights before clipping.
<|code_end|>
, predict the next line using imports from the current file:
import jax
import jax.numpy as jnp
from .numerics import lerp_weight
from .numerics import smoothed_lerp_weight
from .numerics import smoothed_lerp_weight_grad
and context including class names, function names, and sometimes code from other files:
# Path: jax/numerics.py
# def lerp_weight(x, xs):
# """Linear interpolation weight from a sample at x to xs.
#
# Returns the linear interpolation weight of a "query point" at coordinate `x`
# with respect to a "sample" at coordinate `xs`.
#
# The integer coordinates `x` are at pixel centers.
# The floating point coordinates `xs` are at pixel edges.
# (OpenGL convention).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
#
# Returns:
# - 1 when x = xs.
# - 0 when |x - xs| > 1.
# """
# dx = x - xs
# abs_dx = abs(dx)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight(x, xs, eps=1e-8):
# """Smoothed version of `LerpWeight` with gradients more suitable for backprop.
#
# Let f(x, xs) = LerpWeight(x, xs)
# = max(1 - |x - xs|, 0)
# = max(1 - |dx|, 0)
#
# f is not smooth when:
# - |dx| is close to 0. We smooth this by replacing |dx| with
# SmoothedAbs(dx, eps) = sqrt(dx * dx + eps), which has derivative
# dx / sqrt(dx * dx + eps).
# - |dx| = 1. When smoothed, this happens when dx = sqrt(1 - eps). Like ReLU,
# We just ignore this (in the implementation below, when the floats are
# exactly equal, we choose the SmoothedAbsGrad path since it is more useful
# than returning a 0 gradient).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
# eps: a small number.
#
# Returns:
# max(1 - |dx|, 0) where |dx| is smoothed_abs(dx).
# """
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight_grad(x, xs, eps=1e-8):
# """Gradient of smoothed_lerp_weight."""
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# grad = smoothed_abs_grad(dx, eps)
# return jnp.where(abs_dx > 1, 0, grad)
. Output only the next line. | wk_floor = smoothed_lerp_weight(gk_floor + 0.5, gk_float) |
Predict the next line after this snippet: <|code_start|> codomain_tangent: The codomain tangent with shape (gh, gw, gc).
Returns:
The vector-Jacobian product codomain_tangent * J^T(grid, guide) with shape
(h, w) (the same as that of the primal `guide`).
"""
ii, jj = jnp.meshgrid(
jnp.arange(guide.shape[0]), jnp.arange(guide.shape[1]), indexing='ij')
scale_i = grid.shape[0] / guide.shape[0]
scale_j = grid.shape[1] / guide.shape[1]
grid_depth = grid.shape[2]
gif = (ii + 0.5) * scale_i
gjf = (jj + 0.5) * scale_j
gkf = guide * grid.shape[2]
# Compute trilinear interpolation weights without clamping.
gi0 = jnp.floor(gif - 0.5).astype(jnp.int32)
gj0 = jnp.floor(gjf - 0.5).astype(jnp.int32)
gk0 = jnp.floor(gkf - 0.5).astype(jnp.int32)
gi1 = gi0 + 1
gj1 = gj0 + 1
gk1 = gk0 + 1
wi0 = lerp_weight(gi0 + 0.5, gif)
wi1 = lerp_weight(gi1 + 0.5, gif)
wj0 = lerp_weight(gj0 + 0.5, gjf)
wj1 = lerp_weight(gj1 + 0.5, gjf)
<|code_end|>
using the current file's imports:
import jax
import jax.numpy as jnp
from .numerics import lerp_weight
from .numerics import smoothed_lerp_weight
from .numerics import smoothed_lerp_weight_grad
and any relevant context from other files:
# Path: jax/numerics.py
# def lerp_weight(x, xs):
# """Linear interpolation weight from a sample at x to xs.
#
# Returns the linear interpolation weight of a "query point" at coordinate `x`
# with respect to a "sample" at coordinate `xs`.
#
# The integer coordinates `x` are at pixel centers.
# The floating point coordinates `xs` are at pixel edges.
# (OpenGL convention).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
#
# Returns:
# - 1 when x = xs.
# - 0 when |x - xs| > 1.
# """
# dx = x - xs
# abs_dx = abs(dx)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight(x, xs, eps=1e-8):
# """Smoothed version of `LerpWeight` with gradients more suitable for backprop.
#
# Let f(x, xs) = LerpWeight(x, xs)
# = max(1 - |x - xs|, 0)
# = max(1 - |dx|, 0)
#
# f is not smooth when:
# - |dx| is close to 0. We smooth this by replacing |dx| with
# SmoothedAbs(dx, eps) = sqrt(dx * dx + eps), which has derivative
# dx / sqrt(dx * dx + eps).
# - |dx| = 1. When smoothed, this happens when dx = sqrt(1 - eps). Like ReLU,
# We just ignore this (in the implementation below, when the floats are
# exactly equal, we choose the SmoothedAbsGrad path since it is more useful
# than returning a 0 gradient).
#
# Args:
# x: "Query" point position.
# xs: "Sample" position.
# eps: a small number.
#
# Returns:
# max(1 - |dx|, 0) where |dx| is smoothed_abs(dx).
# """
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# return jnp.maximum(1.0 - abs_dx, 0.0)
#
# Path: jax/numerics.py
# def smoothed_lerp_weight_grad(x, xs, eps=1e-8):
# """Gradient of smoothed_lerp_weight."""
# dx = x - xs
# abs_dx = smoothed_abs(dx, eps)
# grad = smoothed_abs_grad(dx, eps)
# return jnp.where(abs_dx > 1, 0, grad)
. Output only the next line. | dwk0 = grid_depth * smoothed_lerp_weight_grad(gk0 + 0.5, gkf) |
Predict the next line for this snippet: <|code_start|>try:
except ImportError: # py3
class TestHandlerBase(AsyncHTTPTestCase, LogTrapTestCase):
orig_func = BaseHandler.get_current_user
def tearDown(self):
BaseHandler.get_current_user = self.orig_func
super(TestHandlerBase, self).tearDown()
def get_app(self):
<|code_end|>
with the help of current file imports:
from mock import Mock
from urllib import urlencode
from urllib.parse import urlencode
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase
from amgut.webserver import AGWebApplication
from amgut.handlers.base_handlers import BaseHandler
and context from other files:
# Path: amgut/webserver.py
# class AGWebApplication(Application):
# def __init__(self):
# handlers = [
# (r"/static/(.*)", BaseStaticFileHandler, {"path": STATIC_PATH}),
# (r"/", MainHandler),
# (r"/db_error/", DBErrorHandler),
# (r"/auth/login/", AuthLoginHandler),
# (r"/auth/logout/", AuthLogoutHandler),
# (r"/auth/register/", AuthRegisterHandoutHandler),
# (r"/authed/help_request/", HelpRequestHandler),
# (r"/authed/addendum/", AddendumHandler),
# (r"/authed/new_participant/", NewParticipantHandler),
# (r"/authed/new_participant_overview/",
# NewParticipantOverviewHandler),
# (r"/authed/sample_overview/", SampleOverviewHandler),
# (r"/authed/add_sample_overview/", AddSampleOverviewHandler),
# (r"/authed/survey_main/", SurveyMainHandler),
# (r"/authed/human_survey/", HumanSurveyHandler),
# (r"/authed/human_survey_completed/", HumanSurveyCompletedHandler),
# (r"/authed/vspassthrough/", VioscreenPassthroughHandler),
# (r"/authed/secondary_survey/", SecondarySurveyHandler),
# (r"/authed/personal_microbiome_overview/",
# PersonalMicrobiomeOverviewHandler),
# (r"/authed/portal/", PortalHandler),
# (r"/authed/add_sample_human/", AddHumanSampleHandler),
# (r"/authed/add_sample_human_ffq/", AddHumanFFQHandler),
# (r"/authed/add_sample_animal/", AddAnimalSampleHandler),
# (r"/authed/add_sample_general/", AddGeneralSampleHandler),
# (r"/authed/change_password/", ChangePasswordHandler),
# (r"/authed/add_animal/", AnimalSurveyHandler),
# (r"/authed/open-humans/", OpenHumansHandler),
# (r"/authed/connect/open-humans/", OpenHumansLoginHandler),
# (r"/authed/download/(.*)", DownloadHandler),
# (r"/faq/", FAQHandler),
# (r"/introduction/", IntroductionHandler),
# (r"/participants/(.*)", ParticipantOverviewHandler),
# (r"/international_shipping/", InternationalHandler),
# (r"/check_participant_name/", CheckParticipantName),
# (r"/authed/taxa_summaries/(.*)", TaxaSummaryHandler),
# (r"/authed/basic_report/(.*)", BasicReportHandler),
# (r"/authed/interactive_report/(.*)", InteractiveReportHandler),
# (r"/retrieve_kitid/", KitIDHandler),
# (r"/forgot_password/", ForgotPasswordHandler),
# (r"/change_pass_verify/", ChangePassVerifyHandler),
# (r"/nojs/", NoJSHandler),
# # 404 PAGE MUST BE LAST IN THIS LIST!
# (r".*", NoPageHandler)
# ]
# settings = {
# "template_path": TEMPLATE_PATH,
# "debug": DEBUG,
# "cookie_secret": AMGUT_CONFIG.cookie_secret,
# # Currently the only login form is on the homepage
# "login_url": media_locale['SITEBASE'] + '/',
# }
# super(AGWebApplication, self).__init__(handlers, **settings)
, which may contain function names, class names, or code. Output only the next line. | self.app = AGWebApplication() |
Here is a snippet: <|code_start|>
new_survey = True
else:
new_survey = False
# If the participant already exists, stop them outright
if new_survey and \
ag_data.check_if_consent_exists(ag_login_id, participant_name):
errmsg = url_escape(tl['PARTICIPANT_EXISTS'] % participant_name)
url = sitebase + "/authed/portal/?errmsg=%s" % errmsg
self.redirect(url)
return
consent = {
'login_id': ag_login_id,
'participant_name': participant_name,
'participant_email': ag_login_info['email'],
'assent_obtainer': 'ANIMAL_SURVEY',
'parent_1_name': 'ANIMAL_SURVEY',
'parent_2_name': 'ANIMAL_SURVEY',
'survey_id': animal_survey_id,
'is_juvenile': True,
'deceased_parent': False,
'obtainer_name': 'ANIMAL_SURVEY',
'age_range': 'ANIMAL_SURVEY'
}
redis.hset(animal_survey_id, 'consent', dumps(consent))
redis.hset(animal_survey_id, 0, dumps(data))
redis.expire(animal_survey_id, 86400)
<|code_end|>
. Write the next line using the current file imports:
from urllib import urlencode
from json import dumps
from tornado.web import authenticated
from tornado.escape import url_escape
from tornado.websocket import WebSocketHandler
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.survey_supp import primary_animal_survey
from amgut.lib.util import make_survey_class, store_survey
from amgut.connections import ag_data, redis
from amgut import text_locale, media_locale
and context from other files:
# Path: amgut/lib/util.py
# def make_survey_class(group, survey_type):
# """Creates a form class for a group of questions
#
# The top-level attributes of the generated class correspond to the
# question_ids from amgut.lib.human_survey_supp structures
#
# Select fields are generated for questions that require a single response,
# and sets of checkboxes for questions that can have multiple responses
# """
# attrs = {}
# prompts = {}
# triggers = defaultdict(list)
# triggered = defaultdict(list)
#
# for q in group.questions:
# for eid, element in zip(q.interface_element_ids, q.interface_elements):
# attrs[eid] = element
# prompts[eid] = q.question
#
# if q.triggers:
# for triggered_id, triggering_responses in q.triggers.items():
# triggers[eid].extend(triggering_responses)
# triggered[eid].extend(group.id_to_eid[triggered_id])
#
# attrs['prompts'] = prompts
# attrs['triggers'] = triggers
# attrs['triggered'] = triggered
# attrs['supplemental_eids'] = group.supplemental_eids
#
# return type(survey_type, (Form,), attrs)
#
# def store_survey(survey, survey_id):
# """Store the survey
#
# Parameters
# ----------
# survey : amgut.lib.data_access.survey.Survey
# The corresponding survey
# survey_id : str
# The corresponding survey ID to retreive from redis
# """
# def get_survey_question_id(key):
# return int(key.split('_')[-2])
#
# data = redis.hgetall(survey_id)
# to_store = PartitionResponse(survey.question_types)
# consent_details = loads(data.pop('consent'))
#
# if 'existing' in data:
# data.pop('existing')
#
# for page in data:
# page_data = loads(data[page])
# questions = page_data['questions']
#
# for quest, resps in viewitems(questions):
# qid = get_survey_question_id(quest)
# qtype = survey.question_types[qid]
#
# if resps is None:
# resps = {-1} # unspecified multiple choice
# elif qtype in ['SINGLE', 'MULTIPLE']:
# resps = set([int(i) for i in resps])
# else:
# pass
#
# to_store[qid] = resps
#
# with_fk_inserts = []
# for qid, indices in viewitems(to_store.with_fk):
# question = survey.questions[qid]
#
# for idx in indices:
# resp = question.responses[idx] if idx != -1 else survey.unspecified
# with_fk_inserts.append((survey_id, qid, resp))
#
# without_fk_inserts = [(survey_id, qid, dumps(v))
# for qid, v in viewitems(to_store.without_fk)]
#
# survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)
, which may include functions, classes, or code. Output only the next line. | store_survey(primary_animal_survey, animal_survey_id) |
Continue the code snippet: <|code_start|>
class HumanSurveyCompletedHandler(BaseHandler):
@authenticated
def get(self):
human_survey_id = self.get_secure_cookie('completed_survey_id')
if human_survey_id is None:
self.clear_cookie('completed_survey_id')
self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
else:
consent_info = ag_data.getConsent(human_survey_id)
internal_surveys = ag_data.get_participants_surveys(
consent_info['ag_login_id'], consent_info['participant_name'])
surveys = [f(human_survey_id, consent_info, internal_surveys)
<|code_end|>
. Use current file imports:
from tornado.web import authenticated
from amgut.lib.util import external_surveys
from amgut.handlers.base_handlers import BaseHandler
from amgut import media_locale
from amgut.connections import ag_data
and context (classes, functions, or code) from other files:
# Path: amgut/lib/util.py
# class PartitionResponse(object):
# def __init__(self, question_types):
# def __setitem__(self, qid, value):
# def _store(self, d, qid, value):
# def make_survey_class(group, survey_type):
# def store_survey(survey, survey_id):
# def get_survey_question_id(key):
# def survey_vioscreen(survey_id, consent_info, internal_surveys=[]):
# def survey_asd(survey_id, consent_info, internal_surveys=[]):
# def survey_fermented(survey_id, consent_info, internal_surveys=[]):
# def survey_surf(survey_id, consent_info, internal_surveys=[]):
# def rollback(f):
# def test_inner(*args, **kwargs):
# def basejoin(base, url):
. Output only the next line. | for f in external_surveys] |
Here is a snippet: <|code_start|>
class SecondarySurveyHandler(BaseHandler):
sec_surveys = {'fermented': fermented_survey,
'surf': surf_survey,
'personal_microbiome': personal_microbiome_survey}
@authenticated
def get(self):
skid = self.current_user
survey_id = self.get_argument('survey', '')
survey_type = self.get_argument('type')
participant_name = url_unescape(self.get_argument('participant_name'))
sec_survey = self.sec_surveys[survey_type]
<|code_end|>
. Write the next line using the current file imports:
from urllib import urlencode
from tornado.escape import url_unescape
from json import dumps
from tornado.web import authenticated
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.survey_supp import (
fermented_survey, surf_survey, personal_microbiome_survey)
from amgut.lib.util import make_survey_class, store_survey
from amgut.connections import ag_data, redis
from amgut import text_locale, media_locale
and context from other files:
# Path: amgut/lib/util.py
# def make_survey_class(group, survey_type):
# """Creates a form class for a group of questions
#
# The top-level attributes of the generated class correspond to the
# question_ids from amgut.lib.human_survey_supp structures
#
# Select fields are generated for questions that require a single response,
# and sets of checkboxes for questions that can have multiple responses
# """
# attrs = {}
# prompts = {}
# triggers = defaultdict(list)
# triggered = defaultdict(list)
#
# for q in group.questions:
# for eid, element in zip(q.interface_element_ids, q.interface_elements):
# attrs[eid] = element
# prompts[eid] = q.question
#
# if q.triggers:
# for triggered_id, triggering_responses in q.triggers.items():
# triggers[eid].extend(triggering_responses)
# triggered[eid].extend(group.id_to_eid[triggered_id])
#
# attrs['prompts'] = prompts
# attrs['triggers'] = triggers
# attrs['triggered'] = triggered
# attrs['supplemental_eids'] = group.supplemental_eids
#
# return type(survey_type, (Form,), attrs)
#
# def store_survey(survey, survey_id):
# """Store the survey
#
# Parameters
# ----------
# survey : amgut.lib.data_access.survey.Survey
# The corresponding survey
# survey_id : str
# The corresponding survey ID to retreive from redis
# """
# def get_survey_question_id(key):
# return int(key.split('_')[-2])
#
# data = redis.hgetall(survey_id)
# to_store = PartitionResponse(survey.question_types)
# consent_details = loads(data.pop('consent'))
#
# if 'existing' in data:
# data.pop('existing')
#
# for page in data:
# page_data = loads(data[page])
# questions = page_data['questions']
#
# for quest, resps in viewitems(questions):
# qid = get_survey_question_id(quest)
# qtype = survey.question_types[qid]
#
# if resps is None:
# resps = {-1} # unspecified multiple choice
# elif qtype in ['SINGLE', 'MULTIPLE']:
# resps = set([int(i) for i in resps])
# else:
# pass
#
# to_store[qid] = resps
#
# with_fk_inserts = []
# for qid, indices in viewitems(to_store.with_fk):
# question = survey.questions[qid]
#
# for idx in indices:
# resp = question.responses[idx] if idx != -1 else survey.unspecified
# with_fk_inserts.append((survey_id, qid, resp))
#
# without_fk_inserts = [(survey_id, qid, dumps(v))
# for qid, v in viewitems(to_store.without_fk)]
#
# survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)
, which may include functions, classes, or code. Output only the next line. | survey_class = make_survey_class(sec_survey.groups[0], |
Given the code snippet: <|code_start|> def post(self):
skid = self.current_user
tl = text_locale['handlers']
ag_login_id = ag_data.get_user_for_kit(skid)
survey_id = self.get_argument('survey_id', None)
survey_type = self.get_argument('type')
participant_name = url_unescape(self.get_argument('participant_name'))
sitebase = media_locale['SITEBASE']
if not survey_id:
survey_id = ag_data.get_new_survey_id()
sec_survey = self.sec_surveys[survey_type]
survey_class = make_survey_class(sec_survey.groups[0],
survey_type='SecondarySurvey')
form = survey_class()
form.process(data=self.request.arguments)
data = {'questions': form.data}
consent = {
'login_id': ag_login_id,
'participant_name': participant_name,
'survey_id': survey_id,
'secondary': True
}
redis.hset(survey_id, 'consent', dumps(consent))
redis.hset(survey_id, 0, dumps(data))
redis.expire(survey_id, 86400)
<|code_end|>
, generate the next line using the imports in this file:
from urllib import urlencode
from tornado.escape import url_unescape
from json import dumps
from tornado.web import authenticated
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.survey_supp import (
fermented_survey, surf_survey, personal_microbiome_survey)
from amgut.lib.util import make_survey_class, store_survey
from amgut.connections import ag_data, redis
from amgut import text_locale, media_locale
and context (functions, classes, or occasionally code) from other files:
# Path: amgut/lib/util.py
# def make_survey_class(group, survey_type):
# """Creates a form class for a group of questions
#
# The top-level attributes of the generated class correspond to the
# question_ids from amgut.lib.human_survey_supp structures
#
# Select fields are generated for questions that require a single response,
# and sets of checkboxes for questions that can have multiple responses
# """
# attrs = {}
# prompts = {}
# triggers = defaultdict(list)
# triggered = defaultdict(list)
#
# for q in group.questions:
# for eid, element in zip(q.interface_element_ids, q.interface_elements):
# attrs[eid] = element
# prompts[eid] = q.question
#
# if q.triggers:
# for triggered_id, triggering_responses in q.triggers.items():
# triggers[eid].extend(triggering_responses)
# triggered[eid].extend(group.id_to_eid[triggered_id])
#
# attrs['prompts'] = prompts
# attrs['triggers'] = triggers
# attrs['triggered'] = triggered
# attrs['supplemental_eids'] = group.supplemental_eids
#
# return type(survey_type, (Form,), attrs)
#
# def store_survey(survey, survey_id):
# """Store the survey
#
# Parameters
# ----------
# survey : amgut.lib.data_access.survey.Survey
# The corresponding survey
# survey_id : str
# The corresponding survey ID to retreive from redis
# """
# def get_survey_question_id(key):
# return int(key.split('_')[-2])
#
# data = redis.hgetall(survey_id)
# to_store = PartitionResponse(survey.question_types)
# consent_details = loads(data.pop('consent'))
#
# if 'existing' in data:
# data.pop('existing')
#
# for page in data:
# page_data = loads(data[page])
# questions = page_data['questions']
#
# for quest, resps in viewitems(questions):
# qid = get_survey_question_id(quest)
# qtype = survey.question_types[qid]
#
# if resps is None:
# resps = {-1} # unspecified multiple choice
# elif qtype in ['SINGLE', 'MULTIPLE']:
# resps = set([int(i) for i in resps])
# else:
# pass
#
# to_store[qid] = resps
#
# with_fk_inserts = []
# for qid, indices in viewitems(to_store.with_fk):
# question = survey.questions[qid]
#
# for idx in indices:
# resp = question.responses[idx] if idx != -1 else survey.unspecified
# with_fk_inserts.append((survey_id, qid, resp))
#
# without_fk_inserts = [(survey_id, qid, dumps(v))
# for qid, v in viewitems(to_store.without_fk)]
#
# survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)
. Output only the next line. | store_survey(sec_survey, survey_id) |
Predict the next line after this snippet: <|code_start|> next_page_number = page_number + 1
if page_number >= 0:
form_data = surveys[page_number]()
form_data.process(data=self.request.arguments)
data = {'questions': form_data.data}
redis.hset(human_survey_id, page_number, dumps(data))
progress = int(100.0 * (page_number + 2) / (len(phs_groups) + 1))
# if this is not the last page, render the next page
if next_page_number < len(surveys):
the_form = surveys[next_page_number]()
existing_responses = redis.hget(human_survey_id, 'existing')
if existing_responses:
existing_responses = loads(existing_responses)
the_form = surveys[next_page_number](data=existing_responses)
title = phs_groups[next_page_number].name
self.render('human_survey.html', the_form=the_form,
skid=self.current_user, TITLE=title,
page_number=next_page_number,
progress=progress)
else:
# only get the cookie if you complete the survey
self.clear_cookie('human_survey_id')
self.set_secure_cookie('completed_survey_id', human_survey_id)
<|code_end|>
using the current file's imports:
from json import dumps, loads
from tornado.web import authenticated
from tornado.escape import url_escape
from amgut import media_locale, text_locale
from amgut.connections import ag_data, redis
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.util import store_survey, make_survey_class
from amgut.lib.survey_supp import primary_human_survey
from amgut.lib.mail import send_email
import logging
and any relevant context from other files:
# Path: amgut/lib/util.py
# def store_survey(survey, survey_id):
# """Store the survey
#
# Parameters
# ----------
# survey : amgut.lib.data_access.survey.Survey
# The corresponding survey
# survey_id : str
# The corresponding survey ID to retreive from redis
# """
# def get_survey_question_id(key):
# return int(key.split('_')[-2])
#
# data = redis.hgetall(survey_id)
# to_store = PartitionResponse(survey.question_types)
# consent_details = loads(data.pop('consent'))
#
# if 'existing' in data:
# data.pop('existing')
#
# for page in data:
# page_data = loads(data[page])
# questions = page_data['questions']
#
# for quest, resps in viewitems(questions):
# qid = get_survey_question_id(quest)
# qtype = survey.question_types[qid]
#
# if resps is None:
# resps = {-1} # unspecified multiple choice
# elif qtype in ['SINGLE', 'MULTIPLE']:
# resps = set([int(i) for i in resps])
# else:
# pass
#
# to_store[qid] = resps
#
# with_fk_inserts = []
# for qid, indices in viewitems(to_store.with_fk):
# question = survey.questions[qid]
#
# for idx in indices:
# resp = question.responses[idx] if idx != -1 else survey.unspecified
# with_fk_inserts.append((survey_id, qid, resp))
#
# without_fk_inserts = [(survey_id, qid, dumps(v))
# for qid, v in viewitems(to_store.without_fk)]
#
# survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)
#
# def make_survey_class(group, survey_type):
# """Creates a form class for a group of questions
#
# The top-level attributes of the generated class correspond to the
# question_ids from amgut.lib.human_survey_supp structures
#
# Select fields are generated for questions that require a single response,
# and sets of checkboxes for questions that can have multiple responses
# """
# attrs = {}
# prompts = {}
# triggers = defaultdict(list)
# triggered = defaultdict(list)
#
# for q in group.questions:
# for eid, element in zip(q.interface_element_ids, q.interface_elements):
# attrs[eid] = element
# prompts[eid] = q.question
#
# if q.triggers:
# for triggered_id, triggering_responses in q.triggers.items():
# triggers[eid].extend(triggering_responses)
# triggered[eid].extend(group.id_to_eid[triggered_id])
#
# attrs['prompts'] = prompts
# attrs['triggers'] = triggers
# attrs['triggered'] = triggered
# attrs['supplemental_eids'] = group.supplemental_eids
#
# return type(survey_type, (Form,), attrs)
. Output only the next line. | store_survey(primary_human_survey, human_survey_id) |
Continue the code snippet: <|code_start|> sample_time = DateTimeField(validators=[required("Required field")],
format='%I:%M %p')
notes = TextField('notes')
class AddHumanFFQHandler(BaseHandler):
@authenticated
def post(self):
self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
@authenticated
def get(self):
ag_login_id = ag_data.get_user_for_kit(self.current_user)
barcode = self.get_secure_cookie('barcode')
participant_name = self.get_secure_cookie('participant_name')
self.clear_cookie('barcode')
self.clear_cookie('participant_name')
if barcode is None or participant_name is None:
self.set_status(404)
self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
return
else:
barcode = escape.json_decode(barcode)
participant_name = escape.json_decode(participant_name)
new_survey_id = ag_data.get_new_survey_id()
ag_data.associate_barcode_to_survey_id(ag_login_id, participant_name,
barcode, new_survey_id)
ag_data.updateVioscreenStatus(new_survey_id, 0) # 0 -> not started
<|code_end|>
. Use current file imports:
from datetime import datetime
from wtforms import (Form, SelectField, DateField, DateTimeField, TextField,
HiddenField, validators)
from tornado.web import authenticated
from tornado import escape
from future.utils import viewitems
from amgut.connections import ag_data
from amgut.lib.util import survey_vioscreen
from amgut.handlers.base_handlers import BaseHandler
from amgut import media_locale
and context (classes, functions, or code) from other files:
# Path: amgut/lib/util.py
# def survey_vioscreen(survey_id, consent_info, internal_surveys=[]):
# """Return a formatted text block and URL for the external survey"""
# tl = text_locale['human_survey_completed.html']
# embedded_text = tl['SURVEY_VIOSCREEN']
# regcode = AMGUT_CONFIG.vioscreen_regcode
# url = ("https://vioscreen.com/remotelogin.aspx?Key=%s&RegCode=%s" %
# (url_escape(encrypt_key(survey_id)), regcode))
# return embedded_text % url
. Output only the next line. | dat = survey_vioscreen(new_survey_id, None, None) |
Using the snippet: <|code_start|> # assert outside the block so it works for AssertionError too !
assert success, "Callable did not raise an exception"
def expect_raises(except_cls, check_context=True):
return _expect_raises(except_cls, check_context=check_context)
def expect_raises_message(except_cls, msg, check_context=True):
return _expect_raises(except_cls, msg=msg, check_context=check_context)
def eq_ignore_whitespace(a, b, msg=None):
a = re.sub(r"^\s+?|\n", "", a)
a = re.sub(r" {2,}", " ", a)
b = re.sub(r"^\s+?|\n", "", b)
b = re.sub(r" {2,}", " ", b)
assert a == b, msg or "%r != %r" % (a, b)
_dialect_mods: Dict[Any, Any] = {}
def _get_dialect(name):
if name is None or name == "default":
return default.DefaultDialect()
else:
<|code_end|>
, determine the next line of code. You have imports:
import contextlib
import re
import sys
from typing import Any
from typing import Dict
from sqlalchemy import exc as sa_exc
from sqlalchemy import util
from sqlalchemy.engine import default
from sqlalchemy.testing.assertions import _expect_warnings
from sqlalchemy.testing.assertions import eq_ # noqa
from sqlalchemy.testing.assertions import is_ # noqa
from sqlalchemy.testing.assertions import is_false # noqa
from sqlalchemy.testing.assertions import is_not_ # noqa
from sqlalchemy.testing.assertions import is_true # noqa
from sqlalchemy.testing.assertions import ne_ # noqa
from sqlalchemy.util import decorator
from ..util import sqla_compat
and context (class names, function names, or code) available:
# Path: alembic/util/sqla_compat.py
# _CE = TypeVar("_CE", bound=Union["ColumnElement", "SchemaItem"])
# AUTOINCREMENT_DEFAULT = "auto"
# def _safe_int(value: str) -> Union[int, str]:
# def _ensure_scope_for_ddl(
# connection: Optional["Connection"],
# ) -> Iterator[None]:
# def _safe_begin_connection_transaction(
# connection: "Connection",
# ) -> "Transaction":
# def _get_connection_in_transaction(connection: Optional["Connection"]) -> bool:
# def _copy(schema_item: _CE, **kw) -> _CE:
# def _get_connection_transaction(
# connection: "Connection",
# ) -> Optional["Transaction"]:
# def _create_url(*arg, **kw) -> url.URL:
# def _connectable_has_table(
# connectable: "Connection", tablename: str, schemaname: Union[str, None]
# ) -> bool:
# def _exec_on_inspector(inspector, statement, **params):
# def _nullability_might_be_unset(metadata_column):
# def _server_default_is_computed(*server_default) -> bool:
# def _server_default_is_identity(*server_default) -> bool:
# def _table_for_constraint(constraint: "Constraint") -> "Table":
# def _columns_for_constraint(constraint):
# def _reflect_table(
# inspector: "Inspector", table: "Table", include_cols: None
# ) -> None:
# def _fk_spec(constraint):
# def _fk_is_self_referential(constraint: "ForeignKeyConstraint") -> bool:
# def _is_type_bound(constraint: "Constraint") -> bool:
# def _find_columns(clause):
# def _remove_column_from_collection(
# collection: "ColumnCollection", column: Union["Column", "ColumnClause"]
# ) -> None:
# def _textual_index_column(
# table: "Table", text_: Union[str, "TextClause", "ColumnElement"]
# ) -> Union["ColumnElement", "Column"]:
# def _copy_expression(expression: _CE, target_table: "Table") -> _CE:
# def replace(col):
# def __init__(self, table: "Table", text: "TextClause") -> None:
# def get_children(self):
# def _render_textual_index_column(
# element: _textual_index_element, compiler: "SQLCompiler", **kw
# ) -> str:
# def _render_literal_bindparam(
# element: _literal_bindparam, compiler: "SQLCompiler", **kw
# ) -> str:
# def _get_index_expressions(idx):
# def _get_index_column_names(idx):
# def _column_kwargs(col: "Column") -> Mapping:
# def _get_constraint_final_name(
# constraint: Union["Index", "Constraint"], dialect: Optional["Dialect"]
# ) -> Optional[str]:
# def _constraint_is_named(
# constraint: Union["Constraint", "Index"], dialect: Optional["Dialect"]
# ) -> bool:
# def _is_mariadb(mysql_dialect: "Dialect") -> bool:
# def _mariadb_normalized_version_info(mysql_dialect):
# def _insert_inline(table: Union["TableClause", "Table"]) -> "Insert":
# def create_mock_engine(url, executor, **kw): # type: ignore[misc]
# def _select(*columns, **kw) -> "Select":
# class _textual_index_element(sql.ColumnElement):
# class _literal_bindparam(BindParameter):
. Output only the next line. | d = sqla_compat._create_url(name).get_dialect()() |
Given the code snippet: <|code_start|>
_home = Path(__file__).parent.parent
def run_command(file):
res = subprocess.run(
[
sys.executable,
str((_home / "tools" / "write_pyi.py").relative_to(_home)),
"--stdout",
"--file",
file,
],
stdout=subprocess.PIPE,
cwd=_home,
encoding="utf-8",
)
return res
class TestStubFiles(TestBase):
__requires__ = ("stubs_test",)
def test_op_pyi(self):
res = run_command("op")
generated = res.stdout
expected = Path(alembic.__file__).parent / "op.pyi"
<|code_end|>
, generate the next line using the imports in this file:
from pathlib import Path
from alembic.testing import eq_
from alembic.testing import TestBase
import subprocess
import sys
import alembic
and context (functions, classes, or occasionally code) from other files:
# Path: alembic/testing/assertions.py
# def _assert_proper_exception_context(exception):
# def assert_raises(except_cls, callable_, *args, **kw):
# def assert_raises_context_ok(except_cls, callable_, *args, **kw):
# def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
# def assert_raises_message_context_ok(
# except_cls, msg, callable_, *args, **kwargs
# ):
# def _assert_raises(
# except_cls, callable_, args, kwargs, msg=None, check_context=False
# ):
# def _expect_raises(except_cls, msg=None, check_context=False):
# def expect_raises(except_cls, check_context=True):
# def expect_raises_message(except_cls, msg, check_context=True):
# def eq_ignore_whitespace(a, b, msg=None):
# def _get_dialect(name):
# def expect_warnings(*messages, **kw):
# def emits_python_deprecation_warning(*messages):
# def decorate(fn, *args, **kw):
# def expect_sqlalchemy_deprecated(*messages, **kw):
# def expect_sqlalchemy_deprecated_20(*messages, **kw):
# class _ErrorContainer:
#
# Path: alembic/testing/fixtures.py
# class TestBase(SQLAlchemyTestBase):
# is_sqlalchemy_future = False
#
# @testing.fixture()
# def ops_context(self, migration_context):
# with migration_context.begin_transaction(_per_migration=True):
# yield Operations(migration_context)
#
# @testing.fixture
# def migration_context(self, connection):
# return MigrationContext.configure(
# connection, opts=dict(transaction_per_migration=True)
# )
#
# @testing.fixture
# def connection(self):
# with config.db.connect() as conn:
# yield conn
. Output only the next line. | eq_(generated, expected.read_text()) |
Given the following code snippet before the placeholder: <|code_start|>
_home = Path(__file__).parent.parent
def run_command(file):
res = subprocess.run(
[
sys.executable,
str((_home / "tools" / "write_pyi.py").relative_to(_home)),
"--stdout",
"--file",
file,
],
stdout=subprocess.PIPE,
cwd=_home,
encoding="utf-8",
)
return res
<|code_end|>
, predict the next line using imports from the current file:
from pathlib import Path
from alembic.testing import eq_
from alembic.testing import TestBase
import subprocess
import sys
import alembic
and context including class names, function names, and sometimes code from other files:
# Path: alembic/testing/assertions.py
# def _assert_proper_exception_context(exception):
# def assert_raises(except_cls, callable_, *args, **kw):
# def assert_raises_context_ok(except_cls, callable_, *args, **kw):
# def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
# def assert_raises_message_context_ok(
# except_cls, msg, callable_, *args, **kwargs
# ):
# def _assert_raises(
# except_cls, callable_, args, kwargs, msg=None, check_context=False
# ):
# def _expect_raises(except_cls, msg=None, check_context=False):
# def expect_raises(except_cls, check_context=True):
# def expect_raises_message(except_cls, msg, check_context=True):
# def eq_ignore_whitespace(a, b, msg=None):
# def _get_dialect(name):
# def expect_warnings(*messages, **kw):
# def emits_python_deprecation_warning(*messages):
# def decorate(fn, *args, **kw):
# def expect_sqlalchemy_deprecated(*messages, **kw):
# def expect_sqlalchemy_deprecated_20(*messages, **kw):
# class _ErrorContainer:
#
# Path: alembic/testing/fixtures.py
# class TestBase(SQLAlchemyTestBase):
# is_sqlalchemy_future = False
#
# @testing.fixture()
# def ops_context(self, migration_context):
# with migration_context.begin_transaction(_per_migration=True):
# yield Operations(migration_context)
#
# @testing.fixture
# def migration_context(self, connection):
# return MigrationContext.configure(
# connection, opts=dict(transaction_per_migration=True)
# )
#
# @testing.fixture
# def connection(self):
# with config.db.connect() as conn:
# yield conn
. Output only the next line. | class TestStubFiles(TestBase): |
Continue the code snippet: <|code_start|> cls._add_proxied_attribute(methname, globals_, locals_, attr_names)
@classmethod
def _add_proxied_attribute(cls, methname, globals_, locals_, attr_names):
if not methname.startswith("_"):
meth = getattr(cls, methname)
if callable(meth):
locals_[methname] = cls._create_method_proxy(
methname, globals_, locals_
)
else:
attr_names.add(methname)
@classmethod
def _create_method_proxy(cls, name, globals_, locals_):
fn = getattr(cls, name)
def _name_error(name, from_):
raise NameError(
"Can't invoke function '%s', as the proxy object has "
"not yet been "
"established for the Alembic '%s' class. "
"Try placing this code inside a callable."
% (name, cls.__name__)
) from from_
globals_["_name_error"] = _name_error
translations = getattr(fn, "_legacy_translations", [])
if translations:
<|code_end|>
. Use current file imports:
import collections
import textwrap
import uuid
import warnings
from collections.abc import Iterable
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Tuple
from typing import TypeVar
from typing import Union
from sqlalchemy.util import asbool # noqa
from sqlalchemy.util import immutabledict # noqa
from sqlalchemy.util import memoized_property # noqa
from sqlalchemy.util import to_list # noqa
from sqlalchemy.util import unique_list # noqa
from .compat import inspect_getfullargspec
from .compat import string_types
and context (classes, functions, or code) from other files:
# Path: alembic/util/compat.py
# class EncodedIO(io.TextIOWrapper):
# def close(self) -> None:
# def importlib_metadata_get(group: str) -> Tuple[EntryPoint, ...]:
# def formatannotation_fwdref(annotation, base_module=None):
#
# Path: alembic/util/compat.py
# class EncodedIO(io.TextIOWrapper):
# def close(self) -> None:
# def importlib_metadata_get(group: str) -> Tuple[EntryPoint, ...]:
# def formatannotation_fwdref(annotation, base_module=None):
. Output only the next line. | spec = inspect_getfullargspec(fn) |
Predict the next line after this snippet: <|code_start|>def _with_legacy_names(translations):
def decorate(fn):
fn._legacy_translations = translations
return fn
return decorate
def rev_id() -> str:
return uuid.uuid4().hex[-12:]
@overload
def to_tuple(x: Any, default: tuple) -> tuple:
...
@overload
def to_tuple(x: None, default: _T = None) -> _T:
...
@overload
def to_tuple(x: Any, default: Optional[tuple] = None) -> tuple:
...
def to_tuple(x, default=None):
if x is None:
return default
<|code_end|>
using the current file's imports:
import collections
import textwrap
import uuid
import warnings
from collections.abc import Iterable
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Tuple
from typing import TypeVar
from typing import Union
from sqlalchemy.util import asbool # noqa
from sqlalchemy.util import immutabledict # noqa
from sqlalchemy.util import memoized_property # noqa
from sqlalchemy.util import to_list # noqa
from sqlalchemy.util import unique_list # noqa
from .compat import inspect_getfullargspec
from .compat import string_types
and any relevant context from other files:
# Path: alembic/util/compat.py
# class EncodedIO(io.TextIOWrapper):
# def close(self) -> None:
# def importlib_metadata_get(group: str) -> Tuple[EntryPoint, ...]:
# def formatannotation_fwdref(annotation, base_module=None):
#
# Path: alembic/util/compat.py
# class EncodedIO(io.TextIOWrapper):
# def close(self) -> None:
# def importlib_metadata_get(group: str) -> Tuple[EntryPoint, ...]:
# def formatannotation_fwdref(annotation, base_module=None):
. Output only the next line. | elif isinstance(x, string_types): |
Based on the snippet: <|code_start|> Represents an ecstatica ellipse
'''
def __init__(self, idx, flags, origin_lcl, centre_lcl, offset_lcl, halfaxes, rotation, colour, parent, actor):
'''
'''
ActorPartAncestor.__init__(self, idx, parent, actor, flags)
self.idx = idx
self._origin_lcl = origin_lcl
self.centre_lcl = centre_lcl
self.offset_lcl = offset_lcl
self._rotation = rotation
self._halfaxes = halfaxes
self._colour = colour
self.pSub = None
self.next_silbling = None
self.points = []
self.flags.registerName("unknown_pos_flag_2", 1)
self.flags.registerName("joint_is_loose", 4)
self.flags.registerName("is_2part_limb", 5)
self.flags.registerName("part_is_fixed", 6)
self.flags.registerName("unknown_rot_flag_200", 9)
self.flags.registerName("unknown_rot_flag_4000", 14)
<|code_end|>
, predict the immediate next line with the help of imports:
from .ActorPartAncestor import ActorPartAncestor
from .Flags import Flags
and context (classes, functions, sometimes code) from other files:
# Path: Ecstatica/ActorPartAncestor.py
# class ActorPartAncestor(object):
# '''
# This class is the common ancestor of Actor and Part. It could be possible that Ecstatica didn't actually
# use subclassing but had Part and Actor each have an instance of this class at offset 0x0h...no, that does not
# seem plausible.
# '''
#
# def __init__(self, index, parent, actor, flags):
# '''
# Constructor
# '''
# self.idx = index
# self.flags = Flags.Flags(flags) #there are 2 bytes of flags at offset +0x02h
#
# #self.matrix_gbl = (0, 0, 0, 0, 0, 0, 0, 0, 0) #rotation matrix into global coordinate system
# self.origin_lcl = (0, 0, 0) #translatin part into global coordinate system
# self.offset_lcl = (0, 0, 0)
#
# self.sub = None #points to another ActorPartAncestor, which can be an Actor or a Part
# self.actor = actor #points to the actor this object belongs to. For the actor himself, this pointer is None
# #(originally, in Ecstatica, it points to the actor objects itself)
# self.rotation = (0, 0, 0) #angles to describe the rotation of the object
# self.parent = parent
#
# self.primechild = None
# self.silblings = []
#
# self.typeinfo = None
#
# #Flags at Offset 0x02h
# flagnames = {"PartIsLoose": 4,
# "PartIs2PartLimb": 5,
# "PartIsFixed": 6,
# "PartFixedIKZAxis": 7} #Not certain yet what exactly this means
#
# def setFlags(self, flag_word):
# '''
# Activates all flags for which a 1 appears in the flag_word. Does NOT clear flags
#
# @param flag_word: Flags 0-15 to set
# '''
# for i in range(16):
# flagvalue = flag_word & (1 << i)
# if flagvalue == 1:
# self.flagnames[i] = True
#
# def clearFlags(self, flag_word):
# '''
# Clears all flags for which a 1 appears in the flag_word. Does NOT set flags
#
# @param flag_word: Flags 0-15 to clear
# '''
# for i in range(16):
# flagvalue = flag_word & (1 << i)
# if flagvalue == 1:
# self.flagnames[i] = False
#
# def addChild(self, childpart):
# assert childpart != None
# assert childpart.parent is self
# assert not childpart is self
#
# if self.primechild != None:
# self.primechild.addSilbling(childpart)
# else:
# self.primechild = childpart
#
# def _getChildren(self):
# if self.primechild == None:
# return []
# else:
# return [self.primechild, ] + self.primechild.silblings
#
# children = property(_getChildren)
#
# def addSilbling(self, silblingpart):
# assert silblingpart != None
# assert silblingpart.parent is self.parent
# assert not silblingpart is self
#
# self.silblings.append(silblingpart)
#
# Path: Ecstatica/Flags.py
# class Flags(object):
# '''
# Describes a 4byte field containing 32 flags
# '''
#
# def __init__(self, startval=None):
# if startval == None:
# startval = 0
# self.value = startval
#
# self._names = {} #in this dict we collect names for the entries to allow more intuitive access
#
# def __getitem__(self, idx):
# if type(idx) == str:
# assert idx in self.names.keys()
# idx = self._names[idx]
#
# assert idx >= 0 and idx < 32
# return self.value & (1 << idx)
#
# def __setitem__(self, idx, val):
# if type(idx) == str:
# assert idx in self.names.keys()
# idx = self._names[idx]
#
# assert idx >= 0 and idx < 32
# if val:
# self.value |= (1 << idx)
# else:
# self.value &= ~(1 << idx)
#
# def __str__(self):
# str = ""
# for i in range(32):
# str += str(self.value & (1 << i))
# return str
#
# def clear(self):
# self.value = 0
#
# def clearSelected(self, vals):
# self.value &= ~vals
#
# def setSelected(self, vals):
# self.value |= vals
#
# def registerName(self, name, entry):
# '''
# allows to register a name for a given entry
# '''
# if name in self.names.keys():
# raise KeyError("Name in use already: " + name + ":" + self._names[name])
# if entry in self.names.values():
# raise ValueError("Entry has name already: " + filter(lambda e: e[1] == entry, self._names.entries())[0] + ":" + entry)
#
# self._names[name] = entry
#
# def _getNames(self):
# return self._names
#
# def overwrite(self, newval):
# self.value = newval
#
# names = property(_getNames)
. Output only the next line. | self.updateflags = Flags() |
Given the following code snippet before the placeholder: <|code_start|>#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#More information about the license is provided in the LICENSE file.
def fantifyNameList(namelist):
stringlist = b""
for name in namelist:
stringlist += bytes(name, 'utf-8')
stringlist += struct.pack('b', 0)
stringlist += struct.pack('b', 0)
return stringlist
def fantifyEventList(eventlist):
'''
'''
#by default, we always construct a terminal event and attach it to the list
#but if the last event in the given list is already a NO_EVENT-event, we omit our own
attach_terminal_event = True
eventliststr = b""
for event in eventlist:
eventliststr += struct.pack(">hhhhh", event.event_type, event.index, event.value1, event.value2, event.value3)
if event.event_type == Event.ev_NEXT_SCENE and event.index != 0: #special case! We have to attach data
#eventliststr += struct.pack(">" + "".join(itertools.repeat("b", len(event.uk_data))), event.uk_data)
eventliststr += event.uk_data.encode("ascii")
eventliststr += struct.pack("b", 0)
<|code_end|>
, predict the next line using imports from the current file:
import struct
import itertools
import codecs
import unittest
from . import Fixpoint
from . import Event
from .Event import ev_NO_EVENT
from . import FantFile
from . import FANTLoad
and context including class names, function names, and sometimes code from other files:
# Path: Ecstatica/Event.py
# class EventType(object):
# class Event(object):
# class NextSceneEvent(Event):
# def __init__(self, typeid, index_type, value1_type, value2_type, value3_type, priority):
# def createEventFromTextData(index_text, event_type_name, value1_text, value2_text, value3_text):
# def __init__(self, index, event_type, value1, value2, value3):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __init__(self, index, value1, value2, value3, uk_data):
# def __str__(self):
# def extractEventVector3(event):
# def extractEventAngles3(event):
. Output only the next line. | elif event.event_type == Event.ev_NO_EVENT: |
Continue the code snippet: <|code_start|> evttype = struct.unpack(">h", fileobj.read(2))[0]
index = struct.unpack(">h", fileobj.read(2))[0]
value1 = struct.unpack(">h", fileobj.read(2))[0]
value2 = struct.unpack(">h", fileobj.read(2))[0]
value3 = struct.unpack(">h", fileobj.read(2))[0]
#There's a special case: ev_NEXT_SCENE
#This Event is directly followed by at least 25 bytes of data which are used to initialize
#a struc_19 object of the scene object
#We simply read in the data and attach it to the Event
if evttype == Event.ev_NEXT_SCENE:
#the additional data block is present only when index != 0
if index != 0:
#read in data
#The special data sections ends with a 0 byte
#We have to read in data until we reach that, thgouh -after 24 bytes - we're not storing anymore what we read in
uk_data = b""
char = fileobj.read(1)
length = 0
while ord(char) != 0:
if length >= 24:
break
uk_data += char
char = fileobj.read(1)
while ord(char) != 0:
print("exceeding char in NEXT_SCENE-Event:", ord(char))
char = fileobj.read(1)
#print "read attachment of length", len(uk_data)
else:
uk_data = b""
<|code_end|>
. Use current file imports:
import struct
import itertools
import os
import unittest
from . import Sound
from . import Code
from . import Event
from . import MapArea
from . import SectorSection
from . import Camera
from . import Fixpoint
from .Event import NextSceneEvent
from . import FantFile
and context (classes, functions, or code) from other files:
# Path: Ecstatica/Event.py
# class NextSceneEvent(Event):
# '''
# The ev_NEXT_SCENE-event is a special case.
# It has additional data attached to it.
# That's why we introduced a new class for that purpose
# '''
# def __init__(self, index, value1, value2, value3, uk_data):
# Event.__init__(self, index, ev_NEXT_SCENE, value1, value2, value3)
# self.uk_data = uk_data
#
# def __str__(self):
# return Event.__str__(self) + ", extra data:\"" + self.uk_data + "\""
. Output only the next line. | return NextSceneEvent(index, value1, value2, value3, uk_data) |
Given the code snippet: <|code_start|> self.actornameidxs = range(500)
self.actionnameidxs = range(1000)
self.scenenameidxs = range(1000)
self.codenameidxs = range(1500)
self.repertnameidxs = range(150)
self.soundnameidxs = range(500)
self.mapareanameidxs = range(100)
def __init__(self):
self.parts = []
self.actors = []
self.actions = []
self.scenes = []
self.points = []
self.triangles = []
self.repertoires = []
self.mapareas = []
self.codes = []
self.sounds = []
self.cameras = []
self.sectorsections = []
self.sectormap = None
self.actorevents = []
self.actionevents = []
self.sceneevents = []
self.repertoireevents = []
<|code_end|>
, generate the next line using the imports in this file:
from .Game import NamesDB
and context (functions, classes, or occasionally code) from other files:
# Path: Ecstatica/Game.py
# class NamesDB(object):
# def __init__(self, nametype):
# self.nametype = nametype
# self.indices = {}
# self.names = []
#
# def addName(self, name):
# '''
# Checks whether name is existing already in the DB and returns
# its index in this case. Otherwise it adds it to the DB and
# returns the new index
# '''
# if name in self.indices.keys():
# return self.indices[name]
# else:
# newindex = len(self.indices)
# self.indices[name] = newindex
# self.names.append(name)
# return newindex
#
# def addNames(self, namelist):
# '''
# Adds a list of names to the DB and returns a number of indices
# '''
# idxs = []
#
# for name in namelist:
# idxs.append(self.addName(name))
#
# return idxs
#
# def __getitem__(self, name):
# '''
# Overload [] operator
# '''
#
# return self.addName(name)
#
# def __len__(self):
# return len(self.names)
#
# def append(self, name):
# '''
# Imitate list operation "append"
# '''
#
# return self.addName(name)
#
# def __str__(self):
# liste=[]
# for entry in self.indices.keys():
# liste.append(entry)
# return "\n".join(liste)
#
# def __iter__(self):
# return self.names.__iter__()
#
# def __next__(self):
# return self.names.__next__()
#
# def __eq__(self, other):
# if self.nametype != other.nametype:
# print("Name type not equal")
# return False
# if self.indices != other.indices:
# print("indices not equal")
# return False
# if self.names != other.names:
# print("names not equal")
# return False
#
# return True
#
# def __ne__(self, other):
# return not self.__eq__(other)
. Output only the next line. | self.partnames = NamesDB("Part") |
Given snippet: <|code_start|>"""Test suite for asttools.references."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
@pytest.fixture
def node():
"""Get an ast.Assign node of 'x = 1'."""
return ast.Assign(
targets=[ast.Name(id='x', ctx=ast.Store())],
value=ast.Num(n=1)
)
def test_parent_references(node):
"""Test that parent references are added to child nodes."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
import pytest
from pycc.asttools import references
and context:
# Path: pycc/asttools/references.py
# def add_parent_references(node):
# def add_sibling_references(node):
# def copy_location(new_node, old_node):
# def get_top_node(node):
which might include code, classes, or functions. Output only the next line. | references.add_parent_references(node) |
Given the following code snippet before the placeholder: <|code_start|>
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
source = """
ONE = 1
TWO = 2
THREE = ONE + TWO
FOUR = THREE + ONE
FIVE = THREE + TWO
def return_const():
return FOUR
def return_var():
return FIVE
FIVE = FIVE + ONE
FIVE -= ONE
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
<|code_end|>
, predict the next line using imports from the current file:
import ast
import pytest
from pycc.asttools import parse
from pycc.optimizers import constant
and context including class names, function names, and sometimes code from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/optimizers/constant.py
# def _resolve_constant_value(name):
# def visit_Name(self, node):
# def visit_BinOp(self, node):
# def optimize(node):
# class ConstantInliner(visitor.NodeTransformer):
. Output only the next line. | return parse.parse(source) |
Next line prediction: <|code_start|>
source = """
ONE = 1
TWO = 2
THREE = ONE + TWO
FOUR = THREE + ONE
FIVE = THREE + TWO
def return_const():
return FOUR
def return_var():
return FIVE
FIVE = FIVE + ONE
FIVE -= ONE
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
return parse.parse(source)
def test_constant_inliner(node):
"""Test that constant values are inlined."""
<|code_end|>
. Use current file imports:
(import ast
import pytest
from pycc.asttools import parse
from pycc.optimizers import constant)
and context including class names, function names, or small code snippets from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/optimizers/constant.py
# def _resolve_constant_value(name):
# def visit_Name(self, node):
# def visit_BinOp(self, node):
# def optimize(node):
# class ConstantInliner(visitor.NodeTransformer):
. Output only the next line. | constant.optimize(node) |
Given the following code snippet before the placeholder: <|code_start|>
def looks_like_closure():
test_var = False
return test_var
import xyz
def uses_import():
return xyz
def has_arguments(xyz=None):
return xyz
fn_ref = some_closure
cls_ref = ClosureClass
built_in = repr
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from pycc.asttools import parse
from pycc.asttools import name
from pycc.asttools import visitor
and context including class names, function names, and sometimes code from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | return parse.parse(source) |
Predict the next line for this snippet: <|code_start|> return node.body[1]
@pytest.fixture
def cls_decl(node):
"""Get the declaration of a class."""
return node.body[2]
@pytest.fixture
def fn_use(node):
"""Get the usage of a function."""
return node.body[7].value
@pytest.fixture
def cls_use(node):
"""Get the usage of a class."""
return node.body[8].value
@pytest.fixture
def builtin_use(node):
"""Get the usage of a built-in name."""
return node.body[9].value
@pytest.fixture
def name_iter(node):
"""Get iterable of all names in the source."""
<|code_end|>
with the help of current file imports:
import pytest
from pycc.asttools import parse
from pycc.asttools import name
from pycc.asttools import visitor
and context from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
, which may contain function names, class names, or code. Output only the next line. | class TestVisitor(visitor.NodeVisitorIter, name.NameVisitorMixin): |
Predict the next line after this snippet: <|code_start|> return node.body[1]
@pytest.fixture
def cls_decl(node):
"""Get the declaration of a class."""
return node.body[2]
@pytest.fixture
def fn_use(node):
"""Get the usage of a function."""
return node.body[7].value
@pytest.fixture
def cls_use(node):
"""Get the usage of a class."""
return node.body[8].value
@pytest.fixture
def builtin_use(node):
"""Get the usage of a built-in name."""
return node.body[9].value
@pytest.fixture
def name_iter(node):
"""Get iterable of all names in the source."""
<|code_end|>
using the current file's imports:
import pytest
from pycc.asttools import parse
from pycc.asttools import name
from pycc.asttools import visitor
and any relevant context from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | class TestVisitor(visitor.NodeVisitorIter, name.NameVisitorMixin): |
Given the following code snippet before the placeholder: <|code_start|>"""Test suite for asttools.visitor."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
@pytest.fixture
def big_ast():
"""Generate a large AST."""
# Trickery to get the path of a near-by file.
file_path = os.path.join(
os.path.dirname(
os.path.realpath(__file__)
),
'test_name.py',
)
with open(file_path, 'r') as source_file:
<|code_end|>
, predict the next line using imports from the current file:
import ast
import functools
import timeit
import os
import pytest
from pycc.asttools import parse
from pycc.asttools import visitor
and context including class names, function names, and sometimes code from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | node = parse.parse(source_file.read()) |
Given the code snippet: <|code_start|> os.path.realpath(__file__)
),
'test_name.py',
)
with open(file_path, 'r') as source_file:
node = parse.parse(source_file.read())
# Duplicate the body several times.
for x in range(5):
node.body.extend(node.body)
return node
def test_visitor_out_performs_original(big_ast):
"""Ensure the non-recursive implementation is at least 2x faster."""
samples = 100
original_visitor = ast.NodeVisitor()
original_time = timeit.timeit(
functools.partial(
original_visitor.visit,
big_ast,
),
number=samples,
)
<|code_end|>
, generate the next line using the imports in this file:
import ast
import functools
import timeit
import os
import pytest
from pycc.asttools import parse
from pycc.asttools import visitor
and context (functions, classes, or occasionally code) from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | custom_visitor = visitor.NodeVisitor(big_ast) |
Continue the code snippet: <|code_start|> else:
return value
class ConstantInliner(visitor.NodeTransformer):
"""NodeTransformer which places constant values in-line."""
def visit_Name(self, node):
"""Replace ast.Name with a value if it is a constant reference."""
n = namewrap.Name(node)
# Skip if not loading the value from memory.
if not isinstance(node.ctx, ast.Load):
return node
# Skip if value is not constant.
if not n.constant or n.node is n.declaration:
return node
# Skip if the node represents the initial assignment.
if n.node is n.declaration:
return node
# Skip if the constant value cannot be found.
if n.source in (
<|code_end|>
. Use current file imports:
import ast
from ..asttools import name as nametools
from ..asttools import visitor
from ..astwrappers import name as namewrap
and context (classes, functions, or code) from other files:
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
#
# Path: pycc/astwrappers/name.py
# class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin):
# class Name(object):
# def visit(self):
# def __init__(self, node):
# def node(self):
# def declaration(self):
# def source(self):
# def token(self):
# def uses(self):
# def assignments(self):
# def constant(self):
# def __repr__(self):
# def __lt__(self, other):
# def __gt__(self, other):
# def __eq__(self, other):
# def __ne__(self, other):
# def __le__(self, other):
# def __ge__(self, other):
# def __hash__(self):
. Output only the next line. | nametools.NAME_SOURCE.BUILTIN, |
Given snippet: <|code_start|>from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
def _resolve_constant_value(name):
"""Get the AST node representing the constant value of a name."""
decl = name.declaration
if isinstance(decl, ast.Assign):
target = decl.targets[0]
value = decl.value
if isinstance(target, ast.Tuple) and isinstance(value, ast.Tuple):
for idx, elt in enumerate(target.elts):
if isinstance(elt, ast.Name) and elt.id == name.token:
return value.elts[idx]
else:
return value
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
from ..asttools import name as nametools
from ..asttools import visitor
from ..astwrappers import name as namewrap
and context:
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
#
# Path: pycc/astwrappers/name.py
# class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin):
# class Name(object):
# def visit(self):
# def __init__(self, node):
# def node(self):
# def declaration(self):
# def source(self):
# def token(self):
# def uses(self):
# def assignments(self):
# def constant(self):
# def __repr__(self):
# def __lt__(self, other):
# def __gt__(self, other):
# def __eq__(self, other):
# def __ne__(self, other):
# def __le__(self, other):
# def __ge__(self, other):
# def __hash__(self):
which might include code, classes, or functions. Output only the next line. | class ConstantInliner(visitor.NodeTransformer): |
Given the code snippet: <|code_start|>
def _resolve_constant_value(name):
"""Get the AST node representing the constant value of a name."""
decl = name.declaration
if isinstance(decl, ast.Assign):
target = decl.targets[0]
value = decl.value
if isinstance(target, ast.Tuple) and isinstance(value, ast.Tuple):
for idx, elt in enumerate(target.elts):
if isinstance(elt, ast.Name) and elt.id == name.token:
return value.elts[idx]
else:
return value
class ConstantInliner(visitor.NodeTransformer):
"""NodeTransformer which places constant values in-line."""
def visit_Name(self, node):
"""Replace ast.Name with a value if it is a constant reference."""
<|code_end|>
, generate the next line using the imports in this file:
import ast
from ..asttools import name as nametools
from ..asttools import visitor
from ..astwrappers import name as namewrap
and context (functions, classes, or occasionally code) from other files:
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
#
# Path: pycc/astwrappers/name.py
# class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin):
# class Name(object):
# def visit(self):
# def __init__(self, node):
# def node(self):
# def declaration(self):
# def source(self):
# def token(self):
# def uses(self):
# def assignments(self):
# def constant(self):
# def __repr__(self):
# def __lt__(self, other):
# def __gt__(self, other):
# def __eq__(self, other):
# def __ne__(self, other):
# def __le__(self, other):
# def __ge__(self, other):
# def __hash__(self):
. Output only the next line. | n = namewrap.Name(node) |
Based on the snippet: <|code_start|>"""Test suite for asttools.compiler."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
source = """
x = True
for y in range(10):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
return parse.parse(source)
def test_bytecode_compiler(node):
"""Ensure that bytecode can be generated without errors."""
compiler.ByteCodeCompiler()(node)
@pytest.mark.skipif(
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pycc import pycompat
from pycc.asttools import parse
from pycc.asttools import compiler
and context (classes, functions, sometimes code) from other files:
# Path: pycc/pycompat.py
# class VERSION(object):
# PY2 = VERSION.major == 2
# PY25 = PY2 and VERSION.minor == 5
# PY26 = PY2 and VERSION.minor == 6
# PY27 = PY2 and VERSION.minor == 7
# PY3 = not PY2
# PY31 = PY3 and VERSION.minor == 1
# PY32 = PY3 and VERSION.minor == 2
# PY33 = PY3 and VERSION.minor == 3
# PY34 = PY3 and VERSION.minor == 4
#
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/compiler.py
# def _code_to_bytecode_py2(code):
# def _code_to_bytecode_py3(code):
# def _code_to_bytecode_py34(code):
# def _code_to_bytecode(code):
# def __call__(self, node, location='<AST>'):
# def __call__(self, node):
# class ByteCodeCompiler(object):
# class SourceCodeCompiler(object):
. Output only the next line. | pycompat.PY3 and pycompat.VERSION.minor > 3, |
Here is a snippet: <|code_start|>"""Test suite for asttools.compiler."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
source = """
x = True
for y in range(10):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pycc import pycompat
from pycc.asttools import parse
from pycc.asttools import compiler
and context from other files:
# Path: pycc/pycompat.py
# class VERSION(object):
# PY2 = VERSION.major == 2
# PY25 = PY2 and VERSION.minor == 5
# PY26 = PY2 and VERSION.minor == 6
# PY27 = PY2 and VERSION.minor == 7
# PY3 = not PY2
# PY31 = PY3 and VERSION.minor == 1
# PY32 = PY3 and VERSION.minor == 2
# PY33 = PY3 and VERSION.minor == 3
# PY34 = PY3 and VERSION.minor == 4
#
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/compiler.py
# def _code_to_bytecode_py2(code):
# def _code_to_bytecode_py3(code):
# def _code_to_bytecode_py34(code):
# def _code_to_bytecode(code):
# def __call__(self, node, location='<AST>'):
# def __call__(self, node):
# class ByteCodeCompiler(object):
# class SourceCodeCompiler(object):
, which may include functions, classes, or code. Output only the next line. | return parse.parse(source) |
Continue the code snippet: <|code_start|>"""Test suite for asttools.compiler."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
source = """
x = True
for y in range(10):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
return parse.parse(source)
def test_bytecode_compiler(node):
"""Ensure that bytecode can be generated without errors."""
<|code_end|>
. Use current file imports:
import pytest
from pycc import pycompat
from pycc.asttools import parse
from pycc.asttools import compiler
and context (classes, functions, or code) from other files:
# Path: pycc/pycompat.py
# class VERSION(object):
# PY2 = VERSION.major == 2
# PY25 = PY2 and VERSION.minor == 5
# PY26 = PY2 and VERSION.minor == 6
# PY27 = PY2 and VERSION.minor == 7
# PY3 = not PY2
# PY31 = PY3 and VERSION.minor == 1
# PY32 = PY3 and VERSION.minor == 2
# PY33 = PY3 and VERSION.minor == 3
# PY34 = PY3 and VERSION.minor == 4
#
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/compiler.py
# def _code_to_bytecode_py2(code):
# def _code_to_bytecode_py3(code):
# def _code_to_bytecode_py34(code):
# def _code_to_bytecode(code):
# def __call__(self, node, location='<AST>'):
# def __call__(self, node):
# class ByteCodeCompiler(object):
# class SourceCodeCompiler(object):
. Output only the next line. | compiler.ByteCodeCompiler()(node) |
Given the following code snippet before the placeholder: <|code_start|>"""Test suite for asttools.scope."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
source = """
def test_func(d=None, *args, **kwargs):
return d, args, kwargs
class TestClass(object):
def test_method(self):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from pycc.asttools import parse
from pycc.asttools import scope
and context including class names, function names, and sometimes code from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
. Output only the next line. | return parse.parse(source) |
Given snippet: <|code_start|> pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
return parse.parse(source)
@pytest.fixture
def func_node(node):
"""Get the function AST node from the source."""
return node.body[0]
@pytest.fixture
def cls_node(node):
"""Get the class AST node from the source."""
return node.body[1]
@pytest.fixture
def method_node(node):
"""Get the function AST of the class method."""
return node.body[1].body[0]
def test_is_scope(node, func_node, cls_node, method_node):
"""Test that scopes are properly identified."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pycc.asttools import parse
from pycc.asttools import scope
and context:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
which might include code, classes, or functions. Output only the next line. | assert scope.is_scope(node) is True |
Using the snippet: <|code_start|> def node(self):
"""Get the raw ast.Name node."""
return self._node
@property
def declaration(self):
"""Get the first declaration of the Name."""
return self._declaration
@property
def source(self):
"""Get the asttools.name.NAME_SOURCE of the Name."""
return self._source
@property
def token(self):
"""Get the string which represents the Name."""
return self._node.id
@property
def uses(self):
"""Get an iterable of all uses of the name.
If the source is asttools.name.NAME_SOURCE.BUILTIN this iterable will
contain all uses of the name in the module. Otherwise only uses within
the lexical scope of the declaration are contained within the iterable.
"""
search_path = self._declaration_scope
if search_path is None:
<|code_end|>
, determine the next line of code. You have imports:
import ast
from ..asttools import references as reftools
from ..asttools import name as nametools
from ..asttools import scope as scopetools
from ..asttools import visitor as visitortools
and context (class names, function names, or code) available:
# Path: pycc/asttools/references.py
# def add_parent_references(node):
# def add_sibling_references(node):
# def copy_location(new_node, old_node):
# def get_top_node(node):
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | search_path = reftools.get_top_node(self._node) |
Based on the snippet: <|code_start|>"""Wrappers for ast.Name nodes."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
from ..asttools import references as reftools
from ..asttools import name as nametools
from ..asttools import scope as scopetools
from ..asttools import visitor as visitortools
and context (classes, functions, sometimes code) from other files:
# Path: pycc/asttools/references.py
# def add_parent_references(node):
# def add_sibling_references(node):
# def copy_location(new_node, old_node):
# def get_top_node(node):
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin): |
Here is a snippet: <|code_start|>
"""Visitor which produces Name objects."""
def visit(self):
"""Produce Name objects from a NameVisitorMixin."""
return (
Name(n)
for n in super(NameGenerator, self).visit()
)
class Name(object):
"""Wrapper for an ast.Name node for ease of use."""
__slots__ = (
'_node',
'_scope',
'_declaration',
'_declaration_scope',
'_source',
)
def __init__(self, node):
"""Initialize the object with as ast.Name node."""
if not isinstance(node, ast.Name):
raise TypeError("Node must be an ast.Name.")
self._node = node
<|code_end|>
. Write the next line using the current file imports:
import ast
from ..asttools import references as reftools
from ..asttools import name as nametools
from ..asttools import scope as scopetools
from ..asttools import visitor as visitortools
and context from other files:
# Path: pycc/asttools/references.py
# def add_parent_references(node):
# def add_sibling_references(node):
# def copy_location(new_node, old_node):
# def get_top_node(node):
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
, which may include functions, classes, or code. Output only the next line. | self._scope = scopetools.parent_scope(self._node) |
Given the following code snippet before the placeholder: <|code_start|>"""Wrappers for ast.Name nodes."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
<|code_end|>
, predict the next line using imports from the current file:
import ast
from ..asttools import references as reftools
from ..asttools import name as nametools
from ..asttools import scope as scopetools
from ..asttools import visitor as visitortools
and context including class names, function names, and sometimes code from other files:
# Path: pycc/asttools/references.py
# def add_parent_references(node):
# def add_sibling_references(node):
# def copy_location(new_node, old_node):
# def get_top_node(node):
#
# Path: pycc/asttools/name.py
# NAME_SOURCE = enum.Enum(('DEFINED', 'ADOPTED', 'IMPORTED', 'BUILTIN'))
# def declaration(node, start=None):
# def name_source(node, declared=None):
# def visit_Name(self, node):
# def visit_alias(self, node):
# def visit_FunctionDef(self, node):
# def visit_Global(self, node):
# def visit_arguments(self, node):
# def visit_arg(self, node):
# class NameVisitorMixin(object):
#
# Path: pycc/asttools/scope.py
# SCOPE_TYPE = enum.Enum(("MODULE", "FUNCTION", "CLASS"))
# def is_scope(node):
# def scope_type(node):
# def parent_scope(node):
# def child_scopes(node):
#
# Path: pycc/asttools/visitor.py
# class NodeVisitor(object):
# class NodeVisitorIter(NodeVisitor):
# class NodeTransformer(NodeVisitor):
# def __init__(self, node):
# def generic_visit(self, node):
# def visit(self):
# def visit(self):
# def __init__(self, *args, **kwargs):
# def modified(self):
# def _replace(self, new, old):
# def visit(self):
. Output only the next line. | class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin): |
Given the code snippet: <|code_start|>
def use_reference():
print(assign_once)
return reference_somewhere
read_with_global = 321
def read_global():
global read_with_global
return read_with_global
write_with_global = 98
def write_global():
global write_with_global
write_with_global = 89
from fake_module import imported_name
def function_name():
pass
class ClassName(object):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
<|code_end|>
, generate the next line using the imports in this file:
import functools
import pytest
from pycc.asttools import parse
from pycc.astwrappers import name
and context (functions, classes, or occasionally code) from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/astwrappers/name.py
# class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin):
# class Name(object):
# def visit(self):
# def __init__(self, node):
# def node(self):
# def declaration(self):
# def source(self):
# def token(self):
# def uses(self):
# def assignments(self):
# def constant(self):
# def __repr__(self):
# def __lt__(self, other):
# def __gt__(self, other):
# def __eq__(self, other):
# def __ne__(self, other):
# def __le__(self, other):
# def __ge__(self, other):
# def __hash__(self):
. Output only the next line. | return parse.parse(source) |
Here is a snippet: <|code_start|>read_with_global = 321
def read_global():
global read_with_global
return read_with_global
write_with_global = 98
def write_global():
global write_with_global
write_with_global = 89
from fake_module import imported_name
def function_name():
pass
class ClassName(object):
pass
"""
@pytest.fixture
def node():
"""Get as AST node from the source."""
return parse.parse(source)
def test_name_generator(node):
"""Test that name wrappers can be produced from an AST."""
<|code_end|>
. Write the next line using the current file imports:
import functools
import pytest
from pycc.asttools import parse
from pycc.astwrappers import name
and context from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/astwrappers/name.py
# class NameGenerator(visitortools.NodeVisitorIter, nametools.NameVisitorMixin):
# class Name(object):
# def visit(self):
# def __init__(self, node):
# def node(self):
# def declaration(self):
# def source(self):
# def token(self):
# def uses(self):
# def assignments(self):
# def constant(self):
# def __repr__(self):
# def __lt__(self, other):
# def __gt__(self, other):
# def __eq__(self, other):
# def __ne__(self, other):
# def __le__(self, other):
# def __ge__(self, other):
# def __hash__(self):
, which may include functions, classes, or code. Output only the next line. | names = name.NameGenerator(node).visit() |
Here is a snippet: <|code_start|> utils.register_extensions(parser)
return parser
PySource = collections.namedtuple('PySource', ('node', 'path'))
def abspath(path):
"""Resolve a path to an absolute path."""
return os.path.realpath(
os.path.expanduser(
os.path.expandvars(
path,
),
),
)
def load_dir(path):
"""Get an iterable of PySource from the given directory."""
for root, subdirs, files in os.walk(abspath(path)):
files = (abspath(os.path.join(root, fname)) for fname in files)
files = (fname for fname in files if fname.endswith('.py'))
for file_name in files:
with open(file_name, 'r') as file_handle:
source = file_handle.read()
<|code_end|>
. Write the next line using the current file imports:
import collections
import os
import sys
from ..asttools import parse
from .extensions import utils
and context from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/cli/extensions/utils.py
# def iter_extensions():
# def register_extensions(parser):
# def execute(args, node):
, which may include functions, classes, or code. Output only the next line. | yield PySource(parse.parse(source), file_name) |
Predict the next line after this snippet: <|code_start|>"""Common utilities for CLI modules."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
def register_arguments(parser):
"""Add arguments required for all CLI tools."""
parser.add_argument(
'--source',
required=True,
help='Path to load the Python source from.',
)
parser.add_argument(
'--destination',
required=False,
help='Path to place the optimized result or "stdout".',
)
<|code_end|>
using the current file's imports:
import collections
import os
import sys
from ..asttools import parse
from .extensions import utils
and any relevant context from other files:
# Path: pycc/asttools/parse.py
# def parse(source, filename='<unknown>', mode='exec'):
# """An ast.parse extension.
#
# This function behaves identically to the standard ast.parse except that it
# adds parent and sibling references to each node.
# """
# node = ast.parse(source, filename, mode)
# references.add_parent_references(node)
# references.add_sibling_references(node)
#
# return node
#
# Path: pycc/cli/extensions/utils.py
# def iter_extensions():
# def register_extensions(parser):
# def execute(args, node):
. Output only the next line. | utils.register_extensions(parser) |
Given snippet: <|code_start|>
query = pyes.MatchAllQuery()
if fulltext or title or description:
query = pyes.BoolQuery()
if fulltext: query.add_must(pyes.StringQuery(fulltext, default_operator=default_operator))
if title: query.add_must(pyes.StringQuery(title, search_fields=['title'], default_operator=default_operator))
if description: query.add_must(pyes.StringQuery(description, search_fields=['description'], default_operator=default_operator))
filters = []
if __name__:
filters.append(pyes.TermsFilter('__name__', __name__))
if _object_type:
filters.append(pyes.TermsFilter('_object_type', _object_type))
if _pub_state:
filters.append(pyes.TermsFilter('_pub_state', _pub_state))
if path_id:
# Convert ObjectIds to strings
filters.append(pyes.TermsFilter('_id_path', [str(x) for x in path_id]))
if viewable_only:
filters.append(pyes.TermsFilter('_view', security.effective_principals(self.request)))
if filters:
query = pyes.FilteredQuery(query, pyes.ANDFilter(filters))
search = pyes.Search(query=query, start=start, size=size, fields=fields)
if highlight_fields:
for field in highlight_fields:
search.add_highlight(field)
# FIXME: use new search() method???
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from folder import Folder
from article import Article
from pyramid import security
from bson.objectid import ObjectId
from cms import dbutil
from users import UserCollection, GroupCollection, User, generate_random_password
from trash import Trash
import permissions
import pyes
and context:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
which might include code, classes, or functions. Output only the next line. | return dbutil.get_es_conn(self.request).search_raw(search, dbutil.get_es_index_name(self.request), sort=sort or '_score') |
Using the snippet: <|code_start|>
class Collection(object):
""" A flat collection (corresponds to a MongoDB collection) of similar Objects,
each with a unique __name__ value.
Collection instances are NOT stored as MongoDB documents.
"""
_object_type = "collection"
def __init__(self, request, collection_name, child_class):
"""
collection_name - name of the MongoDB collection
child_class - the class used to construct children of this collection
"""
self.request = request
self._collection_name = collection_name
self._child_class = child_class
def _get_collection(self):
<|code_end|>
, determine the next line of code. You have imports:
from cms import dbutil
from cms.exceptions import Veto
import string
and context (class names, function names, or code) available:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/exceptions.py
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
. Output only the next line. | return dbutil.get_collection(self.request, self._collection_name) |
Next line prediction: <|code_start|>
# Avoid conflicting with view names.
RESERVED_NAMES = (
'add',
'delete',
'contents',
'rename',
'edit',
'workflow_transition',
'history',
'comment',
'local_roles',
'search',
'object_view',
)
ALLOWED_NAME_CHARACTERS = string.letters + string.digits + ".-_ "
def veto_child_name(self, name, unique=True):
if name is not None: name = name.strip()
if not name: return "Name may not be blank."
if name in self.RESERVED_NAMES: return "\"%s\" is a reserved name." % name
for ch in name:
if ch not in self.ALLOWED_NAME_CHARACTERS:
return "The character \"%s\" is not allowed in names." % ch
if unique and self.has_child(name): return "The name \"%s\" is already in use." % name
return None
def add_child(self, name, child):
error = self.veto_add_child(name, child)
<|code_end|>
. Use current file imports:
(from cms import dbutil
from cms.exceptions import Veto
import string)
and context including class names, function names, or small code snippets from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/exceptions.py
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
. Output only the next line. | if error: raise Veto(error) |
Given snippet: <|code_start|>
_object_type = "user"
_name_title = "Username"
def get_class_schema(cls, request=None):
schema = colander.SchemaNode(colander.Mapping())
schema.add(colander.SchemaNode(colander.String(), name='firstname', title='First name', widget=widgets.get_wide_text_widget()))
schema.add(colander.SchemaNode(colander.String(), name='lastname', title='Last name', widget=widgets.get_wide_text_widget()))
schema.add(colander.SchemaNode(colander.String(), name='email', title='E-mail address', validator=colander.Email(), widget=widgets.get_wide_text_widget()))
schema.add(colander.SchemaNode(deform.Set(allow_empty=True), name='groups', title='Groups', widget=deform.widget.CheckboxChoiceWidget(values=get_groups_vocabulary(request))))
schema.add(colander.SchemaNode(colander.Boolean(), name='active', title='Active account', description="A user must be active in able to log in. You can mark an account as inactive as an alternative to deleting the account.", default=True))
return schema
get_class_schema = classmethod(get_class_schema)
def _get_nonschema_mongo_save_document(self):
doc = Object._get_nonschema_mongo_save_document(self)
doc['encoded_password'] = self.encoded_password
doc['last_logged_in'] = self.last_logged_in
doc['sortable_fullname'] = self.sortable_fullname.lower() # a convenient single sort field for the user management page
return doc
def _load_nonschema_attributes(self, **kwargs):
Object._load_nonschema_attributes(self, **kwargs)
self.encoded_password = kwargs.get('encoded_password', '')
self.last_logged_in = kwargs.get('last_logged_in', None)
def set_password(self, password):
self.encoded_password = self.encode_password(password)
def set_last_logged_in(self, timestamp=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collection import Collection
from object import Object
from cms.dateutil import utcnow
from hashlib import sha1
from pyramid.traversal import find_root
from pyramid_mailer import get_mailer
from pyramid_mailer.message import Message
import colander, deform
import random
import widgets
import permissions
and context:
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
which might include code, classes, or functions. Output only the next line. | if not timestamp: timestamp = utcnow() |
Based on the snippet: <|code_start|> names.append(name)
self._ordered_names = names
self.save()
def delete_child(self, name):
Collection.delete_child(self, name)
self._child_removed(name)
def _child_removed(self, name):
names = self.get_ordered_names()
if (names is not None) and (name in names):
names.remove(name)
self._ordered_names = names
self.save()
def rename_child(self, name, newname, _validate=True):
if Collection.rename_child(self, name, newname, _validate=_validate):
names = self.get_ordered_names()
if names is not None:
idx = names.index(name)
names[idx] = newname
self._ordered_names = names
self.save()
return 1
else:
return 0
def reorder_names_up(self, names_to_reorder, delta=1):
names = self.get_ordered_names()
if names is None: raise NonOrderedFolderException()
<|code_end|>
, predict the immediate next line with the help of imports:
from content import Content
from collection import Collection
from pyramid import security
from cms import orderutil
from cms.exceptions import NonOrderedFolderException, Veto
import colander, deform
import widgets
and context (classes, functions, sometimes code) from other files:
# Path: cms/orderutil.py
# def reorder_ids_by_delta(all_ids, ids_to_reorder, delta):
# def reorder_ids_up(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_down(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_to_top(all_ids, ids_to_reorder):
# def reorder_ids_to_bottom(all_ids, ids_to_reorder):
#
# Path: cms/exceptions.py
# class NonOrderedFolderException(Exception):
# """ Raised by some Folder methods when an attempt is made to call some method that depends
# on ordering, but the given folder is unordered.
# """
# def __init__(self):
# Exception.__init__(self, "This folder doesn't support ordering.")
#
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
. Output only the next line. | reordered_names = orderutil.reorder_ids_up(names, names_to_reorder, delta) |
Continue the code snippet: <|code_start|> if getattr(self.request, '_filter_unauth_traversal', False) and not security.authenticated_userid(self.request):
child = self.get_viewable_child(name)
else:
child = self.get_child(name)
if child is None:
raise KeyError
return child
def get_viewable_children_and_total(self, spec=None, sort=None, skip=0, limit=0):
spec = self._add_view_to_spec(spec)
return Collection.get_children_and_total(self, spec=spec, sort=sort, skip=skip, limit=limit)
def get_viewable_children(self, spec=None, sort=None, skip=0, limit=0):
spec = self._add_view_to_spec(spec)
return Collection.get_children(self, spec=spec, sort=sort, skip=skip, limit=limit)
def get_viewable_child_names_and_total(self, spec=None, sort=None, skip=0, limit=0):
spec = self._add_view_to_spec(spec)
return Collection.get_child_names_and_total(self, spec=spec, sort=sort, skip=skip, limit=limit)
def get_viewable_child_names(self, spec=None, sort=None, skip=0, limit=0):
spec = self._add_view_to_spec(spec)
return Collection.get_child_names(self, spec=spec, sort=sort, skip=skip, limit=limit)
def get_viewable_children_lazily(self, spec=None, sort=None):
spec = self._add_view_to_spec(spec)
return Collection.get_children_lazily(self, spec=spec, sort=sort)
def get_ordered_children(self):
names = self.get_ordered_names()
<|code_end|>
. Use current file imports:
from content import Content
from collection import Collection
from pyramid import security
from cms import orderutil
from cms.exceptions import NonOrderedFolderException, Veto
import colander, deform
import widgets
and context (classes, functions, or code) from other files:
# Path: cms/orderutil.py
# def reorder_ids_by_delta(all_ids, ids_to_reorder, delta):
# def reorder_ids_up(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_down(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_to_top(all_ids, ids_to_reorder):
# def reorder_ids_to_bottom(all_ids, ids_to_reorder):
#
# Path: cms/exceptions.py
# class NonOrderedFolderException(Exception):
# """ Raised by some Folder methods when an attempt is made to call some method that depends
# on ordering, but the given folder is unordered.
# """
# def __init__(self):
# Exception.__init__(self, "This folder doesn't support ordering.")
#
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
. Output only the next line. | if names is None: raise NonOrderedFolderException() |
Given the following code snippet before the placeholder: <|code_start|> attempt = 0
while 1:
if attempt:
candidate = "%s%s%s%s" % (name, sep, attempt, suffix)
else:
candidate = name+suffix
if not self.has_child(candidate):
return candidate
attempt += 1
def veto_add_child(self, name, child, unique=True):
# Return an error message (string) if there's any reason why the specified child can't be added with the specified name.
# Otherwise return None
if child._object_type not in self._allowed_child_types:
return "This %s does not allow child objects of type %s." % (self._object_type, child._object_type)
error = Collection.veto_add_child(self, name, child, unique=unique)
if error: return error
return None
def veto_move_child(self, obj):
if obj._id == self._id:
return "Can't move an object into itself."
if obj._id in self.get_id_path():
return "Can't move an object into a child of itself."
return self.veto_add_child(obj.__name__, obj)
def move_child(self, obj):
""" Move an object into this folder. """
if obj.__parent__._id == self._id: return 0
error = self.veto_move_child(obj)
<|code_end|>
, predict the next line using imports from the current file:
from content import Content
from collection import Collection
from pyramid import security
from cms import orderutil
from cms.exceptions import NonOrderedFolderException, Veto
import colander, deform
import widgets
and context including class names, function names, and sometimes code from other files:
# Path: cms/orderutil.py
# def reorder_ids_by_delta(all_ids, ids_to_reorder, delta):
# def reorder_ids_up(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_down(all_ids, ids_to_reorder, delta=1):
# def reorder_ids_to_top(all_ids, ids_to_reorder):
# def reorder_ids_to_bottom(all_ids, ids_to_reorder):
#
# Path: cms/exceptions.py
# class NonOrderedFolderException(Exception):
# """ Raised by some Folder methods when an attempt is made to call some method that depends
# on ordering, but the given folder is unordered.
# """
# def __init__(self):
# Exception.__init__(self, "This folder doesn't support ordering.")
#
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
. Output only the next line. | if error: raise Veto(error) |
Predict the next line for this snippet: <|code_start|> """
zope.interface.implements(ITrash)
_object_type = "trash"
def __init__(self, request):
self.request = request
self._collection_name = "content"
self.title = "Trash"
self.description = "Content can be moved here as an alternative to deleting it forever."
self.__acl__ = permissions.trash_acl
self._id = 'trash'
def _morph_spec(self, spec):
if spec is None: spec = {}
# Make sure parent is in the spec.
spec['__parent__'] = self._id
return spec
def _get_child_class(self, doc):
return self.__parent__.get_content_factory(doc['_object_type'])
def move_child(self, obj):
if obj.__parent__._id == self._id: return
orig_parent = obj.__parent__
orig_name = obj.__name__
obj._memento = dict(
orig_name = orig_name,
orig_parent_id = orig_parent._id,
orig_parent_path = orig_parent.resource_path(),
<|code_end|>
with the help of current file imports:
from folder import unindex_recursively
from collection import Collection
from interfaces import ITrash
from bson.objectid import ObjectId
from pyramid.security import authenticated_userid
from cms.dateutil import utcnow
from cms.exceptions import Veto
import zope.interface
import permissions
and context from other files:
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
#
# Path: cms/exceptions.py
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
, which may contain function names, class names, or code. Output only the next line. | trashed_at = utcnow(), |
Here is a snippet: <|code_start|> trashed_by = authenticated_userid(self.request),
)
obj.__parent__ = self
obj.__name__ = str(obj._id)
obj.save() # FIXME: set_modified=False?
unindex_recursively(obj, include_self=True)
# Notify old parent that child was moved (gives ordered folders an opportunity to update their ordered name list).
orig_parent._child_removed(orig_name)
def _child_removed(self, name):
pass # Like I care? I'm trash!
def dememento_child(self, child):
child.__name__ = child._memento['orig_name']
del child._memento
def veto_restore_child(self, child):
""" Return an error message string if there's any reason why the given child cannot
be restored into its original parent.
Otherwise return None.
"""
root = self.__parent__
orig_parent = root.get_content_by_id(child._memento['orig_parent_id'])
if orig_parent is None: return "Original parent object no longer exists."
if orig_parent.in_trash(): return "Original parent is also in the trash."
return orig_parent.veto_add_child(child._memento['orig_name'], child)
def restore_child(self, child):
root = self.__parent__
orig_parent = root.get_content_by_id(child._memento['orig_parent_id'])
<|code_end|>
. Write the next line using the current file imports:
from folder import unindex_recursively
from collection import Collection
from interfaces import ITrash
from bson.objectid import ObjectId
from pyramid.security import authenticated_userid
from cms.dateutil import utcnow
from cms.exceptions import Veto
import zope.interface
import permissions
and context from other files:
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
#
# Path: cms/exceptions.py
# class Veto(Exception):
# """ May be raised when an attempt is made to do something that the CMS doesn't allow,
# such as adding an object to a folder with a name that's already in use.
# Higher level code (such as views) may want to catch these Veto exceptions
# and present them to end users in a friendly manner.
# """
# def __init__(self, msg):
# Exception.__init__(self, msg)
, which may include functions, classes, or code. Output only the next line. | if orig_parent.in_trash(): raise Veto("Original parent is also in the trash.") |
Given the following code snippet before the placeholder: <|code_start|>
dmp = diff_match_patch.diff_match_patch()
class HistoryCollection(object):
def __init__(self, request):
self.request = request
self._collection_name = "history"
def _get_collection(self):
<|code_end|>
, predict the next line using imports from the current file:
from cms import dbutil, diffutil, htmlutil
from cms.dateutil import utcnow
from pyramid.security import authenticated_userid
from cms.thirdparty import diff_match_patch
and context including class names, function names, and sometimes code from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/diffutil.py
# def pretty_text_diff(text1, text2):
# def startInsertText(self):
# def endInsertText(self):
# def startDeleteText(self):
# def endDeleteText(self):
# def pretty_html_diff(html1, html2):
# def flatten_dictionary(d, prefix=''):
# def _flatten_list(l, prefix=''):
# def unflatten_dictionary(fd):
# def diff_flattened_dictionaries(fd1, fd2):
# def patch_flattened_dictionary(fd, patch):
# def diff_dictionaries(d1, d2):
# def patch_dictionary(d, patch):
# def patch_dictionary_multi(d, patches):
# def get_patch_keys(patch, top_level_only=False):
# class MyHTMLMatcher(htmldiff.NoTagHTMLMatcher):
#
# Path: cms/htmlutil.py
# def sniff_html(s):
# def __init__(self, formatter, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def handle_starttag(self, tag, method, attrs):
# def handle_endtag(self, tag, method):
# def unknown_starttag(self, tag, attrs):
# def unknown_endtag(self, tag):
# def handle_data(self, data):
# def handle_charref(self, ref):
# def handle_entityref(self, ref):
# def html_to_text(html, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def main():
# class HTML_to_text_parser(htmllib.HTMLParser):
# SELF_CLOSING_FIX_RE = re.compile(r'(\S)/>')
#
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | return dbutil.get_collection(self.request, self._collection_name) |
Next line prediction: <|code_start|> user = authenticated_userid(self.request),
action = action,
ids = ids,
)
doc.update(**kwargs)
self._get_collection().save(doc, safe=True)
def get_history(self, spec=None, sort=None, skip=0, limit=0):
cursor = self._get_collection().find(spec=spec, sort=sort, skip=skip, limit=limit)
total = cursor.count()
return dict(total=total, items=list(cursor))
def get_history_for_id(self, _id, skip=0, limit=20):
return self.get_history(spec={'ids':_id}, sort=[('time', -1)], skip=skip, limit=limit)
def get_history_for_user(self, username, skip=0, limit=20):
return self.get_history(spec={'user':username}, sort=[('time', -1)], skip=skip, limit=limit)
def get_history_item(self, _id):
return self._get_collection().find_one(dict(_id=_id))
def apply_history(self, obj, history_id):
""" Given a content object and the _id of a history record, apply
changes from the edit history such that the object has the schema
values it had just after the specified history event.
Note that this method modifies the content object in place.
"""
patches = []
for history in self.get_history_for_id(obj._id)['items']:
if history['_id'] == history_id:
<|code_end|>
. Use current file imports:
(from cms import dbutil, diffutil, htmlutil
from cms.dateutil import utcnow
from pyramid.security import authenticated_userid
from cms.thirdparty import diff_match_patch)
and context including class names, function names, or small code snippets from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/diffutil.py
# def pretty_text_diff(text1, text2):
# def startInsertText(self):
# def endInsertText(self):
# def startDeleteText(self):
# def endDeleteText(self):
# def pretty_html_diff(html1, html2):
# def flatten_dictionary(d, prefix=''):
# def _flatten_list(l, prefix=''):
# def unflatten_dictionary(fd):
# def diff_flattened_dictionaries(fd1, fd2):
# def patch_flattened_dictionary(fd, patch):
# def diff_dictionaries(d1, d2):
# def patch_dictionary(d, patch):
# def patch_dictionary_multi(d, patches):
# def get_patch_keys(patch, top_level_only=False):
# class MyHTMLMatcher(htmldiff.NoTagHTMLMatcher):
#
# Path: cms/htmlutil.py
# def sniff_html(s):
# def __init__(self, formatter, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def handle_starttag(self, tag, method, attrs):
# def handle_endtag(self, tag, method):
# def unknown_starttag(self, tag, attrs):
# def unknown_endtag(self, tag):
# def handle_data(self, data):
# def handle_charref(self, ref):
# def handle_entityref(self, ref):
# def html_to_text(html, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def main():
# class HTML_to_text_parser(htmllib.HTMLParser):
# SELF_CLOSING_FIX_RE = re.compile(r'(\S)/>')
#
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | data = diffutil.patch_dictionary_multi(obj.get_schema_values(), patches) |
Next line prediction: <|code_start|>
dmp = diff_match_patch.diff_match_patch()
class HistoryCollection(object):
def __init__(self, request):
self.request = request
self._collection_name = "history"
def _get_collection(self):
return dbutil.get_collection(self.request, self._collection_name)
def log_history(self, action, ids, **kwargs):
doc = dict(
<|code_end|>
. Use current file imports:
(from cms import dbutil, diffutil, htmlutil
from cms.dateutil import utcnow
from pyramid.security import authenticated_userid
from cms.thirdparty import diff_match_patch)
and context including class names, function names, or small code snippets from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/diffutil.py
# def pretty_text_diff(text1, text2):
# def startInsertText(self):
# def endInsertText(self):
# def startDeleteText(self):
# def endDeleteText(self):
# def pretty_html_diff(html1, html2):
# def flatten_dictionary(d, prefix=''):
# def _flatten_list(l, prefix=''):
# def unflatten_dictionary(fd):
# def diff_flattened_dictionaries(fd1, fd2):
# def patch_flattened_dictionary(fd, patch):
# def diff_dictionaries(d1, d2):
# def patch_dictionary(d, patch):
# def patch_dictionary_multi(d, patches):
# def get_patch_keys(patch, top_level_only=False):
# class MyHTMLMatcher(htmldiff.NoTagHTMLMatcher):
#
# Path: cms/htmlutil.py
# def sniff_html(s):
# def __init__(self, formatter, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def handle_starttag(self, tag, method, attrs):
# def handle_endtag(self, tag, method):
# def unknown_starttag(self, tag, attrs):
# def unknown_endtag(self, tag):
# def handle_data(self, data):
# def handle_charref(self, ref):
# def handle_entityref(self, ref):
# def html_to_text(html, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# def main():
# class HTML_to_text_parser(htmllib.HTMLParser):
# SELF_CLOSING_FIX_RE = re.compile(r'(\S)/>')
#
# Path: cms/dateutil.py
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | time = utcnow(), |
Next line prediction: <|code_start|>
# Example implementation of a common content type.
class Article(Content):
_object_type = "article"
def get_class_schema(cls, request=None):
schema = Content.get_class_schema(request)
#schema.add(colander.SchemaNode(colander_types.DateUS(), name='dateline', default=today_for_request_tz(request)))
<|code_end|>
. Use current file imports:
(from content import Content
from cms import colander_types
from cms.dateutil import get_timezone_for_request, today_for_request_tz, utcnow
import colander, deform
import widgets)
and context including class names, function names, or small code snippets from other files:
# Path: cms/colander_types.py
# class DateTimeUS(colander.SchemaType):
# class DateUS(colander.SchemaType):
# def __init__(self, timezone='UTC'):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
#
# Path: cms/dateutil.py
# def get_timezone_for_request(request=None, default='UTC'):
# # FIXME: consider making this a user preference
# if request:
# return request.registry.settings.get('default_timezone', default)
# else:
# return default
#
# def today_for_request_tz(request):
# """ Return "today's date" for the request's timezone.
# Kinda tricky since at any moment there are always two current dates, depending on your local timezone.
# On the other hand, there's only one UTC date at any moment.
# """
# return convert_from_utc_to_request_tz(datetime.datetime.utcnow(), request).date()
#
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | schema.add(colander.SchemaNode(colander_types.DateTimeUS(get_timezone_for_request(request)), name='dateline', default=utcnow())) |
Given the code snippet: <|code_start|>
# Example implementation of a common content type.
class Article(Content):
_object_type = "article"
def get_class_schema(cls, request=None):
schema = Content.get_class_schema(request)
#schema.add(colander.SchemaNode(colander_types.DateUS(), name='dateline', default=today_for_request_tz(request)))
<|code_end|>
, generate the next line using the imports in this file:
from content import Content
from cms import colander_types
from cms.dateutil import get_timezone_for_request, today_for_request_tz, utcnow
import colander, deform
import widgets
and context (functions, classes, or occasionally code) from other files:
# Path: cms/colander_types.py
# class DateTimeUS(colander.SchemaType):
# class DateUS(colander.SchemaType):
# def __init__(self, timezone='UTC'):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
#
# Path: cms/dateutil.py
# def get_timezone_for_request(request=None, default='UTC'):
# # FIXME: consider making this a user preference
# if request:
# return request.registry.settings.get('default_timezone', default)
# else:
# return default
#
# def today_for_request_tz(request):
# """ Return "today's date" for the request's timezone.
# Kinda tricky since at any moment there are always two current dates, depending on your local timezone.
# On the other hand, there's only one UTC date at any moment.
# """
# return convert_from_utc_to_request_tz(datetime.datetime.utcnow(), request).date()
#
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | schema.add(colander.SchemaNode(colander_types.DateTimeUS(get_timezone_for_request(request)), name='dateline', default=utcnow())) |
Based on the snippet: <|code_start|>
# Example implementation of a common content type.
class Article(Content):
_object_type = "article"
def get_class_schema(cls, request=None):
schema = Content.get_class_schema(request)
#schema.add(colander.SchemaNode(colander_types.DateUS(), name='dateline', default=today_for_request_tz(request)))
<|code_end|>
, predict the immediate next line with the help of imports:
from content import Content
from cms import colander_types
from cms.dateutil import get_timezone_for_request, today_for_request_tz, utcnow
import colander, deform
import widgets
and context (classes, functions, sometimes code) from other files:
# Path: cms/colander_types.py
# class DateTimeUS(colander.SchemaType):
# class DateUS(colander.SchemaType):
# def __init__(self, timezone='UTC'):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
# def serialize(self, node, appstruct):
# def deserialize(self, node, cstruct):
#
# Path: cms/dateutil.py
# def get_timezone_for_request(request=None, default='UTC'):
# # FIXME: consider making this a user preference
# if request:
# return request.registry.settings.get('default_timezone', default)
# else:
# return default
#
# def today_for_request_tz(request):
# """ Return "today's date" for the request's timezone.
# Kinda tricky since at any moment there are always two current dates, depending on your local timezone.
# On the other hand, there's only one UTC date at any moment.
# """
# return convert_from_utc_to_request_tz(datetime.datetime.utcnow(), request).date()
#
# def utcnow(zero_seconds=False):
# """ Returns a timezone aware version of utcnow.
# If zero_seconds, the datetime will be rounded down to the minute.
# """
# now = datetime.datetime.now(pytz.utc)
# if zero_seconds: return now.replace(second=0, microsecond=0)
# return now
. Output only the next line. | schema.add(colander.SchemaNode(colander_types.DateTimeUS(get_timezone_for_request(request)), name='dateline', default=utcnow())) |
Continue the code snippet: <|code_start|># Some pre-configured widgets for use with cms.resources
def get_html_widget(**kwargs):
return deform.widget.RichTextWidget(width='100%', theme='advanced', **kwargs)
# Be sure site includes a css rule for .wide_input { width: 100%; }
def get_wide_text_widget(**kwargs):
return deform.widget.TextInputWidget(css_class="wide_input", **kwargs)
def get_wide_textarea_widget(**kwargs):
return deform.widget.TextAreaWidget(css_class="wide_input", **kwargs)
def get_fileupload_widget(request, **kwargs):
return deform.widget.FileUploadWidget(_get_fileupload_temp_store(request), **kwargs)
def _get_fileupload_temp_store(request):
if request is None: return None
if not hasattr(request, '_tmpstore'):
<|code_end|>
. Use current file imports:
import deform
from cms.filetempstore import MongoFileUploadTempStore
and context (classes, functions, or code) from other files:
# Path: cms/filetempstore.py
# class MongoFileUploadTempStore(object):
#
# MAPPING_NAME = "_tmp_files"
#
# # FIXME: Should the purge really be done on every instantiation, or would
# # it be better to have a nightly job call purge(delete_cutoff) where delete_cutoff
# # is a timedelta?
# def __init__(self, request, collection='fs', delete_cutoff_days=1):
# self.gridfs = get_gridfs(request, collection)
# self.request = request
# self.delete_cutoff_days = datetime.timedelta(delete_cutoff_days)
# self.purge()
#
# def purge(self):
# cutoff = dateutil.utcnow() - self.delete_cutoff_days
# old_ids = []
# for item in self.gridfs._GridFS__files.find({'parents':[], 'uploadDate':{'$lt':cutoff}}, fields=[]):
# old_ids.append(item['_id'])
# if old_ids:
# log.debug("purging old files: %s" % repr(old_ids))
# for id in old_ids:
# self.gridfs.delete(id)
#
# def get(self, name, default=None):
# #log.debug("get(%s, %s)" % (repr(name), repr(default)))
# files_dict = self.get_file_mapping()
# _id = files_dict.get(name)
# if _id:
# try:
# result = self.gridfs.get(_id)
# except NoFile, e:
# return default
# return filedict(
# fp=result,
# mimetype=result.content_type,
# uid=name,
# preview_url=self.preview_url_for_id(_id),
# filename=result.name,
# size=result.length,
# _id=_id,
# parents=result.parents
# )
# return default
#
# def __setitem__(self, name, value):
# #log.debug("__setitem__(%s, %s)" % (repr(name), repr(value)))
# if value.has_key('_id'):
# _id = value['_id']
# else:
# _id = self.gridfs.put(value['fp'], filename=value['filename'], contentType=value['mimetype'], parents=[])
# value['_id'] = _id
# value['parents'] = []
# value['preview_url'] = self.preview_url_for_id(_id)
# files_dict = self.get_file_mapping()
# files_dict[name] = _id
# setattr(self.request, self.MAPPING_NAME, files_dict)
#
# def __getitem__(self, name):
# #log.debug("__getitem__(%s)" % repr(name))
# return self.get(name)
#
# def __contains__(self, name):
# #log.debug("__contains__(%s)" % repr(name))
# files_dict = self.get_file_mapping()
# _id = files_dict.get(name)
# if _id:
# return self.gridfs.exists(_id)
# return False
#
# def preview_url(self, uid):
# #log.debug("preview_url(%s)" % repr(uid))
# _id = self.get_file_mapping().get(uid)
# return self.preview_url_for_id(_id)
#
# def preview_url_for_id(self, _id):
# # There should be a view to handle these urls.
# return "%s/serve_file/%s" % (self.request.application_url, str(_id))
#
# def get_file_mapping(self):
# return getattr(self.request, self.MAPPING_NAME, {})
#
# def serialize_file_mapping(self):
# items = []
# for (uid, _id) in self.get_file_mapping().items():
# items.append("%s:%s" % (uid, str(_id)))
# return ",".join(items)
#
# def _deserialize_file_mapping(self, serialized_string):
# """ Deserialize a string such as returned from serialize_file_mapping().
# """
# files_dict = {}
# if serialized_string:
# for item in serialized_string.split(','):
# (uid, _id) = item.split(':', 1)
# files_dict[uid] = ObjectId(_id)
# return files_dict
#
# def update_file_mapping_from_serialized(self, serialized_string):
# deserialized_dict = self._deserialize_file_mapping(serialized_string)
# files_dict = self.get_file_mapping()
# for (uid, _id) in deserialized_dict.items():
# # If the current mapping has this uid, the user must have uploaded a new file,
# # so skip the uid (otherwise it would revert to the original file).
# if not files_dict.has_key(uid):
# files_dict[uid] = _id
# setattr(self.request, self.MAPPING_NAME, files_dict)
. Output only the next line. | tmpstore = MongoFileUploadTempStore(request) |
Continue the code snippet: <|code_start|> mapping['_view'] = dict(type='string', include_in_all=False, index='not_analyzed')
mapping['_pub_state'] = dict(type='string', include_in_all=False, index='not_analyzed')
mapping['_id_path'] = dict(type='string', include_in_all=False, index='not_analyzed')
mapping['_object_type'] = dict(type='string', include_in_all=False, index='not_analyzed')
mapping['title'] = dict(type='string', include_in_all=True, boost=4.0)
mapping['sortable_title'] = dict(type='string', include_in_all=False, index='not_analyzed')
mapping['description'] = dict(type='string', include_in_all=True, boost=2.0)
mapping['other_text'] = dict(type='string', include_in_all=True)
mapping['_created'] = dict(type='date', format='dateOptionalTime', include_in_all=False)
mapping['_modified'] = dict(type='date', format='dateOptionalTime', include_in_all=False)
return mapping
_get_es_mapping = classmethod(_get_es_mapping)
def _get_es_document(self):
doc = dict(__name__ = self.__name__,
_object_type = self._object_type,
title = self.title,
sortable_title = self.sortable_title.lower(),
description = self.description,
_created = self._created,
_modified = self._modified,
_id_path = [str(x) for x in self.get_id_path()],
)
doc['_view'] = self._get_view_principals()
_pub_state = self.get_pub_state()
if _pub_state: doc['_pub_state'] = _pub_state
doc['other_text'] = self.get_es_other_text()
return doc
def index(self):
<|code_end|>
. Use current file imports:
from object import Object
from cms import dbutil
from bson.objectid import ObjectId
from cms.htmlutil import html_to_text
from pyramid import security
from interfaces import IContent, ITrash
import colander, deform
import widgets
import permissions
import repoze.workflow
import zope.interface
import pyes
import logging
and context (classes, functions, or code) from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/htmlutil.py
# def html_to_text(html, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# output_unicode = False
# if type(html) == unicode:
# html = html.encode('utf-8')
# output_unicode = True
#
# textout = cStringIO.StringIO()
# formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
# parser = HTML_to_text_parser(formtext, show_link_urls, skip_tags, unknown_entity_replacement)
#
# # Annoyingly HTMLParser doesn't handle self-closing tags without a space
# # (such as "<br/>") properly.
# # So let's add any missing spaces (for example, "<br />").
# html = SELF_CLOSING_FIX_RE.sub(r'\1 />', html)
#
# parser.feed(html)
# parser.close()
# text = textout.getvalue().strip()
# del textout, formtext, parser
# if output_unicode: return unicode(text, 'utf-8')
# else: return text
. Output only the next line. | dbutil.get_es_conn(self.request).index(self._get_es_document(), dbutil.get_es_index_name(self.request), self._get_es_doctype(), str(self._id)) |
Predict the next line for this snippet: <|code_start|>
def index(self):
dbutil.get_es_conn(self.request).index(self._get_es_document(), dbutil.get_es_index_name(self.request), self._get_es_doctype(), str(self._id))
def unindex(self):
try:
dbutil.get_es_conn(self.request).delete(dbutil.get_es_index_name(self.request), self._get_es_doctype(), str(self._id))
except pyes.exceptions.NotFoundException, e:
pass
def get_es_other_text(self):
return '\n'.join(self._get_text_values_for_schema_node(self.get_schema(), self.get_schema_values()))
def _get_text_values_for_schema_node(self, node, value):
result = []
if not value: return result
if type(node.typ) == colander.Mapping:
for cnode in node.children:
name = cnode.name
val = value.get(name, None)
if val:
result += self._get_text_values_for_schema_node(cnode, val)
elif type(node.typ) == colander.Sequence:
if node.children:
cnode = node.children[0]
for val in value:
result += self._get_text_values_for_schema_node(cnode, val)
elif type(node.typ) == colander.String:
if getattr(node, 'include_in_other_text', True):
if type(node.widget) == deform.widget.RichTextWidget:
<|code_end|>
with the help of current file imports:
from object import Object
from cms import dbutil
from bson.objectid import ObjectId
from cms.htmlutil import html_to_text
from pyramid import security
from interfaces import IContent, ITrash
import colander, deform
import widgets
import permissions
import repoze.workflow
import zope.interface
import pyes
import logging
and context from other files:
# Path: cms/dbutil.py
# def get_mongodb(request):
# def get_collection(request, name):
# def get_gridfs(request, collection='fs'):
# def encode_keys(d):
# def get_es_conn(request):
# def get_es_index_name(request):
# def serve_gridfs_file(file):
# def serve_gridfs_file_for_id(request, id, collection='fs'):
#
# Path: cms/htmlutil.py
# def html_to_text(html, show_link_urls=1, skip_tags=[], unknown_entity_replacement=None):
# output_unicode = False
# if type(html) == unicode:
# html = html.encode('utf-8')
# output_unicode = True
#
# textout = cStringIO.StringIO()
# formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
# parser = HTML_to_text_parser(formtext, show_link_urls, skip_tags, unknown_entity_replacement)
#
# # Annoyingly HTMLParser doesn't handle self-closing tags without a space
# # (such as "<br/>") properly.
# # So let's add any missing spaces (for example, "<br />").
# html = SELF_CLOSING_FIX_RE.sub(r'\1 />', html)
#
# parser.feed(html)
# parser.close()
# text = textout.getvalue().strip()
# del textout, formtext, parser
# if output_unicode: return unicode(text, 'utf-8')
# else: return text
, which may contain function names, class names, or code. Output only the next line. | value = html_to_text(value, 0) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
'''
Emulate a USB device to be used for fuzzing
Usage:
umap2fuzz -P=PHY_INFO -C=DEVICE_CLASS [-q] [--vid=VID] [--pid=PID] [-i=FUZZER_IP] [-p FUZZER_PORT] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-C --class DEVICE_CLASS class of the device or path to python file with device class
-v --verbose verbosity level
-i --fuzzer-ip HOST hostname or IP of the fuzzer [default: 127.0.0.1]
-p --fuzzer-port PORT port of the fuzzer [default: 26007]
-q --quiet quiet mode. only print warning/error messages
--vid VID override vendor ID
--pid PID override product ID
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
Examples:
emulate disk-on-key:
umap2fuzz -P fd:/dev/ttyUSB1 -C mass_storage
'''
<|code_end|>
. Use current file imports:
import os
import time
from kitty.remote.rpc import RpcClient
from umap2.apps.emulate import Umap2EmulationApp
and context (classes, functions, or code) from other files:
# Path: umap2/apps/emulate.py
# class Umap2EmulationApp(Umap2App):
#
# def run(self):
# self.fuzzer = self.get_fuzzer()
# self.phy = self.load_phy(self.options['--phy'])
# self.dev = self.load_device(self.options['--class'], self.phy)
# try:
# self.dev.connect()
# self.dev.run()
# except KeyboardInterrupt:
# self.logger.info('user terminated the run')
# except:
# self.logger.error('Got exception while connecting/running device')
# self.logger.error(traceback.format_exc())
# self.dev.disconnect()
#
# def get_fuzzer(self):
# return None
. Output only the next line. | class Umap2FuzzApp(Umap2EmulationApp): |
Predict the next line after this snippet: <|code_start|>'''
Hub templates
'''
# hub_descriptor
'''
d = struct.pack(
'<BBHBB',
DescriptorType.hub,
self.num_ports,
self.hub_chars,
self.pwr_on_2_pwr_good,
self.hub_contr_current,
)
num_bytes = self.num_ports // 7
if self.num_ports % 7 != 0:
num_bytes += 1
d += '\x00' * num_bytes
d += '\xff' * num_bytes
d = struct.pack('B', len(d) + 1) + d
return d
'''
hub_descriptor = Descriptor(
name='hub_descriptor',
<|code_end|>
using the current file's imports:
from umap2.core.usb import DescriptorType
from kitty.model import UInt8, LE16, RandomBytes
from kitty.model import Size
from generic import Descriptor
and any relevant context from other files:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
. Output only the next line. | descriptor_type=DescriptorType.hub, |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
'''
List default classes supported in umap
Usage:
umap2list [-v]
Options:
-v, --verbose show more information
'''
<|code_end|>
with the help of current file imports:
from umap2.apps.base import Umap2App
and context from other files:
# Path: umap2/apps/base.py
# class Umap2App(object):
#
# def __init__(self, docstring=None):
# if docstring is not None:
# self.options = docopt.docopt(docstring)
# else:
# self.options = {}
# self.umap_class_dict = {
# 'audio': ('audio', 'Headset'),
# 'billboard': ('billboard', 'A billboard, requires USB 2.1 and higher'),
# 'cdc_acm': ('cdc_acm', 'Abstract Control Model device (like serial modem)'),
# 'cdc_dl': ('cdc_dl', 'Direct Line Control device (like modem)'),
# 'ftdi': ('ftdi', 'USB<->RS232 FTDI chip'),
# 'hub': ('hub', 'USB hub'),
# 'keyboard': ('keyboard', 'Keyboard'),
# 'mass_storage': ('mass_storage', 'Disk on key'),
# 'mtp': ('mtp', 'Android phone'),
# 'printer': ('printer', 'Printer'),
# 'smartcard': ('smartcard', 'USB<->smart card interface'),
# }
# self.umap_classes = sorted(self.umap_class_dict.keys())
# self.logger = self.get_logger()
# self.num_processed = 0
# self.fuzzer = None
# self.setup_packet_received = False
#
# def get_logger(self):
# levels = {
# 0: logging.INFO,
# 1: logging.DEBUG,
# # verbose is added by umap2.__init__ module
# 2: logging.VERBOSE,
# }
# verbose = self.options.get('--verbose', 0)
# logger = logging.getLogger('umap2')
# if verbose in levels:
# set_default_handler_level(levels[verbose])
# else:
# set_default_handler_level(logging.VERBOSE)
# if self.options.get('--quiet', False):
# set_default_handler_level(logging.WARNING)
# return logger
#
# def load_phy(self, phy_string):
# self.logger.info('Loading physical interface: %s' % phy_string)
# phy_arr = phy_string.split(':')
# phy_type = phy_arr[0]
# if phy_type == 'fd':
# self.logger.debug('Physical interface is facedancer')
# dev_name = phy_arr[1]
# s = Serial(dev_name, 115200, parity=PARITY_NONE, timeout=2)
# # fd = Facedancer(s)
# phy = Max342xPhy(self, s)
# return phy
# elif phy_type == 'rd':
# try:
# from umap2.phy.raspdancer.raspdancer_phy import RaspdancerPhy
# self.logger.debug('Physical interface is raspdancer')
# phy = RaspdancerPhy(self)
# return phy
# except ImportError:
# raise Exception('Raspdancer support misses spi module and/or gpio module.')
# elif phy_type == 'gadgetfs':
# self.logger.debug('Physical interface is GadgetFs')
# phy = GadgetFsPhy(self)
# return phy
# raise Exception('Phy type not supported: %s' % phy_type)
#
# def load_device(self, dev_name, phy):
# if dev_name in self.umap_classes:
# self.logger.info('Loading USB device %s' % dev_name)
# module_name = self.umap_class_dict[dev_name][0]
# module = importlib.import_module('umap2.dev.%s' % module_name)
# else:
# self.logger.info('Loading custom USB device from file: %s' % dev_name)
# dirpath, filename = os.path.split(dev_name)
# modulename = filename[:-3]
# if dirpath in sys.path:
# sys.path.remove(dirpath)
# sys.path.insert(0, dirpath)
# module = __import__(modulename, globals(), locals(), [], -1)
# usb_device = module.usb_device
# kwargs = self.get_user_device_kwargs()
# dev = usb_device(self, phy, **kwargs)
# return dev
#
# def get_user_device_kwargs(self):
# '''
# if user provides values for the device, get them here
# '''
# kwargs = {}
# self.update_from_user_param('--vid', 'vid', kwargs, 'int')
# self.update_from_user_param('--pid', 'pid', kwargs, 'int')
# return kwargs
#
# def update_from_user_param(self, flag, arg_name, kwargs, type):
# val = self.options.get(flag, None)
# if val is not None:
# if type == 'int':
# kwargs[arg_name] = int(val, 0)
# self.logger.info('Setting user-supplied %s: %#x' % (arg_name, kwargs[arg_name]))
# else:
# raise Exception('arg type not supported!!')
#
# def signal_setup_packet_received(self):
# '''
# Signal that we received a setup packet from the host (host is alive)
# '''
# self.setup_packet_received = True
#
# def should_stop_phy(self):
# '''
# :return: whether phy should stop serving.
# '''
# return False
#
# def usb_function_supported(self, reason=None):
# '''
# Callback from a USB device, notifying that the current USB device
# is supported by the host.
# By default, do nothing with this information
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# pass
#
# def get_mutation(self, stage, data=None):
# '''
# mutation is only needed when fuzzing
# '''
# return None
, which may contain function names, class names, or code. Output only the next line. | class Umap2ListClassesApp(Umap2App): |
Based on the snippet: <|code_start|>'''
USB Interface class.
Each instance represents a single USB interface.
This is a base class, and should be subclassed.
'''
<|code_end|>
, predict the immediate next line with the help of imports:
import struct
from umap2.core.usb import interface_class_to_descriptor_type, DescriptorType
from umap2.core.usb_base import USBBaseActor
from umap2.fuzz.helpers import mutable
and context (classes, functions, sometimes code) from other files:
# Path: umap2/core/usb.py
# def interface_class_to_descriptor_type(interface_class):
# return USB.if_class_to_desc_type.get(interface_class, None)
#
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
#
# Path: umap2/core/usb_base.py
# class USBBaseActor(object):
#
# name = 'Actor'
#
# def __init__(self, app, phy):
# '''
# :param app: Umap2 application
# :param phy: Physical connection
# '''
# self.phy = phy
# self.app = app
# self.session_data = {}
# self.str_dict = {}
# self.logger = logging.getLogger('umap2')
#
# def get_mutation(self, stage, data=None):
# '''
# :param stage: stage name
# :param data: dictionary (string: bytearray) of data for the fuzzer (default: None)
# :return: mutation for current stage, None if not current fuzzing stage
# '''
# return self.app.get_mutation(stage, data)
#
# def send_on_endpoint(self, ep, data):
# '''
# Send data on a given endpoint
#
# :param ep: endpoint number
# :param data: data to send
# '''
# self.phy.send_on_endpoint(ep, data)
#
# def get_session_data(self, stage):
# '''
# If an entity wants to pass specific data to the fuzzer when getting a mutation,
# it could return a session data here.
# This session data should be a dictionary of string:bytearray.
# The keys of the dictionary should match the keys in the templates.
#
# :param stage: stage that the session data is for
# :return: dictionary of session data
# '''
# return self.session_data
#
# def usb_function_supported(self, reason=None):
# '''
# Mark current USB function as supported by the host.
# This will tell the application to stop emulating current device.
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# self.app.usb_function_supported(reason)
#
# def add_string_with_id(self, str_id, s):
# '''
# Add a string to the string dictionary
#
# :param str_id: id of the string
# :param s: the string
# '''
# self.str_dict[str_id] = s
#
# def get_string_by_id(self, str_id):
# '''
# Get a string by it's id
#
# :param str_id: string id
# :return: the string, or None if id does not exist
# '''
# self.debug('Getting string by id %#x' % (str_id))
# if str_id in self.str_dict:
# return self.str_dict[str_id]
# return None
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# Path: umap2/fuzz/helpers.py
# def mutable(stage, silent=False):
# def wrap_f(func):
# func_self = None
# if inspect.ismethod(func):
# func_self = func.im_self
# func = func.im_func
#
# def wrapper(*args, **kwargs):
# if func_self is None:
# self = args[0]
# args = tuple(args[1:])
# else:
# self = func_self
# response = None
# valid_req = kwargs.get('valid', False)
# info = self.info if not silent else self.debug
# if not valid_req:
# log_stage(stage)
# session_data = self.get_session_data(stage)
# data = kwargs.get('fuzzing_data', {})
# data.update(session_data)
# response = self.get_mutation(stage=stage, data=data)
# try:
# if response is not None:
# if not silent:
# info('Got mutation for stage %s' % stage)
# else:
# if valid_req:
# info('Calling %s' % (func.__name__))
# else:
# info('Calling %s (stage: "%s")' % (func.__name__, stage))
# response = func(self, *args, **kwargs)
# except Exception as e:
# self.logger.error(traceback.format_exc())
# self.logger.error(''.join(traceback.format_stack()))
# raise e
# if response is not None:
# info('Response: %s' % binascii.hexlify(response))
# return response
# return wrapper
# return wrap_f
. Output only the next line. | class USBInterface(USBBaseActor): |
Given snippet: <|code_start|> def parser_wrapper(pfn):
def wrapper(self, desc):
# print 'Parsing desc %02x: %s' % (desc_type, hexlify(desc))
self.select_node(desc_type)
node = DescriptorNode(desc_type)
node.text = pfn(self, desc, node)
self.push_node(node)
return wrapper
return parser_wrapper
def build_init(cls_name, params):
params.insert(0, ('phy', 'phy'))
params.insert(0, ('app', 'app'))
s = '%s(\n ' % (cls_name)
s += ',\n '.join('%s=%s' % (a, b if type(b) != int else hex(b)) for (a, b) in params)
s += '\n)'
return s
class Parser(object):
transfer_types = ('USBEndpoint.transfer_type_', ['control', 'isochronous', 'bulk', 'interrupt'])
sync_types = ('USBEndpoint.sync_type_', ['none', 'async', 'adaptive', 'synchronous'])
usage_types = ('USBEndpoint.usage_type_', ['data', 'feedback', 'implicit_feedback'])
def __init__(self, opts):
self.opts = opts
self.root_node = RootNode()
self.curr_node = self.root_node
self.parsers = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from docopt import docopt
from binascii import unhexlify, hexlify
from umap2.core.usb import DescriptorType
import struct
and context:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
which might include code, classes, or functions. Output only the next line. | DescriptorType.configuration: self.parse_configuration_desc, |
Given the following code snippet before the placeholder: <|code_start|>class _AC_DescriptorSubTypes: # AC Interface Descriptor Subtype
'''Descriptor sub types [audio10.pdf table A-5]'''
AC_DESCRIPTOR_UNDEFINED = 0x00
HEADER = 0x01
INPUT_TERMINAL = 0x02
OUTPUT_TERMINAL = 0x03
MIXER_UNIT = 0x04
SELECTOR_UNIT = 0x05
FEATURE_UNIT = 0x06
PROCESSING_UNIT = 0x07
EXTENSION_UNIT = 0x08
class _AS_DescriptorSubTypes: # AS Interface Descriptor Subtype
'''Descriptor sub types [audio10.pdf table A-6]'''
AS_DESCRIPTOR_UNDEFINED = 0x00
AS_GENERAL = 0x01
FORMAT_TYPE = 0x02
FORMAT_SPECIFIC = 0x03
# TODO: audio_ep2_buffer_available
# TODO: remove?
audio_header_descriptor = Descriptor(
name='audio_header_descriptor',
<|code_end|>
, predict the next line using imports from the current file:
from umap2.core.usb import DescriptorType
from kitty.model import UInt8, LE16, RandomBytes, BitField, Static
from kitty.model import Template, Repeat, List, Container, ForEach, OneOf
from kitty.model import ElementCount, SizeInBytes
from kitty.model import ENC_INT_LE
from hid import GenerateHidReport
from generic import Descriptor, SizedPt, DynamicInt, SubDescriptor
and context including class names, function names, and sometimes code from other files:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
. Output only the next line. | descriptor_type=DescriptorType.cs_interface, |
Here is a snippet: <|code_start|># USBCSInterface.py
#
# Contains class definition for USBCSInterface.
class USBCSInterface(USBBaseActor):
name = 'CSInterface'
def __init__(self, name, app, phy, cs_config):
'''
:param app: umap2 application
:param phy: physical connection
:param cs_config: class specific configuration
'''
super(USBCSInterface, self).__init__(app, phy)
self.name = name
self.cs_config = cs_config
self.descriptors = {}
<|code_end|>
. Write the next line using the current file imports:
import struct
from umap2.core.usb import DescriptorType
from umap2.core.usb_base import USBBaseActor
and context from other files:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
#
# Path: umap2/core/usb_base.py
# class USBBaseActor(object):
#
# name = 'Actor'
#
# def __init__(self, app, phy):
# '''
# :param app: Umap2 application
# :param phy: Physical connection
# '''
# self.phy = phy
# self.app = app
# self.session_data = {}
# self.str_dict = {}
# self.logger = logging.getLogger('umap2')
#
# def get_mutation(self, stage, data=None):
# '''
# :param stage: stage name
# :param data: dictionary (string: bytearray) of data for the fuzzer (default: None)
# :return: mutation for current stage, None if not current fuzzing stage
# '''
# return self.app.get_mutation(stage, data)
#
# def send_on_endpoint(self, ep, data):
# '''
# Send data on a given endpoint
#
# :param ep: endpoint number
# :param data: data to send
# '''
# self.phy.send_on_endpoint(ep, data)
#
# def get_session_data(self, stage):
# '''
# If an entity wants to pass specific data to the fuzzer when getting a mutation,
# it could return a session data here.
# This session data should be a dictionary of string:bytearray.
# The keys of the dictionary should match the keys in the templates.
#
# :param stage: stage that the session data is for
# :return: dictionary of session data
# '''
# return self.session_data
#
# def usb_function_supported(self, reason=None):
# '''
# Mark current USB function as supported by the host.
# This will tell the application to stop emulating current device.
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# self.app.usb_function_supported(reason)
#
# def add_string_with_id(self, str_id, s):
# '''
# Add a string to the string dictionary
#
# :param str_id: id of the string
# :param s: the string
# '''
# self.str_dict[str_id] = s
#
# def get_string_by_id(self, str_id):
# '''
# Get a string by it's id
#
# :param str_id: string id
# :return: the string, or None if id does not exist
# '''
# self.debug('Getting string by id %#x' % (str_id))
# if str_id in self.str_dict:
# return self.str_dict[str_id]
# return None
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | self.descriptors[DescriptorType.cs_interface] = self.get_descriptor |
Based on the snippet: <|code_start|>'''
Scan device support in USB host
Usage:
umap2scan -P=PHY_INFO [-q] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-v --verbose verbosity level
-q --quiet quiet mode. only print warning/error messages
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
Example:
umap2scan -P fd:/dev/ttyUSB0 -q
'''
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import traceback
from umap2.apps.base import Umap2App
and context (classes, functions, sometimes code) from other files:
# Path: umap2/apps/base.py
# class Umap2App(object):
#
# def __init__(self, docstring=None):
# if docstring is not None:
# self.options = docopt.docopt(docstring)
# else:
# self.options = {}
# self.umap_class_dict = {
# 'audio': ('audio', 'Headset'),
# 'billboard': ('billboard', 'A billboard, requires USB 2.1 and higher'),
# 'cdc_acm': ('cdc_acm', 'Abstract Control Model device (like serial modem)'),
# 'cdc_dl': ('cdc_dl', 'Direct Line Control device (like modem)'),
# 'ftdi': ('ftdi', 'USB<->RS232 FTDI chip'),
# 'hub': ('hub', 'USB hub'),
# 'keyboard': ('keyboard', 'Keyboard'),
# 'mass_storage': ('mass_storage', 'Disk on key'),
# 'mtp': ('mtp', 'Android phone'),
# 'printer': ('printer', 'Printer'),
# 'smartcard': ('smartcard', 'USB<->smart card interface'),
# }
# self.umap_classes = sorted(self.umap_class_dict.keys())
# self.logger = self.get_logger()
# self.num_processed = 0
# self.fuzzer = None
# self.setup_packet_received = False
#
# def get_logger(self):
# levels = {
# 0: logging.INFO,
# 1: logging.DEBUG,
# # verbose is added by umap2.__init__ module
# 2: logging.VERBOSE,
# }
# verbose = self.options.get('--verbose', 0)
# logger = logging.getLogger('umap2')
# if verbose in levels:
# set_default_handler_level(levels[verbose])
# else:
# set_default_handler_level(logging.VERBOSE)
# if self.options.get('--quiet', False):
# set_default_handler_level(logging.WARNING)
# return logger
#
# def load_phy(self, phy_string):
# self.logger.info('Loading physical interface: %s' % phy_string)
# phy_arr = phy_string.split(':')
# phy_type = phy_arr[0]
# if phy_type == 'fd':
# self.logger.debug('Physical interface is facedancer')
# dev_name = phy_arr[1]
# s = Serial(dev_name, 115200, parity=PARITY_NONE, timeout=2)
# # fd = Facedancer(s)
# phy = Max342xPhy(self, s)
# return phy
# elif phy_type == 'rd':
# try:
# from umap2.phy.raspdancer.raspdancer_phy import RaspdancerPhy
# self.logger.debug('Physical interface is raspdancer')
# phy = RaspdancerPhy(self)
# return phy
# except ImportError:
# raise Exception('Raspdancer support misses spi module and/or gpio module.')
# elif phy_type == 'gadgetfs':
# self.logger.debug('Physical interface is GadgetFs')
# phy = GadgetFsPhy(self)
# return phy
# raise Exception('Phy type not supported: %s' % phy_type)
#
# def load_device(self, dev_name, phy):
# if dev_name in self.umap_classes:
# self.logger.info('Loading USB device %s' % dev_name)
# module_name = self.umap_class_dict[dev_name][0]
# module = importlib.import_module('umap2.dev.%s' % module_name)
# else:
# self.logger.info('Loading custom USB device from file: %s' % dev_name)
# dirpath, filename = os.path.split(dev_name)
# modulename = filename[:-3]
# if dirpath in sys.path:
# sys.path.remove(dirpath)
# sys.path.insert(0, dirpath)
# module = __import__(modulename, globals(), locals(), [], -1)
# usb_device = module.usb_device
# kwargs = self.get_user_device_kwargs()
# dev = usb_device(self, phy, **kwargs)
# return dev
#
# def get_user_device_kwargs(self):
# '''
# if user provides values for the device, get them here
# '''
# kwargs = {}
# self.update_from_user_param('--vid', 'vid', kwargs, 'int')
# self.update_from_user_param('--pid', 'pid', kwargs, 'int')
# return kwargs
#
# def update_from_user_param(self, flag, arg_name, kwargs, type):
# val = self.options.get(flag, None)
# if val is not None:
# if type == 'int':
# kwargs[arg_name] = int(val, 0)
# self.logger.info('Setting user-supplied %s: %#x' % (arg_name, kwargs[arg_name]))
# else:
# raise Exception('arg type not supported!!')
#
# def signal_setup_packet_received(self):
# '''
# Signal that we received a setup packet from the host (host is alive)
# '''
# self.setup_packet_received = True
#
# def should_stop_phy(self):
# '''
# :return: whether phy should stop serving.
# '''
# return False
#
# def usb_function_supported(self, reason=None):
# '''
# Callback from a USB device, notifying that the current USB device
# is supported by the host.
# By default, do nothing with this information
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# pass
#
# def get_mutation(self, stage, data=None):
# '''
# mutation is only needed when fuzzing
# '''
# return None
. Output only the next line. | class Umap2ScanApp(Umap2App): |
Continue the code snippet: <|code_start|>
class TestApp(Umap2App):
def __init__(self, docstring=None, event_handler=None):
super(TestApp, self).__init__(docstring)
<|code_end|>
. Use current file imports:
import logging
from umap2.apps.base import Umap2App
from umap2.utils.ulogger import set_default_handler_level
from infra_phy import TestPhy
and context (classes, functions, or code) from other files:
# Path: umap2/apps/base.py
# class Umap2App(object):
#
# def __init__(self, docstring=None):
# if docstring is not None:
# self.options = docopt.docopt(docstring)
# else:
# self.options = {}
# self.umap_class_dict = {
# 'audio': ('audio', 'Headset'),
# 'billboard': ('billboard', 'A billboard, requires USB 2.1 and higher'),
# 'cdc_acm': ('cdc_acm', 'Abstract Control Model device (like serial modem)'),
# 'cdc_dl': ('cdc_dl', 'Direct Line Control device (like modem)'),
# 'ftdi': ('ftdi', 'USB<->RS232 FTDI chip'),
# 'hub': ('hub', 'USB hub'),
# 'keyboard': ('keyboard', 'Keyboard'),
# 'mass_storage': ('mass_storage', 'Disk on key'),
# 'mtp': ('mtp', 'Android phone'),
# 'printer': ('printer', 'Printer'),
# 'smartcard': ('smartcard', 'USB<->smart card interface'),
# }
# self.umap_classes = sorted(self.umap_class_dict.keys())
# self.logger = self.get_logger()
# self.num_processed = 0
# self.fuzzer = None
# self.setup_packet_received = False
#
# def get_logger(self):
# levels = {
# 0: logging.INFO,
# 1: logging.DEBUG,
# # verbose is added by umap2.__init__ module
# 2: logging.VERBOSE,
# }
# verbose = self.options.get('--verbose', 0)
# logger = logging.getLogger('umap2')
# if verbose in levels:
# set_default_handler_level(levels[verbose])
# else:
# set_default_handler_level(logging.VERBOSE)
# if self.options.get('--quiet', False):
# set_default_handler_level(logging.WARNING)
# return logger
#
# def load_phy(self, phy_string):
# self.logger.info('Loading physical interface: %s' % phy_string)
# phy_arr = phy_string.split(':')
# phy_type = phy_arr[0]
# if phy_type == 'fd':
# self.logger.debug('Physical interface is facedancer')
# dev_name = phy_arr[1]
# s = Serial(dev_name, 115200, parity=PARITY_NONE, timeout=2)
# # fd = Facedancer(s)
# phy = Max342xPhy(self, s)
# return phy
# elif phy_type == 'rd':
# try:
# from umap2.phy.raspdancer.raspdancer_phy import RaspdancerPhy
# self.logger.debug('Physical interface is raspdancer')
# phy = RaspdancerPhy(self)
# return phy
# except ImportError:
# raise Exception('Raspdancer support misses spi module and/or gpio module.')
# elif phy_type == 'gadgetfs':
# self.logger.debug('Physical interface is GadgetFs')
# phy = GadgetFsPhy(self)
# return phy
# raise Exception('Phy type not supported: %s' % phy_type)
#
# def load_device(self, dev_name, phy):
# if dev_name in self.umap_classes:
# self.logger.info('Loading USB device %s' % dev_name)
# module_name = self.umap_class_dict[dev_name][0]
# module = importlib.import_module('umap2.dev.%s' % module_name)
# else:
# self.logger.info('Loading custom USB device from file: %s' % dev_name)
# dirpath, filename = os.path.split(dev_name)
# modulename = filename[:-3]
# if dirpath in sys.path:
# sys.path.remove(dirpath)
# sys.path.insert(0, dirpath)
# module = __import__(modulename, globals(), locals(), [], -1)
# usb_device = module.usb_device
# kwargs = self.get_user_device_kwargs()
# dev = usb_device(self, phy, **kwargs)
# return dev
#
# def get_user_device_kwargs(self):
# '''
# if user provides values for the device, get them here
# '''
# kwargs = {}
# self.update_from_user_param('--vid', 'vid', kwargs, 'int')
# self.update_from_user_param('--pid', 'pid', kwargs, 'int')
# return kwargs
#
# def update_from_user_param(self, flag, arg_name, kwargs, type):
# val = self.options.get(flag, None)
# if val is not None:
# if type == 'int':
# kwargs[arg_name] = int(val, 0)
# self.logger.info('Setting user-supplied %s: %#x' % (arg_name, kwargs[arg_name]))
# else:
# raise Exception('arg type not supported!!')
#
# def signal_setup_packet_received(self):
# '''
# Signal that we received a setup packet from the host (host is alive)
# '''
# self.setup_packet_received = True
#
# def should_stop_phy(self):
# '''
# :return: whether phy should stop serving.
# '''
# return False
#
# def usb_function_supported(self, reason=None):
# '''
# Callback from a USB device, notifying that the current USB device
# is supported by the host.
# By default, do nothing with this information
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# pass
#
# def get_mutation(self, stage, data=None):
# '''
# mutation is only needed when fuzzing
# '''
# return None
#
# Path: umap2/utils/ulogger.py
# def set_default_handler_level(level):
# global stdio_handler
# stdio_handler.setLevel(level)
. Output only the next line. | set_default_handler_level(logging.ERROR) |
Continue the code snippet: <|code_start|> args = report_str[index:index + num_args]
value = sum(ord(args[i]) << (i * 8) for i in range(len(args))) # little endian...
fields.append(Container(
name=cur_name,
fields=[
UInt8(opcode, name='opcode'),
BitField(value, 8 * len(args), encoder=ENC_INT_LE, name='value')
]
))
index += num_args
return OneOf(
name=name,
fields=[
Container(
name='generation',
fields=fields
),
MutableField(
name='mutation',
value=report_str
),
RandomHidReport(
name='random_sequences'
),
])
# ############### Templates ############### #
hid_descriptor = Descriptor(
name='hid_descriptor',
<|code_end|>
. Use current file imports:
from umap2.core.usb import DescriptorType
from kitty.model import Template, Container, OneOf, TakeFrom
from kitty.model import MutableField
from kitty.model import UInt8, LE16, BitField, Static
from kitty.model import ENC_INT_LE
from kitty.core import KittyException
from random import Random
from generic import DynamicInt, Descriptor
and context (classes, functions, or code) from other files:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
. Output only the next line. | descriptor_type=DescriptorType.hid, |
Here is a snippet: <|code_start|> pin_control = 0x11
revision = 0x12
function_address = 0x13
io_pins = 0x14
class USBCTL:
'''
USBCTL (r15) register bits
'''
hoscsten = 0x80
vbgate = 0x40
chipres = 0x20
pwrdown = 0x10
connect = 0x08
sigrwu = 0x04
class PINCTL:
'''
PINCTL (r17) register bits
'''
setup_data_avail = 0x20 # SUDAVIRQ
in3_buffer_avail = 0x10 # IN3BAVIRQ
in2_buffer_avail = 0x08 # IN2BAVIRQ
out1_data_avail = 0x04 # OUT1DAVIRQ
out0_data_avail = 0x02 # OUT0DAVIRQ
in0_buffer_avail = 0x01 # IN0BAVIRQ
<|code_end|>
. Write the next line using the current file imports:
import struct
from binascii import hexlify
from umap2.phy.iphy import PhyInterface
from umap2.phy.raspdancer.raspdancer import Raspdancer
and context from other files:
# Path: umap2/phy/iphy.py
# class PhyInterface(object):
# '''
# This class specifies the API that a physical interface should conform to
# '''
#
# def __init__(self, app, name):
# '''
# :type app: :class:`~umap2.app.base.Umap2App`
# :param app: application instance
# '''
# self.app = app
# self.name = name
# self.logger = logging.getLogger('umap2')
# self.stop = False
# self.connected_device = None
#
# def connect(self, usb_device):
# '''
# Connect a USB device
#
# :type usb_device: :class:`~umap2.core.usb_class.USBClass`
# :param usb_device: USB device class
# '''
# self.connected_device = usb_device
#
# def disconnect(self):
# '''
# Disconnect a device.
# Once this function returns, the phy doesn't have a reference to the
# device.
#
# :return: the disconnected device (if was connected)
# '''
# if self.connected_device:
# self.info('Disconnected device %s' % self.connected_device.name)
# else:
# self.info('Disconnect called when already disconnected')
# dev = self.connected_device
# self.connected_device = None
# return dev
#
# def is_connected(self):
# return self.connected_device is not None
#
# def send_on_endpoint(self, ep_num, data):
# '''
# Send data on a specific endpoint
#
# :param ep_num: number of endpoint
# :param data: data to send
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def stall_ep0(self):
# '''
# Stalls control endpoint (0)
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def run(self):
# '''
# Handle USB requests
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# Path: umap2/phy/raspdancer/raspdancer.py
# class Raspdancer:
#
# def __init__(self):
# GPIO.setmode(GPIO.BOARD)
# # pin15=GPIO22 is linked to MAX3420 -RST
# GPIO.setup(15, GPIO.OUT)
# GPIO.output(15,GPIO.LOW)
# GPIO.output(15,GPIO.HIGH)
# spi.openSPI(speed=26000000)
#
# def __del__(self):
# spi.closeSPI()
# GPIO.output(15,GPIO.LOW)
# GPIO.output(15,GPIO.HIGH)
# GPIO.cleanup()
#
# def transfer(self, data=[]):
# if isinstance(data,str):
# data = [ord(x) for x in data]
# data = tuple(data)
# data = spi.transfer(data)
# dataout = "".join([chr(x) for x in data])
# return dataout
, which may include functions, classes, or code. Output only the next line. | class RaspdancerPhy(PhyInterface): |
Given the following code snippet before the placeholder: <|code_start|> USBCTL (r15) register bits
'''
hoscsten = 0x80
vbgate = 0x40
chipres = 0x20
pwrdown = 0x10
connect = 0x08
sigrwu = 0x04
class PINCTL:
'''
PINCTL (r17) register bits
'''
setup_data_avail = 0x20 # SUDAVIRQ
in3_buffer_avail = 0x10 # IN3BAVIRQ
in2_buffer_avail = 0x08 # IN2BAVIRQ
out1_data_avail = 0x04 # OUT1DAVIRQ
out0_data_avail = 0x02 # OUT0DAVIRQ
in0_buffer_avail = 0x01 # IN0BAVIRQ
class RaspdancerPhy(PhyInterface):
# bitmask values for reg_pin_control = 0x11
interrupt_level = 0x08
full_duplex = 0x10
def __init__(self, app):
super(RaspdancerPhy, self).__init__(app, 'RaspdancerPhy')
<|code_end|>
, predict the next line using imports from the current file:
import struct
from binascii import hexlify
from umap2.phy.iphy import PhyInterface
from umap2.phy.raspdancer.raspdancer import Raspdancer
and context including class names, function names, and sometimes code from other files:
# Path: umap2/phy/iphy.py
# class PhyInterface(object):
# '''
# This class specifies the API that a physical interface should conform to
# '''
#
# def __init__(self, app, name):
# '''
# :type app: :class:`~umap2.app.base.Umap2App`
# :param app: application instance
# '''
# self.app = app
# self.name = name
# self.logger = logging.getLogger('umap2')
# self.stop = False
# self.connected_device = None
#
# def connect(self, usb_device):
# '''
# Connect a USB device
#
# :type usb_device: :class:`~umap2.core.usb_class.USBClass`
# :param usb_device: USB device class
# '''
# self.connected_device = usb_device
#
# def disconnect(self):
# '''
# Disconnect a device.
# Once this function returns, the phy doesn't have a reference to the
# device.
#
# :return: the disconnected device (if was connected)
# '''
# if self.connected_device:
# self.info('Disconnected device %s' % self.connected_device.name)
# else:
# self.info('Disconnect called when already disconnected')
# dev = self.connected_device
# self.connected_device = None
# return dev
#
# def is_connected(self):
# return self.connected_device is not None
#
# def send_on_endpoint(self, ep_num, data):
# '''
# Send data on a specific endpoint
#
# :param ep_num: number of endpoint
# :param data: data to send
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def stall_ep0(self):
# '''
# Stalls control endpoint (0)
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def run(self):
# '''
# Handle USB requests
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# Path: umap2/phy/raspdancer/raspdancer.py
# class Raspdancer:
#
# def __init__(self):
# GPIO.setmode(GPIO.BOARD)
# # pin15=GPIO22 is linked to MAX3420 -RST
# GPIO.setup(15, GPIO.OUT)
# GPIO.output(15,GPIO.LOW)
# GPIO.output(15,GPIO.HIGH)
# spi.openSPI(speed=26000000)
#
# def __del__(self):
# spi.closeSPI()
# GPIO.output(15,GPIO.LOW)
# GPIO.output(15,GPIO.HIGH)
# GPIO.cleanup()
#
# def transfer(self, data=[]):
# if isinstance(data,str):
# data = [ord(x) for x in data]
# data = tuple(data)
# data = spi.transfer(data)
# dataout = "".join([chr(x) for x in data])
# return dataout
. Output only the next line. | self.device = Raspdancer() |
Given the code snippet: <|code_start|>'''
Tempaltes related to generic enumeration stage
'''
# fields
# containers
# dynamic fields
# encoders
# Device descriptor
# Section 9.6.1, page 261
device_descriptor = Descriptor(
name='device_descriptor',
<|code_end|>
, generate the next line using the imports in this file:
from umap2.core.usb import DescriptorType
from kitty.model import LE16, UInt8, BitField, String, RandomBytes
from kitty.model import Template, Container, List
from kitty.model import ElementCount, SizeInBytes
from kitty.model import StrEncodeEncoder, ENC_INT_LE
from generic import Descriptor, SubDescriptor
and context (functions, classes, or occasionally code) from other files:
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
. Output only the next line. | descriptor_type=DescriptorType.device, |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
'''
Prepare stages for USB fuzzing
Usage:
umap2stages -P=PHY_INFO -C=DEVICE_CLASS -s=FILE [-q] [--vid=VID] [--pid=PID] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-C --class DEVICE_CLASS class of the device or path to python file with device class
-s --stage-file FILE file to store list of stages in
-q --quiet quiet mode. only print warning/error messages
-v --verbose verbosity level
--vid VID override vendor ID
--pid PID override product ID
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
'''
<|code_end|>
. Use current file imports:
import time
from umap2.apps.emulate import Umap2EmulationApp
from umap2.fuzz.helpers import StageLogger, set_stage_logger
and context (classes, functions, or code) from other files:
# Path: umap2/apps/emulate.py
# class Umap2EmulationApp(Umap2App):
#
# def run(self):
# self.fuzzer = self.get_fuzzer()
# self.phy = self.load_phy(self.options['--phy'])
# self.dev = self.load_device(self.options['--class'], self.phy)
# try:
# self.dev.connect()
# self.dev.run()
# except KeyboardInterrupt:
# self.logger.info('user terminated the run')
# except:
# self.logger.error('Got exception while connecting/running device')
# self.logger.error(traceback.format_exc())
# self.dev.disconnect()
#
# def get_fuzzer(self):
# return None
#
# Path: umap2/fuzz/helpers.py
# class StageLogger(object):
#
# def __init__(self, filename):
# self.filename = filename
# self.fd = None
#
# def start(self):
# self.fd = open(self.filename, 'wb')
#
# def stop(self):
# if self.fd:
# self.fd.close()
#
# def log_stage(self, stage):
# if self.fd:
# self.fd.write(stage + '\n')
# self.fd.flush()
#
# def set_stage_logger(logger):
# '''
# Set a new stage logger
# '''
# global stage_logger
# stage_logger = logger
. Output only the next line. | class Umap2MakeStagesApp(Umap2EmulationApp): |
Given snippet: <|code_start|>#!/usr/bin/env python
'''
Prepare stages for USB fuzzing
Usage:
umap2stages -P=PHY_INFO -C=DEVICE_CLASS -s=FILE [-q] [--vid=VID] [--pid=PID] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-C --class DEVICE_CLASS class of the device or path to python file with device class
-s --stage-file FILE file to store list of stages in
-q --quiet quiet mode. only print warning/error messages
-v --verbose verbosity level
--vid VID override vendor ID
--pid PID override product ID
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
'''
class Umap2MakeStagesApp(Umap2EmulationApp):
def load_device(self, dev_name, phy):
self.start_time = time.time()
self.stage_file_name = self.options['--stage-file']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from umap2.apps.emulate import Umap2EmulationApp
from umap2.fuzz.helpers import StageLogger, set_stage_logger
and context:
# Path: umap2/apps/emulate.py
# class Umap2EmulationApp(Umap2App):
#
# def run(self):
# self.fuzzer = self.get_fuzzer()
# self.phy = self.load_phy(self.options['--phy'])
# self.dev = self.load_device(self.options['--class'], self.phy)
# try:
# self.dev.connect()
# self.dev.run()
# except KeyboardInterrupt:
# self.logger.info('user terminated the run')
# except:
# self.logger.error('Got exception while connecting/running device')
# self.logger.error(traceback.format_exc())
# self.dev.disconnect()
#
# def get_fuzzer(self):
# return None
#
# Path: umap2/fuzz/helpers.py
# class StageLogger(object):
#
# def __init__(self, filename):
# self.filename = filename
# self.fd = None
#
# def start(self):
# self.fd = open(self.filename, 'wb')
#
# def stop(self):
# if self.fd:
# self.fd.close()
#
# def log_stage(self, stage):
# if self.fd:
# self.fd.write(stage + '\n')
# self.fd.flush()
#
# def set_stage_logger(logger):
# '''
# Set a new stage logger
# '''
# global stage_logger
# stage_logger = logger
which might include code, classes, or functions. Output only the next line. | stage_logger = StageLogger(self.stage_file_name) |
Given snippet: <|code_start|>#!/usr/bin/env python
'''
Prepare stages for USB fuzzing
Usage:
umap2stages -P=PHY_INFO -C=DEVICE_CLASS -s=FILE [-q] [--vid=VID] [--pid=PID] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-C --class DEVICE_CLASS class of the device or path to python file with device class
-s --stage-file FILE file to store list of stages in
-q --quiet quiet mode. only print warning/error messages
-v --verbose verbosity level
--vid VID override vendor ID
--pid PID override product ID
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
'''
class Umap2MakeStagesApp(Umap2EmulationApp):
def load_device(self, dev_name, phy):
self.start_time = time.time()
self.stage_file_name = self.options['--stage-file']
stage_logger = StageLogger(self.stage_file_name)
stage_logger.start()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from umap2.apps.emulate import Umap2EmulationApp
from umap2.fuzz.helpers import StageLogger, set_stage_logger
and context:
# Path: umap2/apps/emulate.py
# class Umap2EmulationApp(Umap2App):
#
# def run(self):
# self.fuzzer = self.get_fuzzer()
# self.phy = self.load_phy(self.options['--phy'])
# self.dev = self.load_device(self.options['--class'], self.phy)
# try:
# self.dev.connect()
# self.dev.run()
# except KeyboardInterrupt:
# self.logger.info('user terminated the run')
# except:
# self.logger.error('Got exception while connecting/running device')
# self.logger.error(traceback.format_exc())
# self.dev.disconnect()
#
# def get_fuzzer(self):
# return None
#
# Path: umap2/fuzz/helpers.py
# class StageLogger(object):
#
# def __init__(self, filename):
# self.filename = filename
# self.fd = None
#
# def start(self):
# self.fd = open(self.filename, 'wb')
#
# def stop(self):
# if self.fd:
# self.fd.close()
#
# def log_stage(self, stage):
# if self.fd:
# self.fd.write(stage + '\n')
# self.fd.flush()
#
# def set_stage_logger(logger):
# '''
# Set a new stage logger
# '''
# global stage_logger
# stage_logger = logger
which might include code, classes, or functions. Output only the next line. | set_stage_logger(stage_logger) |
Based on the snippet: <|code_start|>'''
USB Configuration class.
Each instance represents a single USB configuration.
In most cases it should not be subclassed.
'''
<|code_end|>
, predict the immediate next line with the help of imports:
import struct
from umap2.core.usb_base import USBBaseActor
from umap2.core.usb import DescriptorType
from umap2.fuzz.helpers import mutable
and context (classes, functions, sometimes code) from other files:
# Path: umap2/core/usb_base.py
# class USBBaseActor(object):
#
# name = 'Actor'
#
# def __init__(self, app, phy):
# '''
# :param app: Umap2 application
# :param phy: Physical connection
# '''
# self.phy = phy
# self.app = app
# self.session_data = {}
# self.str_dict = {}
# self.logger = logging.getLogger('umap2')
#
# def get_mutation(self, stage, data=None):
# '''
# :param stage: stage name
# :param data: dictionary (string: bytearray) of data for the fuzzer (default: None)
# :return: mutation for current stage, None if not current fuzzing stage
# '''
# return self.app.get_mutation(stage, data)
#
# def send_on_endpoint(self, ep, data):
# '''
# Send data on a given endpoint
#
# :param ep: endpoint number
# :param data: data to send
# '''
# self.phy.send_on_endpoint(ep, data)
#
# def get_session_data(self, stage):
# '''
# If an entity wants to pass specific data to the fuzzer when getting a mutation,
# it could return a session data here.
# This session data should be a dictionary of string:bytearray.
# The keys of the dictionary should match the keys in the templates.
#
# :param stage: stage that the session data is for
# :return: dictionary of session data
# '''
# return self.session_data
#
# def usb_function_supported(self, reason=None):
# '''
# Mark current USB function as supported by the host.
# This will tell the application to stop emulating current device.
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# self.app.usb_function_supported(reason)
#
# def add_string_with_id(self, str_id, s):
# '''
# Add a string to the string dictionary
#
# :param str_id: id of the string
# :param s: the string
# '''
# self.str_dict[str_id] = s
#
# def get_string_by_id(self, str_id):
# '''
# Get a string by it's id
#
# :param str_id: string id
# :return: the string, or None if id does not exist
# '''
# self.debug('Getting string by id %#x' % (str_id))
# if str_id in self.str_dict:
# return self.str_dict[str_id]
# return None
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
#
# Path: umap2/fuzz/helpers.py
# def mutable(stage, silent=False):
# def wrap_f(func):
# func_self = None
# if inspect.ismethod(func):
# func_self = func.im_self
# func = func.im_func
#
# def wrapper(*args, **kwargs):
# if func_self is None:
# self = args[0]
# args = tuple(args[1:])
# else:
# self = func_self
# response = None
# valid_req = kwargs.get('valid', False)
# info = self.info if not silent else self.debug
# if not valid_req:
# log_stage(stage)
# session_data = self.get_session_data(stage)
# data = kwargs.get('fuzzing_data', {})
# data.update(session_data)
# response = self.get_mutation(stage=stage, data=data)
# try:
# if response is not None:
# if not silent:
# info('Got mutation for stage %s' % stage)
# else:
# if valid_req:
# info('Calling %s' % (func.__name__))
# else:
# info('Calling %s (stage: "%s")' % (func.__name__, stage))
# response = func(self, *args, **kwargs)
# except Exception as e:
# self.logger.error(traceback.format_exc())
# self.logger.error(''.join(traceback.format_stack()))
# raise e
# if response is not None:
# info('Response: %s' % binascii.hexlify(response))
# return response
# return wrapper
# return wrap_f
. Output only the next line. | class USBConfiguration(USBBaseActor): |
Given the code snippet: <|code_start|>'''
Try to detect OS based on the USB traffic.
Not implemented yet.
Usage:
umap2detect -P=PHY_INFO [-q] [-v ...]
Options:
-P --phy PHY_INFO physical layer info, see list below
-v --verbose verbosity level
-q --quiet quiet mode. only print warning/error messages
Physical layer:
fd:<serial_port> use facedancer connected to given serial port
gadgetfs use gadgetfs (requires mounting of gadgetfs beforehand)
Example:
umap2detect -P fd:/dev/ttyUSB0 -q
'''
<|code_end|>
, generate the next line using the imports in this file:
from umap2.apps.base import Umap2App
and context (functions, classes, or occasionally code) from other files:
# Path: umap2/apps/base.py
# class Umap2App(object):
#
# def __init__(self, docstring=None):
# if docstring is not None:
# self.options = docopt.docopt(docstring)
# else:
# self.options = {}
# self.umap_class_dict = {
# 'audio': ('audio', 'Headset'),
# 'billboard': ('billboard', 'A billboard, requires USB 2.1 and higher'),
# 'cdc_acm': ('cdc_acm', 'Abstract Control Model device (like serial modem)'),
# 'cdc_dl': ('cdc_dl', 'Direct Line Control device (like modem)'),
# 'ftdi': ('ftdi', 'USB<->RS232 FTDI chip'),
# 'hub': ('hub', 'USB hub'),
# 'keyboard': ('keyboard', 'Keyboard'),
# 'mass_storage': ('mass_storage', 'Disk on key'),
# 'mtp': ('mtp', 'Android phone'),
# 'printer': ('printer', 'Printer'),
# 'smartcard': ('smartcard', 'USB<->smart card interface'),
# }
# self.umap_classes = sorted(self.umap_class_dict.keys())
# self.logger = self.get_logger()
# self.num_processed = 0
# self.fuzzer = None
# self.setup_packet_received = False
#
# def get_logger(self):
# levels = {
# 0: logging.INFO,
# 1: logging.DEBUG,
# # verbose is added by umap2.__init__ module
# 2: logging.VERBOSE,
# }
# verbose = self.options.get('--verbose', 0)
# logger = logging.getLogger('umap2')
# if verbose in levels:
# set_default_handler_level(levels[verbose])
# else:
# set_default_handler_level(logging.VERBOSE)
# if self.options.get('--quiet', False):
# set_default_handler_level(logging.WARNING)
# return logger
#
# def load_phy(self, phy_string):
# self.logger.info('Loading physical interface: %s' % phy_string)
# phy_arr = phy_string.split(':')
# phy_type = phy_arr[0]
# if phy_type == 'fd':
# self.logger.debug('Physical interface is facedancer')
# dev_name = phy_arr[1]
# s = Serial(dev_name, 115200, parity=PARITY_NONE, timeout=2)
# # fd = Facedancer(s)
# phy = Max342xPhy(self, s)
# return phy
# elif phy_type == 'rd':
# try:
# from umap2.phy.raspdancer.raspdancer_phy import RaspdancerPhy
# self.logger.debug('Physical interface is raspdancer')
# phy = RaspdancerPhy(self)
# return phy
# except ImportError:
# raise Exception('Raspdancer support misses spi module and/or gpio module.')
# elif phy_type == 'gadgetfs':
# self.logger.debug('Physical interface is GadgetFs')
# phy = GadgetFsPhy(self)
# return phy
# raise Exception('Phy type not supported: %s' % phy_type)
#
# def load_device(self, dev_name, phy):
# if dev_name in self.umap_classes:
# self.logger.info('Loading USB device %s' % dev_name)
# module_name = self.umap_class_dict[dev_name][0]
# module = importlib.import_module('umap2.dev.%s' % module_name)
# else:
# self.logger.info('Loading custom USB device from file: %s' % dev_name)
# dirpath, filename = os.path.split(dev_name)
# modulename = filename[:-3]
# if dirpath in sys.path:
# sys.path.remove(dirpath)
# sys.path.insert(0, dirpath)
# module = __import__(modulename, globals(), locals(), [], -1)
# usb_device = module.usb_device
# kwargs = self.get_user_device_kwargs()
# dev = usb_device(self, phy, **kwargs)
# return dev
#
# def get_user_device_kwargs(self):
# '''
# if user provides values for the device, get them here
# '''
# kwargs = {}
# self.update_from_user_param('--vid', 'vid', kwargs, 'int')
# self.update_from_user_param('--pid', 'pid', kwargs, 'int')
# return kwargs
#
# def update_from_user_param(self, flag, arg_name, kwargs, type):
# val = self.options.get(flag, None)
# if val is not None:
# if type == 'int':
# kwargs[arg_name] = int(val, 0)
# self.logger.info('Setting user-supplied %s: %#x' % (arg_name, kwargs[arg_name]))
# else:
# raise Exception('arg type not supported!!')
#
# def signal_setup_packet_received(self):
# '''
# Signal that we received a setup packet from the host (host is alive)
# '''
# self.setup_packet_received = True
#
# def should_stop_phy(self):
# '''
# :return: whether phy should stop serving.
# '''
# return False
#
# def usb_function_supported(self, reason=None):
# '''
# Callback from a USB device, notifying that the current USB device
# is supported by the host.
# By default, do nothing with this information
#
# :param reason: reason why we decided it is supported (default: None)
# '''
# pass
#
# def get_mutation(self, stage, data=None):
# '''
# mutation is only needed when fuzzing
# '''
# return None
. Output only the next line. | class Umap2DetectOSApp(Umap2App): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.