identifier
stringlengths 0
89
| parameters
stringlengths 0
399
| return_statement
stringlengths 0
982
⌀ | docstring
stringlengths 10
3.04k
| docstring_summary
stringlengths 0
3.04k
| function
stringlengths 13
25.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | argument_list
null | language
stringclasses 3
values | docstring_language
stringclasses 4
values | docstring_language_predictions
stringclasses 4
values | is_langid_reliable
stringclasses 2
values | is_langid_extra_reliable
bool 1
class | type
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
teste | (area) | return dict(nome=area) | Rederizando uma view com o decorador do jinja. | Rederizando uma view com o decorador do jinja. | def teste(area):
"""Rederizando uma view com o decorador do jinja."""
return dict(nome=area) | [
"def",
"teste",
"(",
"area",
")",
":",
"return",
"dict",
"(",
"nome",
"=",
"area",
")"
] | [
10,
0
] | [
12,
26
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
create_aliens | (ai_settings, screen, aliens, alien_number, row_number) | Cria um alien e o posiciona na tela | Cria um alien e o posiciona na tela | def create_aliens(ai_settings, screen, aliens, alien_number, row_number):
"""Cria um alien e o posiciona na tela"""
alien = Alien(ai_settings, screen)
position_aliens(alien, aliens, alien_number, row_number) | [
"def",
"create_aliens",
"(",
"ai_settings",
",",
"screen",
",",
"aliens",
",",
"alien_number",
",",
"row_number",
")",
":",
"alien",
"=",
"Alien",
"(",
"ai_settings",
",",
"screen",
")",
"position_aliens",
"(",
"alien",
",",
"aliens",
",",
"alien_number",
",",
"row_number",
")"
] | [
205,
0
] | [
208,
60
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Scoreboard.__init__ | (self, ai_settings, screen, stats) | Inicia os atributos da pontuação | Inicia os atributos da pontuação | def __init__(self, ai_settings, screen, stats):
"""Inicia os atributos da pontuação"""
self.screen = screen
self.screen_rect = screen.get_rect()
self.ai_settings = ai_settings
self.stats = stats
# Configurações da fonte para as informações de pontuação
self.text_color = (255, 255, 255)
self.font = pygame.font.SysFont(None, 32)
# Prepara a imagem da pontuação inicial
self.prep_score()
self.prep_high_score()
self.prep_level()
self.prep_ships() | [
"def",
"__init__",
"(",
"self",
",",
"ai_settings",
",",
"screen",
",",
"stats",
")",
":",
"self",
".",
"screen",
"=",
"screen",
"self",
".",
"screen_rect",
"=",
"screen",
".",
"get_rect",
"(",
")",
"self",
".",
"ai_settings",
"=",
"ai_settings",
"self",
".",
"stats",
"=",
"stats",
"# Configurações da fonte para as informações de pontuação",
"self",
".",
"text_color",
"=",
"(",
"255",
",",
"255",
",",
"255",
")",
"self",
".",
"font",
"=",
"pygame",
".",
"font",
".",
"SysFont",
"(",
"None",
",",
"32",
")",
"# Prepara a imagem da pontuação inicial",
"self",
".",
"prep_score",
"(",
")",
"self",
".",
"prep_high_score",
"(",
")",
"self",
".",
"prep_level",
"(",
")",
"self",
".",
"prep_ships",
"(",
")"
] | [
8,
4
] | [
23,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DocumentStore.rollback | (self, id: str) | Delela documento com o ID informado. | Delela documento com o ID informado. | def rollback(self, id: str) -> None:
"""Delela documento com o ID informado."""
self.delete_one({"_id": id}) | [
"def",
"rollback",
"(",
"self",
",",
"id",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"delete_one",
"(",
"{",
"\"_id\"",
":",
"id",
"}",
")"
] | [
50,
4
] | [
52,
36
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
cadastro | (request) | Cadastra um novo usuário no sistema | Cadastra um novo usuário no sistema | def cadastro(request):
"""Cadastra um novo usuário no sistema"""
if request.method == 'POST':
nome = request.POST['nome']
email = request.POST['email']
senha = request.POST['password']
senha2 = request.POST['password2']
if campo_vazio(nome):
messages.error(request, 'O nome não pode ficar em branco')
return redirect('cadastro')
if campo_vazio(email):
messages.error(request, 'O e-mail não pode ficar em branco')
return redirect('cadastro')
if senhas_nao_iguais(senha, senha2):
messages.error(request, 'As senhas digitadas não são iguais')
return redirect('cadastro')
# verificando pelo e-mail se o usuário já está no banco de dados
if User.objects.filter(email=email).exists():
messages.error(request, 'E-mail já cadastrado')
return redirect('cadastro')
if User.objects.filter(username=nome).exists():
messages.error(request, 'Nome já cadastrado')
return redirect('cadastro')
user = User.objects.create_user(username=nome, email=email, password=senha)
user.save()
messages.success(request, 'Usuário cadastrado com sucesso')
return redirect('login')
else:
return render(request, 'usuarios/cadastro.html') | [
"def",
"cadastro",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"nome",
"=",
"request",
".",
"POST",
"[",
"'nome'",
"]",
"email",
"=",
"request",
".",
"POST",
"[",
"'email'",
"]",
"senha",
"=",
"request",
".",
"POST",
"[",
"'password'",
"]",
"senha2",
"=",
"request",
".",
"POST",
"[",
"'password2'",
"]",
"if",
"campo_vazio",
"(",
"nome",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'O nome não pode ficar em branco')",
"",
"return",
"redirect",
"(",
"'cadastro'",
")",
"if",
"campo_vazio",
"(",
"email",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'O e-mail não pode ficar em branco')",
"",
"return",
"redirect",
"(",
"'cadastro'",
")",
"if",
"senhas_nao_iguais",
"(",
"senha",
",",
"senha2",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'As senhas digitadas não são iguais')",
"",
"return",
"redirect",
"(",
"'cadastro'",
")",
"# verificando pelo e-mail se o usuário já está no banco de dados",
"if",
"User",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"email",
")",
".",
"exists",
"(",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'E-mail já cadastrado')",
"",
"return",
"redirect",
"(",
"'cadastro'",
")",
"if",
"User",
".",
"objects",
".",
"filter",
"(",
"username",
"=",
"nome",
")",
".",
"exists",
"(",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'Nome já cadastrado')",
"",
"return",
"redirect",
"(",
"'cadastro'",
")",
"user",
"=",
"User",
".",
"objects",
".",
"create_user",
"(",
"username",
"=",
"nome",
",",
"email",
"=",
"email",
",",
"password",
"=",
"senha",
")",
"user",
".",
"save",
"(",
")",
"messages",
".",
"success",
"(",
"request",
",",
"'Usuário cadastrado com sucesso')",
"",
"return",
"redirect",
"(",
"'login'",
")",
"else",
":",
"return",
"render",
"(",
"request",
",",
"'usuarios/cadastro.html'",
")"
] | [
6,
0
] | [
34,
56
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EquipamentoAcessoResource.handle_put | (self, request, user, *args, **kwargs) | Trata uma requisição PUT para alterar informações de acesso a equipamentos.
URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/
| Trata uma requisição PUT para alterar informações de acesso a equipamentos. | def handle_put(self, request, user, *args, **kwargs):
"""Trata uma requisição PUT para alterar informações de acesso a equipamentos.
URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/
"""
# Obtém dados do request e verifica acesso
try:
# Obtém argumentos passados na URL
id_equipamento = kwargs.get('id_equipamento')
if id_equipamento is None:
return self.response_error(147)
id_tipo_acesso = kwargs.get('id_tipo_acesso')
if id_tipo_acesso is None:
return self.response_error(208)
# Após obtenção do id_equipamento podemos verificar a permissão
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION,
None,
id_equipamento,
AdminPermission.EQUIP_WRITE_OPERATION):
return self.not_authorized()
# Obtém dados do XML
xml_map, attrs_map = loads(request.raw_post_data)
# Obtém o mapa correspondente ao root node do mapa do XML
# (networkapi)
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')
# Verifica a existência do node "equipamento_acesso"
equipamento_acesso_map = networkapi_map.get('equipamento_acesso')
if equipamento_acesso_map is None:
return self.response_error(3, u'Não existe valor para a tag equipamento_acesso do XML de requisição.')
# Verifica a existência do valor "fqdn"
fqdn = equipamento_acesso_map.get('fqdn')
if fqdn is None:
return self.response_error(205)
# Verifica a existência do valor "user"
username = equipamento_acesso_map.get('user')
if username is None:
return self.response_error(206)
# Verifica a existência do valor "pass"
password = equipamento_acesso_map.get('pass')
if password is None:
return self.response_error(207)
# Obtém o valor de "enable_pass"
enable_pass = equipamento_acesso_map.get('enable_pass')
with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):
# Altera a informação de acesso ao equipamentoconforme dados
# recebidos no XML
EquipamentoAcesso.update(user,
id_equipamento,
id_tipo_acesso,
fqdn=fqdn,
user=username,
password=password,
enable_pass=enable_pass
)
# Retorna response vazio em caso de sucesso
return self.response(dumps_networkapi({}))
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
except EquipamentoNotFoundError:
return self.response_error(117, id_equipamento)
except EquipamentoAcesso.DoesNotExist:
return self.response_error(209, id_equipamento, id_tipo_acesso)
except (EquipamentoError, GrupoError):
return self.response_error(1) | [
"def",
"handle_put",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Obtém dados do request e verifica acesso",
"try",
":",
"# Obtém argumentos passados na URL",
"id_equipamento",
"=",
"kwargs",
".",
"get",
"(",
"'id_equipamento'",
")",
"if",
"id_equipamento",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"147",
")",
"id_tipo_acesso",
"=",
"kwargs",
".",
"get",
"(",
"'id_tipo_acesso'",
")",
"if",
"id_tipo_acesso",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"208",
")",
"# Após obtenção do id_equipamento podemos verificar a permissão",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"None",
",",
"id_equipamento",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"# Obtém dados do XML",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"# Obtém o mapa correspondente ao root node do mapa do XML",
"# (networkapi)",
"networkapi_map",
"=",
"xml_map",
".",
"get",
"(",
"'networkapi'",
")",
"if",
"networkapi_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag networkapi do XML de requisição.')",
"",
"# Verifica a existência do node \"equipamento_acesso\"",
"equipamento_acesso_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'equipamento_acesso'",
")",
"if",
"equipamento_acesso_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag equipamento_acesso do XML de requisição.')",
"",
"# Verifica a existência do valor \"fqdn\"",
"fqdn",
"=",
"equipamento_acesso_map",
".",
"get",
"(",
"'fqdn'",
")",
"if",
"fqdn",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"205",
")",
"# Verifica a existência do valor \"user\"",
"username",
"=",
"equipamento_acesso_map",
".",
"get",
"(",
"'user'",
")",
"if",
"username",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"206",
")",
"# Verifica a existência do valor \"pass\"",
"password",
"=",
"equipamento_acesso_map",
".",
"get",
"(",
"'pass'",
")",
"if",
"password",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"207",
")",
"# Obtém o valor de \"enable_pass\"",
"enable_pass",
"=",
"equipamento_acesso_map",
".",
"get",
"(",
"'enable_pass'",
")",
"with",
"distributedlock",
"(",
"LOCK_EQUIPMENT_ACCESS",
"%",
"id_tipo_acesso",
")",
":",
"# Altera a informação de acesso ao equipamentoconforme dados",
"# recebidos no XML",
"EquipamentoAcesso",
".",
"update",
"(",
"user",
",",
"id_equipamento",
",",
"id_tipo_acesso",
",",
"fqdn",
"=",
"fqdn",
",",
"user",
"=",
"username",
",",
"password",
"=",
"password",
",",
"enable_pass",
"=",
"enable_pass",
")",
"# Retorna response vazio em caso de sucesso",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisição.')",
"",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"id_equipamento",
")",
"except",
"EquipamentoAcesso",
".",
"DoesNotExist",
":",
"return",
"self",
".",
"response_error",
"(",
"209",
",",
"id_equipamento",
",",
"id_tipo_acesso",
")",
"except",
"(",
"EquipamentoError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
222,
4
] | [
305,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
fetch_stages_to_do | (path: str, all_stages: List[str]) | Retorna a lista de estágios a serem processados
e a quantidade de estágios já realizados | Retorna a lista de estágios a serem processados
e a quantidade de estágios já realizados | def fetch_stages_to_do(path: str, all_stages: List[str]) -> Tuple[Set[str], Set[str], str]:
"""Retorna a lista de estágios a serem processados
e a quantidade de estágios já realizados"""
with open(path, "r") as file:
stages_already_done = file.readlines()
stages_to_do = set(all_stages) - set(stages_already_done)
return stages_to_do, stages_already_done, path | [
"def",
"fetch_stages_to_do",
"(",
"path",
":",
"str",
",",
"all_stages",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"str",
"]",
",",
"Set",
"[",
"str",
"]",
",",
"str",
"]",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"file",
":",
"stages_already_done",
"=",
"file",
".",
"readlines",
"(",
")",
"stages_to_do",
"=",
"set",
"(",
"all_stages",
")",
"-",
"set",
"(",
"stages_already_done",
")",
"return",
"stages_to_do",
",",
"stages_already_done",
",",
"path"
] | [
144,
0
] | [
151,
54
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
link_journals_and_issues | (**kwargs) | Atualiza o relacionamento entre Journal e Issue. | Atualiza o relacionamento entre Journal e Issue. | def link_journals_and_issues(**kwargs):
"""Atualiza o relacionamento entre Journal e Issue."""
issue_json_path = kwargs["ti"].xcom_pull(
task_ids="copy_mst_bases_to_work_folder_task", key="issue_json_path"
)
with open(issue_json_path) as f:
issues = json.load(f)
logging.info("reading file from %s." % (issue_json_path))
journal_issues = mount_journals_issues_link(issues)
update_journals_and_issues_link(journal_issues) | [
"def",
"link_journals_and_issues",
"(",
"*",
"*",
"kwargs",
")",
":",
"issue_json_path",
"=",
"kwargs",
"[",
"\"ti\"",
"]",
".",
"xcom_pull",
"(",
"task_ids",
"=",
"\"copy_mst_bases_to_work_folder_task\"",
",",
"key",
"=",
"\"issue_json_path\"",
")",
"with",
"open",
"(",
"issue_json_path",
")",
"as",
"f",
":",
"issues",
"=",
"json",
".",
"load",
"(",
"f",
")",
"logging",
".",
"info",
"(",
"\"reading file from %s.\"",
"%",
"(",
"issue_json_path",
")",
")",
"journal_issues",
"=",
"mount_journals_issues_link",
"(",
"issues",
")",
"update_journals_and_issues_link",
"(",
"journal_issues",
")"
] | [
425,
0
] | [
437,
51
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Analisador.generate_pivottable | (self, dataProcessamento:str, inputPath: str, filesNamePrefix: str, outputPath: str) | Função para montar pivot table com resultados finais
a partir dos arquivos processados previamente atraves do metodo analise
Parâmetros:
dataProcessamento: dia do processamento
path: caminho para destino do resultado final
| Função para montar pivot table com resultados finais
a partir dos arquivos processados previamente atraves do metodo analise
Parâmetros:
dataProcessamento: dia do processamento
path: caminho para destino do resultado final
| def generate_pivottable(self, dataProcessamento:str, inputPath: str, filesNamePrefix: str, outputPath: str):
'''Função para montar pivot table com resultados finais
a partir dos arquivos processados previamente atraves do metodo analise
Parâmetros:
dataProcessamento: dia do processamento
path: caminho para destino do resultado final
'''
try:
os.makedirs(outputPath)
except OSError as e:
if e.errno != errno.EEXIST:
raise
total = pd.DataFrame()
files_results = glob.glob(inputPath+"/*"+str(filesNamePrefix)+"*.csv")
for files in files_results:
final_result_dataset = pd.read_csv(files)
total = pd.concat([total, final_result_dataset], axis=0)
total.to_csv(outputPath+"/Final_Result_{}_{}.csv".format(filesNamePrefix, dataProcessamento), index=False)
classifiers = total["Classifier_Model"].unique()
for metric in self.metrics:
for classifier in classifiers:
df = total[total['Classifier_Model'] == classifier].pivot_table(index='Data_Set', columns=['Embedding'],
values=[metric])
df.to_csv(outputPath+"/pivot_{}_{}_{}_{}.csv".format(classifier,metric, filesNamePrefix, dataProcessamento))
dfBestRes = total.pivot_table(index='Data_Set', columns=['Embedding'], values=[metric], aggfunc='max')
dfBestRes.to_csv(outputPath + "/Best_Result_overall_{}_{}_{}.csv".format(metric,filesNamePrefix, dataProcessamento))
print("Pivot tables salvas!") | [
"def",
"generate_pivottable",
"(",
"self",
",",
"dataProcessamento",
":",
"str",
",",
"inputPath",
":",
"str",
",",
"filesNamePrefix",
":",
"str",
",",
"outputPath",
":",
"str",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"outputPath",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"total",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"files_results",
"=",
"glob",
".",
"glob",
"(",
"inputPath",
"+",
"\"/*\"",
"+",
"str",
"(",
"filesNamePrefix",
")",
"+",
"\"*.csv\"",
")",
"for",
"files",
"in",
"files_results",
":",
"final_result_dataset",
"=",
"pd",
".",
"read_csv",
"(",
"files",
")",
"total",
"=",
"pd",
".",
"concat",
"(",
"[",
"total",
",",
"final_result_dataset",
"]",
",",
"axis",
"=",
"0",
")",
"total",
".",
"to_csv",
"(",
"outputPath",
"+",
"\"/Final_Result_{}_{}.csv\"",
".",
"format",
"(",
"filesNamePrefix",
",",
"dataProcessamento",
")",
",",
"index",
"=",
"False",
")",
"classifiers",
"=",
"total",
"[",
"\"Classifier_Model\"",
"]",
".",
"unique",
"(",
")",
"for",
"metric",
"in",
"self",
".",
"metrics",
":",
"for",
"classifier",
"in",
"classifiers",
":",
"df",
"=",
"total",
"[",
"total",
"[",
"'Classifier_Model'",
"]",
"==",
"classifier",
"]",
".",
"pivot_table",
"(",
"index",
"=",
"'Data_Set'",
",",
"columns",
"=",
"[",
"'Embedding'",
"]",
",",
"values",
"=",
"[",
"metric",
"]",
")",
"df",
".",
"to_csv",
"(",
"outputPath",
"+",
"\"/pivot_{}_{}_{}_{}.csv\"",
".",
"format",
"(",
"classifier",
",",
"metric",
",",
"filesNamePrefix",
",",
"dataProcessamento",
")",
")",
"dfBestRes",
"=",
"total",
".",
"pivot_table",
"(",
"index",
"=",
"'Data_Set'",
",",
"columns",
"=",
"[",
"'Embedding'",
"]",
",",
"values",
"=",
"[",
"metric",
"]",
",",
"aggfunc",
"=",
"'max'",
")",
"dfBestRes",
".",
"to_csv",
"(",
"outputPath",
"+",
"\"/Best_Result_overall_{}_{}_{}.csv\"",
".",
"format",
"(",
"metric",
",",
"filesNamePrefix",
",",
"dataProcessamento",
")",
")",
"print",
"(",
"\"Pivot tables salvas!\"",
")"
] | [
273,
4
] | [
308,
37
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
AtorTestes.teste_status | (self) | Confere status de um ator | Confere status de um ator | def teste_status(self):
ator = Ator()
'Confere status de um ator'
# Conferencia de caracter de ator ativo
self.assertEqual(ATIVO, ator.status(0))
# Colidindo ator com ele mesmo para alterar seu status para destruido
ator._tempo_de_colisao = 3.2
self.assertEqual(ATIVO, ator.status(3.1),
'Status para tempo 3.1 de jogo deveria mostrar status ativo, já que é menor que o tempo de colisão 3.2')
self.assertEqual(DESTRUIDO, ator.status(3.2),
'Status para tempo 3.2 de jogo deveria mostrar status destruido, já que é igual ao tempo de colisão 3.2')
self.assertEqual(DESTRUIDO, ator.status(4),
'Status para tempo 4 de jogo deveria mostrar status destruido, já que é maior que o tempo de colisão 3.2') | [
"def",
"teste_status",
"(",
"self",
")",
":",
"ator",
"=",
"Ator",
"(",
")",
"# Conferencia de caracter de ator ativo",
"self",
".",
"assertEqual",
"(",
"ATIVO",
",",
"ator",
".",
"status",
"(",
"0",
")",
")",
"# Colidindo ator com ele mesmo para alterar seu status para destruido",
"ator",
".",
"_tempo_de_colisao",
"=",
"3.2",
"self",
".",
"assertEqual",
"(",
"ATIVO",
",",
"ator",
".",
"status",
"(",
"3.1",
")",
",",
"'Status para tempo 3.1 de jogo deveria mostrar status ativo, já que é menor que o tempo de colisão 3.2')",
"",
"self",
".",
"assertEqual",
"(",
"DESTRUIDO",
",",
"ator",
".",
"status",
"(",
"3.2",
")",
",",
"'Status para tempo 3.2 de jogo deveria mostrar status destruido, já que é igual ao tempo de colisão 3.2')",
"",
"self",
".",
"assertEqual",
"(",
"DESTRUIDO",
",",
"ator",
".",
"status",
"(",
"4",
")",
",",
"'Status para tempo 4 de jogo deveria mostrar status destruido, já que é maior que o tempo de colisão 3.2')",
""
] | [
42,
4
] | [
56,
134
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
suspend_proc | () | Suspende o processo ativo (em destaque na interface).
Exceptions:
NoSuchProcess: quando o processo referente ao pid não é
encontrado. | Suspende o processo ativo (em destaque na interface). | def suspend_proc():
""" Suspende o processo ativo (em destaque na interface).
Exceptions:
NoSuchProcess: quando o processo referente ao pid não é
encontrado. """
pid = get_current_process()
p = psutil.Process(pid)
p.suspend() | [
"def",
"suspend_proc",
"(",
")",
":",
"pid",
"=",
"get_current_process",
"(",
")",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"p",
".",
"suspend",
"(",
")"
] | [
65,
0
] | [
74,
15
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
eh_quadrada | (matriz) | Recebe uma matriz númerica e confere se suas
dimensões constituem uma matriz quadrada
list -> boolean | Recebe uma matriz númerica e confere se suas
dimensões constituem uma matriz quadrada
list -> boolean | def eh_quadrada(matriz):
""" Recebe uma matriz númerica e confere se suas
dimensões constituem uma matriz quadrada
list -> boolean """
linhas = len(matriz)
if matriz == []:
colunas = 0
else:
colunas = len(matriz[0])
if linhas == colunas:
return True
else:
return False | [
"def",
"eh_quadrada",
"(",
"matriz",
")",
":",
"linhas",
"=",
"len",
"(",
"matriz",
")",
"if",
"matriz",
"==",
"[",
"]",
":",
"colunas",
"=",
"0",
"else",
":",
"colunas",
"=",
"len",
"(",
"matriz",
"[",
"0",
"]",
")",
"if",
"linhas",
"==",
"colunas",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | [
0,
0
] | [
12,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Stack.peek | (self) | Retorna o topo da pilha sem remoção | Retorna o topo da pilha sem remoção | def peek(self):
""" Retorna o topo da pilha sem remoção"""
if self._size > 0:
return self.top.data # valor do topo
raise IndexError('The stack is empty!') | [
"def",
"peek",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
">",
"0",
":",
"return",
"self",
".",
"top",
".",
"data",
"# valor do topo",
"raise",
"IndexError",
"(",
"'The stack is empty!'",
")"
] | [
23,
4
] | [
27,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CallbackARQ.mecanismoARQ | (self, evento) | MEF mecanismo ARQ: Parâmetro deve ser um objeto Evento | MEF mecanismo ARQ: Parâmetro deve ser um objeto Evento | def mecanismoARQ(self, evento):
''' MEF mecanismo ARQ: Parâmetro deve ser um objeto Evento '''
if self.atual == Estados.Ocioso: # Ocioso
if evento.tipo == TipoEvento.DATA:
self.tratamentoEventoData(evento.dados)
elif evento.tipo == TipoEvento.Payload:
# print('payload', self.atual)
self.atual = Estados.Espera
evento.dados.sequencia = self.tx
evento.dados.tipo = 0
self.quadroANTERIOR = evento.dados # Armazena quadro enviado
self.lower.envia(evento.dados)
self.reload_timeout()
self.enable_timeout() # Habilitando Timeout padrao
self.upper.disable() # Bloqueia recebimento de dados superiores
else:
print('erro ARQ')
elif self.atual == Estados.Espera: # Espera
if evento.tipo == TipoEvento.DATA:
self.tratamentoEventoData(evento.dados)
elif evento.tipo == TipoEvento.Timeout:
# print('timeout',self.atual)
self.atual = Estados.BackoffTX # Mudando de estado
self.enable_timeout() # Habilitando timer
elif evento.tipo == TipoEvento.ACK_TX:
if evento.dados.sequencia != self.tx:
# print('ACK tx errado', self.atual)
self.atual = Estados.BackoffTX # Mudando de estado
timer = self.timeslot * random.randint(0, 7)
self.timeout = timer # Habilitando timer
# self.reload_timeout()
self.enable_timeout()
else:
# print('ACK tx certo', self.atual)
self.tx = self.tx ^ 1
self.atual = Estados.BackoffRX
timer = self.timeslot * random.randint(0, 7)
self.timeout = timer # Habilitando timer
# self.reload_timeout()
self.enable_timeout()
else:
print('erro ARQ')
elif self.atual == Estados.BackoffTX: # BackoffTX
if evento.tipo == TipoEvento.DATA:
self.tratamentoEventoData(evento.dados)
elif evento.tipo == TipoEvento.Timeout:
# print('reenviando')
self.lower.envia(self.quadroANTERIOR) # Retransmissão quadro ack_not_TX
self.atual = Estados.Espera # Mudanca de estado
self.reload_timeout()
self.enable_timeout() # Timeout padrao
elif self.atual == Estados.BackoffRX: # BackoffRX
if evento.tipo == TipoEvento.DATA:
self.tratamentoEventoData(evento.dados)
self.disable_timeout()
self.atual = Estados.Ocioso
self.upper.enable()
elif evento.tipo == TipoEvento.Timeout:
# print('voltando para ocioso')
self.atual = Estados.Ocioso # Mudanca de estado
self.upper.enable() # Habilitando camada superior
self.disable_timeout()
else:
print('Estado MEF não existente!') | [
"def",
"mecanismoARQ",
"(",
"self",
",",
"evento",
")",
":",
"if",
"self",
".",
"atual",
"==",
"Estados",
".",
"Ocioso",
":",
"# Ocioso",
"if",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"DATA",
":",
"self",
".",
"tratamentoEventoData",
"(",
"evento",
".",
"dados",
")",
"elif",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"Payload",
":",
"# print('payload', self.atual)",
"self",
".",
"atual",
"=",
"Estados",
".",
"Espera",
"evento",
".",
"dados",
".",
"sequencia",
"=",
"self",
".",
"tx",
"evento",
".",
"dados",
".",
"tipo",
"=",
"0",
"self",
".",
"quadroANTERIOR",
"=",
"evento",
".",
"dados",
"# Armazena quadro enviado",
"self",
".",
"lower",
".",
"envia",
"(",
"evento",
".",
"dados",
")",
"self",
".",
"reload_timeout",
"(",
")",
"self",
".",
"enable_timeout",
"(",
")",
"# Habilitando Timeout padrao",
"self",
".",
"upper",
".",
"disable",
"(",
")",
"# Bloqueia recebimento de dados superiores",
"else",
":",
"print",
"(",
"'erro ARQ'",
")",
"elif",
"self",
".",
"atual",
"==",
"Estados",
".",
"Espera",
":",
"# Espera",
"if",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"DATA",
":",
"self",
".",
"tratamentoEventoData",
"(",
"evento",
".",
"dados",
")",
"elif",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"Timeout",
":",
"# print('timeout',self.atual)",
"self",
".",
"atual",
"=",
"Estados",
".",
"BackoffTX",
"# Mudando de estado",
"self",
".",
"enable_timeout",
"(",
")",
"# Habilitando timer",
"elif",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"ACK_TX",
":",
"if",
"evento",
".",
"dados",
".",
"sequencia",
"!=",
"self",
".",
"tx",
":",
"# print('ACK tx errado', self.atual)",
"self",
".",
"atual",
"=",
"Estados",
".",
"BackoffTX",
"# Mudando de estado",
"timer",
"=",
"self",
".",
"timeslot",
"*",
"random",
".",
"randint",
"(",
"0",
",",
"7",
")",
"self",
".",
"timeout",
"=",
"timer",
"# Habilitando timer",
"# self.reload_timeout()",
"self",
".",
"enable_timeout",
"(",
")",
"else",
":",
"# print('ACK tx certo', self.atual)",
"self",
".",
"tx",
"=",
"self",
".",
"tx",
"^",
"1",
"self",
".",
"atual",
"=",
"Estados",
".",
"BackoffRX",
"timer",
"=",
"self",
".",
"timeslot",
"*",
"random",
".",
"randint",
"(",
"0",
",",
"7",
")",
"self",
".",
"timeout",
"=",
"timer",
"# Habilitando timer",
"# self.reload_timeout()",
"self",
".",
"enable_timeout",
"(",
")",
"else",
":",
"print",
"(",
"'erro ARQ'",
")",
"elif",
"self",
".",
"atual",
"==",
"Estados",
".",
"BackoffTX",
":",
"# BackoffTX",
"if",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"DATA",
":",
"self",
".",
"tratamentoEventoData",
"(",
"evento",
".",
"dados",
")",
"elif",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"Timeout",
":",
"# print('reenviando')",
"self",
".",
"lower",
".",
"envia",
"(",
"self",
".",
"quadroANTERIOR",
")",
"# Retransmissão quadro ack_not_TX",
"self",
".",
"atual",
"=",
"Estados",
".",
"Espera",
"# Mudanca de estado",
"self",
".",
"reload_timeout",
"(",
")",
"self",
".",
"enable_timeout",
"(",
")",
"# Timeout padrao",
"elif",
"self",
".",
"atual",
"==",
"Estados",
".",
"BackoffRX",
":",
"# BackoffRX",
"if",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"DATA",
":",
"self",
".",
"tratamentoEventoData",
"(",
"evento",
".",
"dados",
")",
"self",
".",
"disable_timeout",
"(",
")",
"self",
".",
"atual",
"=",
"Estados",
".",
"Ocioso",
"self",
".",
"upper",
".",
"enable",
"(",
")",
"elif",
"evento",
".",
"tipo",
"==",
"TipoEvento",
".",
"Timeout",
":",
"# print('voltando para ocioso')",
"self",
".",
"atual",
"=",
"Estados",
".",
"Ocioso",
"# Mudanca de estado",
"self",
".",
"upper",
".",
"enable",
"(",
")",
"# Habilitando camada superior",
"self",
".",
"disable_timeout",
"(",
")",
"else",
":",
"print",
"(",
"'Estado MEF não existente!')",
""
] | [
46,
4
] | [
119,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
sudoku_i | (sc, dificuldade) | return nlista | A função sudoku_i(sudoku incompleto), tem como objetivo receber o sudoku gerado na primeira função e a dificuldade nesse sudoku, para esconder alguns números, para que assim seja possível jogar
sc: o sudoku completo
dificuldade: 'facil', 'medio', 'dificil'
| A função sudoku_i(sudoku incompleto), tem como objetivo receber o sudoku gerado na primeira função e a dificuldade nesse sudoku, para esconder alguns números, para que assim seja possível jogar
sc: o sudoku completo
dificuldade: 'facil', 'medio', 'dificil'
| def sudoku_i(sc, dificuldade):
""" A função sudoku_i(sudoku incompleto), tem como objetivo receber o sudoku gerado na primeira função e a dificuldade nesse sudoku, para esconder alguns números, para que assim seja possível jogar
sc: o sudoku completo
dificuldade: 'facil', 'medio', 'dificil'
"""
#Dados que serão exibidos
sl1 = sc[0][:]
sl2 = sc[1][:]
sl3 = sc[2][:]
sl4 = sc[3][:]
sl5 = sc[4][:]
sl6 = sc[5][:]
sl7 = sc[6][:]
sl8 = sc[7][:]
sl9 = sc[8][:]
nlista = [sl1, sl2, sl3, sl4, sl5, sl6, sl7, sl8, sl9]
i = 0
n = (0, 1, 2, 3, 4, 5, 6, 7, 8)
if dificuldade == 'facil':
for conteL in nlista:
for c in range(0, 5):
facil = random.choice(n)
conteL[facil] = ''
nlista[i] = conteL
i = i + 1
if dificuldade == 'medio':
for conteL in nlista:
for c in range(0, 6):
medio = random.choice(n)
conteL[medio] = ''
nlista[i] = conteL
i = i + 1
if dificuldade == 'dificil':
for conteL in nlista:
for c in range(0, 7):
dificil = random.choice(n)
conteL[dificil] = ''
nlista[i] = conteL
i = i + 1
return nlista | [
"def",
"sudoku_i",
"(",
"sc",
",",
"dificuldade",
")",
":",
"#Dados que serão exibidos",
"sl1",
"=",
"sc",
"[",
"0",
"]",
"[",
":",
"]",
"sl2",
"=",
"sc",
"[",
"1",
"]",
"[",
":",
"]",
"sl3",
"=",
"sc",
"[",
"2",
"]",
"[",
":",
"]",
"sl4",
"=",
"sc",
"[",
"3",
"]",
"[",
":",
"]",
"sl5",
"=",
"sc",
"[",
"4",
"]",
"[",
":",
"]",
"sl6",
"=",
"sc",
"[",
"5",
"]",
"[",
":",
"]",
"sl7",
"=",
"sc",
"[",
"6",
"]",
"[",
":",
"]",
"sl8",
"=",
"sc",
"[",
"7",
"]",
"[",
":",
"]",
"sl9",
"=",
"sc",
"[",
"8",
"]",
"[",
":",
"]",
"nlista",
"=",
"[",
"sl1",
",",
"sl2",
",",
"sl3",
",",
"sl4",
",",
"sl5",
",",
"sl6",
",",
"sl7",
",",
"sl8",
",",
"sl9",
"]",
"i",
"=",
"0",
"n",
"=",
"(",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
")",
"if",
"dificuldade",
"==",
"'facil'",
":",
"for",
"conteL",
"in",
"nlista",
":",
"for",
"c",
"in",
"range",
"(",
"0",
",",
"5",
")",
":",
"facil",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"conteL",
"[",
"facil",
"]",
"=",
"''",
"nlista",
"[",
"i",
"]",
"=",
"conteL",
"i",
"=",
"i",
"+",
"1",
"if",
"dificuldade",
"==",
"'medio'",
":",
"for",
"conteL",
"in",
"nlista",
":",
"for",
"c",
"in",
"range",
"(",
"0",
",",
"6",
")",
":",
"medio",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"conteL",
"[",
"medio",
"]",
"=",
"''",
"nlista",
"[",
"i",
"]",
"=",
"conteL",
"i",
"=",
"i",
"+",
"1",
"if",
"dificuldade",
"==",
"'dificil'",
":",
"for",
"conteL",
"in",
"nlista",
":",
"for",
"c",
"in",
"range",
"(",
"0",
",",
"7",
")",
":",
"dificil",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"conteL",
"[",
"dificil",
"]",
"=",
"''",
"nlista",
"[",
"i",
"]",
"=",
"conteL",
"i",
"=",
"i",
"+",
"1",
"return",
"nlista"
] | [
492,
0
] | [
536,
14
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Knowledge.unexplored | (self) | return self.rooms(lambda r: not r.is_explored) | Retorna um gerador de índices de salas inexploradas. | Retorna um gerador de índices de salas inexploradas. | def unexplored(self):
"""Retorna um gerador de índices de salas inexploradas."""
return self.rooms(lambda r: not r.is_explored) | [
"def",
"unexplored",
"(",
"self",
")",
":",
"return",
"self",
".",
"rooms",
"(",
"lambda",
"r",
":",
"not",
"r",
".",
"is_explored",
")"
] | [
290,
2
] | [
294,
50
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
EletricCar.describe_details | (self) | Retorna os detalhes do carro elétrico. | Retorna os detalhes do carro elétrico. | def describe_details(self):
"""Retorna os detalhes do carro elétrico."""
while True:
disponible_color = {1: 'White', 2: 'Black', 3: 'Silver', 4: 'Red'}
print('Escolha a cor do seu Tesla Eletric Car. \nDisponible Color:')
for number, color in disponible_color.items():
print('\t' + str(number) + ': ' + color + '.')
color = int(input('Digite aqui sua cor favorita:\n'))
if color in disponible_color:
if color == 1:
your_car = {'Color': 'White', 'Horse Power': '80 hp', 'Torque': '14 kNm', 'Style': 'Sedan'}
print('Congratulations!!!!\nDetails of the your Tesla Electric Car:')
for value, key in your_car.items():
print('\t' + value + ': ' + key)
break
elif color == 2:
your_car = {'Color': 'Black', 'Horse Power': '80 hp', 'Torque': '14 kNm', 'Style': 'Hatch'}
print('Congratulations!!!!\nDetails of the your Tesla Electric Car:')
for value, key in your_car.items():
print('\t' + value + ': ' + key)
break
elif color == 3:
your_car = {'Color': 'Silver', 'Horse Power': '90 hp', 'Torque': '16 kNm', 'Style': 'SUV'}
print('Congratulations!!!!\nDetails of the your Tesla Electric Car:')
for value, key in your_car.items():
print('\t' + value + ': ' + key)
break
else:
your_car = {'Color': 'Red', 'Power': '116 hp', 'Torque': '18 kNm', 'Style': 'Cupê'}
print('Congratulations!!!!\nDetails of the your Tesla Electric Car:')
for value, key in your_car.items():
print('\t' + value + ': ' + key)
break
else:
print('Não estamos personalizando o carro elétrico no momento!') | [
"def",
"describe_details",
"(",
"self",
")",
":",
"while",
"True",
":",
"disponible_color",
"=",
"{",
"1",
":",
"'White'",
",",
"2",
":",
"'Black'",
",",
"3",
":",
"'Silver'",
",",
"4",
":",
"'Red'",
"}",
"print",
"(",
"'Escolha a cor do seu Tesla Eletric Car. \\nDisponible Color:'",
")",
"for",
"number",
",",
"color",
"in",
"disponible_color",
".",
"items",
"(",
")",
":",
"print",
"(",
"'\\t'",
"+",
"str",
"(",
"number",
")",
"+",
"': '",
"+",
"color",
"+",
"'.'",
")",
"color",
"=",
"int",
"(",
"input",
"(",
"'Digite aqui sua cor favorita:\\n'",
")",
")",
"if",
"color",
"in",
"disponible_color",
":",
"if",
"color",
"==",
"1",
":",
"your_car",
"=",
"{",
"'Color'",
":",
"'White'",
",",
"'Horse Power'",
":",
"'80 hp'",
",",
"'Torque'",
":",
"'14 kNm'",
",",
"'Style'",
":",
"'Sedan'",
"}",
"print",
"(",
"'Congratulations!!!!\\nDetails of the your Tesla Electric Car:'",
")",
"for",
"value",
",",
"key",
"in",
"your_car",
".",
"items",
"(",
")",
":",
"print",
"(",
"'\\t'",
"+",
"value",
"+",
"': '",
"+",
"key",
")",
"break",
"elif",
"color",
"==",
"2",
":",
"your_car",
"=",
"{",
"'Color'",
":",
"'Black'",
",",
"'Horse Power'",
":",
"'80 hp'",
",",
"'Torque'",
":",
"'14 kNm'",
",",
"'Style'",
":",
"'Hatch'",
"}",
"print",
"(",
"'Congratulations!!!!\\nDetails of the your Tesla Electric Car:'",
")",
"for",
"value",
",",
"key",
"in",
"your_car",
".",
"items",
"(",
")",
":",
"print",
"(",
"'\\t'",
"+",
"value",
"+",
"': '",
"+",
"key",
")",
"break",
"elif",
"color",
"==",
"3",
":",
"your_car",
"=",
"{",
"'Color'",
":",
"'Silver'",
",",
"'Horse Power'",
":",
"'90 hp'",
",",
"'Torque'",
":",
"'16 kNm'",
",",
"'Style'",
":",
"'SUV'",
"}",
"print",
"(",
"'Congratulations!!!!\\nDetails of the your Tesla Electric Car:'",
")",
"for",
"value",
",",
"key",
"in",
"your_car",
".",
"items",
"(",
")",
":",
"print",
"(",
"'\\t'",
"+",
"value",
"+",
"': '",
"+",
"key",
")",
"break",
"else",
":",
"your_car",
"=",
"{",
"'Color'",
":",
"'Red'",
",",
"'Power'",
":",
"'116 hp'",
",",
"'Torque'",
":",
"'18 kNm'",
",",
"'Style'",
":",
"'Cupê'}",
"",
"print",
"(",
"'Congratulations!!!!\\nDetails of the your Tesla Electric Car:'",
")",
"for",
"value",
",",
"key",
"in",
"your_car",
".",
"items",
"(",
")",
":",
"print",
"(",
"'\\t'",
"+",
"value",
"+",
"': '",
"+",
"key",
")",
"break",
"else",
":",
"print",
"(",
"'Não estamos personalizando o carro elétrico no momento!')",
""
] | [
69,
4
] | [
106,
82
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ship.center_ship | (self) | Centraliza a espaçonave na tela | Centraliza a espaçonave na tela | def center_ship(self):
"""Centraliza a espaçonave na tela"""
self.center = self.screen_rect.centerx
self.centery = self.screen_rect.bottom - 30 | [
"def",
"center_ship",
"(",
"self",
")",
":",
"self",
".",
"center",
"=",
"self",
".",
"screen_rect",
".",
"centerx",
"self",
".",
"centery",
"=",
"self",
".",
"screen_rect",
".",
"bottom",
"-",
"30"
] | [
54,
4
] | [
57,
51
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
my_min | (values) | return minimum | Retorna o elemento mínimo de uma lista.
Considerando a lista recebida como parâmetro, identifica e retorna
o elemento mínimo nela contido.
Parameters
----------
values : list
A lista cujo elemento mínimo deve ser identificado
Return
------
minimum : ?
O elemento mínimo da lista
| Retorna o elemento mínimo de uma lista. | def my_min(values):
""" Retorna o elemento mínimo de uma lista.
Considerando a lista recebida como parâmetro, identifica e retorna
o elemento mínimo nela contido.
Parameters
----------
values : list
A lista cujo elemento mínimo deve ser identificado
Return
------
minimum : ?
O elemento mínimo da lista
"""
minimum = values[0]
for i in values:
if (i < minimum):
minimum = i
return minimum | [
"def",
"my_min",
"(",
"values",
")",
":",
"minimum",
"=",
"values",
"[",
"0",
"]",
"for",
"i",
"in",
"values",
":",
"if",
"(",
"i",
"<",
"minimum",
")",
":",
"minimum",
"=",
"i",
"return",
"minimum"
] | [
129,
0
] | [
149,
18
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Queue.peek | (self) | Retorna o topo sem remover | Retorna o topo sem remover | def peek(self):
"""Retorna o topo sem remover"""
if self._size > 0:
elem = self.first.data
return elem
raise IndexError("The queue is empty") | [
"def",
"peek",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
">",
"0",
":",
"elem",
"=",
"self",
".",
"first",
".",
"data",
"return",
"elem",
"raise",
"IndexError",
"(",
"\"The queue is empty\"",
")"
] | [
43,
4
] | [
48,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update_bullets | (ai_settings, screen, stats, sb, ship, aliens, bullets) | Atualiza a posição dos projéteis e se livra dos projéteis antigos | Atualiza a posição dos projéteis e se livra dos projéteis antigos | def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
"""Atualiza a posição dos projéteis e se livra dos projéteis antigos"""
# Atualiza as posições dos projéteis
bullets.update()
# Livra dos projeteis que ultrapassam a tela
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets) | [
"def",
"update_bullets",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
":",
"# Atualiza as posições dos projéteis",
"bullets",
".",
"update",
"(",
")",
"# Livra dos projeteis que ultrapassam a tela",
"for",
"bullet",
"in",
"bullets",
".",
"copy",
"(",
")",
":",
"if",
"bullet",
".",
"rect",
".",
"bottom",
"<=",
"0",
":",
"bullets",
".",
"remove",
"(",
"bullet",
")",
"check_bullet_alien_collisions",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")"
] | [
150,
0
] | [
159,
88
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ordem_Servico.get_pagamento_input_os | (self) | return self.dt_pagamento.strftime("%Y-%m-%dT%H:%M") | Data pagamento OS correta para template. | Data pagamento OS correta para template. | def get_pagamento_input_os(self):
""" Data pagamento OS correta para template."""
return self.dt_pagamento.strftime("%Y-%m-%dT%H:%M") | [
"def",
"get_pagamento_input_os",
"(",
"self",
")",
":",
"return",
"self",
".",
"dt_pagamento",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M\"",
")"
] | [
294,
4
] | [
296,
59
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Anuncio.dias_ativo | (self) | return (self.data_termino - self.data_inicio).days + 1 | Retorna a quantidade de dias que o anúncio ficará ativo | Retorna a quantidade de dias que o anúncio ficará ativo | def dias_ativo(self) -> int:
"""Retorna a quantidade de dias que o anúncio ficará ativo"""
return (self.data_termino - self.data_inicio).days + 1 | [
"def",
"dias_ativo",
"(",
"self",
")",
"->",
"int",
":",
"return",
"(",
"self",
".",
"data_termino",
"-",
"self",
".",
"data_inicio",
")",
".",
"days",
"+",
"1"
] | [
77,
4
] | [
79,
62
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
main | () | Função principal | Função principal | def main():
'Função principal'
try:
infile = sys.argv[1] # arquivo de entrada
databaseName = sys.argv[2] # nome da base de dados
except IndexError:
print 'Número de argumentos inválido!'
uso()
sys.exit(1)
restoreDatabase(infile, databaseName) | [
"def",
"main",
"(",
")",
":",
"try",
":",
"infile",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"# arquivo de entrada",
"databaseName",
"=",
"sys",
".",
"argv",
"[",
"2",
"]",
"# nome da base de dados",
"except",
"IndexError",
":",
"print",
"'Número de argumentos inválido!'",
"uso",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"restoreDatabase",
"(",
"infile",
",",
"databaseName",
")"
] | [
77,
0
] | [
86,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | False | true | null |
|
qtd_divisores | (numero) | return contador | Percorrendo do 1 ao número e verificando se o resto de divisão de cada
número no intervalo é igual à zero, caso seja, adição ao contador | Percorrendo do 1 ao número e verificando se o resto de divisão de cada
número no intervalo é igual à zero, caso seja, adição ao contador | def qtd_divisores(numero):
contador = 0
""" Percorrendo do 1 ao número e verificando se o resto de divisão de cada
número no intervalo é igual à zero, caso seja, adição ao contador """
for i in range(1, numero + 1):
if numero % i == 0:
print(i)
contador += 1
return contador | [
"def",
"qtd_divisores",
"(",
"numero",
")",
":",
"contador",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"numero",
"+",
"1",
")",
":",
"if",
"numero",
"%",
"i",
"==",
"0",
":",
"print",
"(",
"i",
")",
"contador",
"+=",
"1",
"return",
"contador"
] | [
0,
0
] | [
8,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TradeCalculator.is_trade_valid | (self) | return is_trade_valid | Define se a instancia de TradeCalculator gera um trade valido | Define se a instancia de TradeCalculator gera um trade valido | def is_trade_valid(self) -> bool:
"""Define se a instancia de TradeCalculator gera um trade valido"""
base_experience_player1 = self._total_base_experience(self._player1)
base_experience_player2 = self._total_base_experience(self._player2)
is_trade_valid = self._is_base_experience_approximated(base_experience_player1, base_experience_player2)
return is_trade_valid | [
"def",
"is_trade_valid",
"(",
"self",
")",
"->",
"bool",
":",
"base_experience_player1",
"=",
"self",
".",
"_total_base_experience",
"(",
"self",
".",
"_player1",
")",
"base_experience_player2",
"=",
"self",
".",
"_total_base_experience",
"(",
"self",
".",
"_player2",
")",
"is_trade_valid",
"=",
"self",
".",
"_is_base_experience_approximated",
"(",
"base_experience_player1",
",",
"base_experience_player2",
")",
"return",
"is_trade_valid"
] | [
11,
4
] | [
18,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
dc_sort_index | (dcdf: dc.DataFrame) | return dcdf | emulate pandas sort_index for a dask_cudf DataFrame.
This pulls the index into a column, then uses set_index.
Args:
dcdf (dc.DataFrame): original dask_cudf DataFrame
Returns:
dc.DataFrame: newly sorted index for dask_cudf DataFrame
| emulate pandas sort_index for a dask_cudf DataFrame.
This pulls the index into a column, then uses set_index. | def dc_sort_index(dcdf: dc.DataFrame) -> dc.DataFrame:
"""emulate pandas sort_index for a dask_cudf DataFrame.
This pulls the index into a column, then uses set_index.
Args:
dcdf (dc.DataFrame): original dask_cudf DataFrame
Returns:
dc.DataFrame: newly sorted index for dask_cudf DataFrame
"""
idx = dcdf.index.name
dcdf = dcdf.reset_index().rename(columns={"index": idx})
dcdf = dcdf.set_index(idx)
return dcdf | [
"def",
"dc_sort_index",
"(",
"dcdf",
":",
"dc",
".",
"DataFrame",
")",
"->",
"dc",
".",
"DataFrame",
":",
"idx",
"=",
"dcdf",
".",
"index",
".",
"name",
"dcdf",
"=",
"dcdf",
".",
"reset_index",
"(",
")",
".",
"rename",
"(",
"columns",
"=",
"{",
"\"index\"",
":",
"idx",
"}",
")",
"dcdf",
"=",
"dcdf",
".",
"set_index",
"(",
"idx",
")",
"return",
"dcdf"
] | [
57,
0
] | [
70,
15
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
JointProbDist.values | (self, var) | return self.vals[var] | Retorna o conjunto de valores possíveis para uma variável. | Retorna o conjunto de valores possíveis para uma variável. | def values(self, var):
"Retorna o conjunto de valores possíveis para uma variável."
return self.vals[var] | [
"def",
"values",
"(",
"self",
",",
"var",
")",
":",
"return",
"self",
".",
"vals",
"[",
"var",
"]"
] | [
115,
4
] | [
117,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update | (id) | return render_template('autor/update.html', autor=autor, error=error) | Atualiza um autor pelo seu respectivo id. | Atualiza um autor pelo seu respectivo id. | def update(id):
"""Atualiza um autor pelo seu respectivo id."""
autor = get_autor(id)
error = None
if request.method == 'POST':
nome = request.form['nome']
if not nome:
error = 'Nome é obrigatório.'
print(autor)
if nome == autor['nome']:
return redirect(url_for('autor.index'))
else:
try:
if verifica_autor_bd(nome):
error = 'Este autor já está registrado!'
else:
db.insert_bd('UPDATE autor set nome = "%s" where id = %d' % (nome, id))
return redirect(url_for('autor.index'))
except:
return render_template('404.html')
return render_template('autor/update.html', autor=autor, error=error) | [
"def",
"update",
"(",
"id",
")",
":",
"autor",
"=",
"get_autor",
"(",
"id",
")",
"error",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"nome",
"=",
"request",
".",
"form",
"[",
"'nome'",
"]",
"if",
"not",
"nome",
":",
"error",
"=",
"'Nome é obrigatório.'",
"print",
"(",
"autor",
")",
"if",
"nome",
"==",
"autor",
"[",
"'nome'",
"]",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'autor.index'",
")",
")",
"else",
":",
"try",
":",
"if",
"verifica_autor_bd",
"(",
"nome",
")",
":",
"error",
"=",
"'Este autor já está registrado!'",
"else",
":",
"db",
".",
"insert_bd",
"(",
"'UPDATE autor set nome = \"%s\" where id = %d'",
"%",
"(",
"nome",
",",
"id",
")",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'autor.index'",
")",
")",
"except",
":",
"return",
"render_template",
"(",
"'404.html'",
")",
"return",
"render_template",
"(",
"'autor/update.html'",
",",
"autor",
"=",
"autor",
",",
"error",
"=",
"error",
")"
] | [
80,
0
] | [
103,
73
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Funcionario.__str__ | (self) | return self.nome | Devolve uma representação em string do modelo. | Devolve uma representação em string do modelo. | def __str__(self):
""" Devolve uma representação em string do modelo."""
return self.nome | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"nome"
] | [
80,
4
] | [
82,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Pyvidesk.services | (self) | return Services(token=self.token) | Retorna um objeto de services do pyvidesk | Retorna um objeto de services do pyvidesk | def services(self):
"""Retorna um objeto de services do pyvidesk"""
return Services(token=self.token) | [
"def",
"services",
"(",
"self",
")",
":",
"return",
"Services",
"(",
"token",
"=",
"self",
".",
"token",
")"
] | [
27,
4
] | [
29,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Subnet.get_debug | (self) | return f'SUBNET: Criada a subnet {self.name} com endereço de rede {self.local_address}/{self.local_mask}.' | Retorna string com o resultado da criacao das subnets. | Retorna string com o resultado da criacao das subnets. | def get_debug(self):
""" Retorna string com o resultado da criacao das subnets."""
return f'SUBNET: Criada a subnet {self.name} com endereço de rede {self.local_address}/{self.local_mask}.' | [
"def",
"get_debug",
"(",
"self",
")",
":",
"return",
"f'SUBNET: Criada a subnet {self.name} com endereço de rede {self.local_address}/{self.local_mask}.'"
] | [
37,
4
] | [
40,
115
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Stack.push | (self, value) | Adiciona o valor (value) ao final da pilha | Adiciona o valor (value) ao final da pilha | def push(self, value):
""" Adiciona o valor (value) ao final da pilha """
self.__stack.append(value) | [
"def",
"push",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__stack",
".",
"append",
"(",
"value",
")"
] | [
13,
4
] | [
15,
34
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
JointProbDist.__setitem__ | (self, values, p) | Set P (valores) = p. Os valores podem ser uma tupla ou um dict; deve
Têm um valor para cada uma das variáveis na articulação. Também acompanhar
Dos valores que vimos até agora para cada variável. | Set P (valores) = p. Os valores podem ser uma tupla ou um dict; deve
Têm um valor para cada uma das variáveis na articulação. Também acompanhar
Dos valores que vimos até agora para cada variável. | def __setitem__(self, values, p):
"""Set P (valores) = p. Os valores podem ser uma tupla ou um dict; deve
Têm um valor para cada uma das variáveis na articulação. Também acompanhar
Dos valores que vimos até agora para cada variável."""
values = event_values(values, self.variables)
self.prob[values] = p
for var, val in zip(self.variables, values):
if val not in self.vals[var]:
self.vals[var].append(val) | [
"def",
"__setitem__",
"(",
"self",
",",
"values",
",",
"p",
")",
":",
"values",
"=",
"event_values",
"(",
"values",
",",
"self",
".",
"variables",
")",
"self",
".",
"prob",
"[",
"values",
"]",
"=",
"p",
"for",
"var",
",",
"val",
"in",
"zip",
"(",
"self",
".",
"variables",
",",
"values",
")",
":",
"if",
"val",
"not",
"in",
"self",
".",
"vals",
"[",
"var",
"]",
":",
"self",
".",
"vals",
"[",
"var",
"]",
".",
"append",
"(",
"val",
")"
] | [
105,
4
] | [
113,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestTituloEleitoral.setUp | (self) | Inicia novo objeto em todo os testes | Inicia novo objeto em todo os testes | def setUp(self):
""" Inicia novo objeto em todo os testes """
self.titulo_eleitoral = docbr.TituloEleitoral() | [
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"titulo_eleitoral",
"=",
"docbr",
".",
"TituloEleitoral",
"(",
")"
] | [
5,
4
] | [
7,
55
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
create_right_side_MMQ | (uarray, ut) | return matrix | funcao que cria o lado direito do sistema MMQ, funciona de forma analoga
a funcao que cria a matrix do sistema MMQ | funcao que cria o lado direito do sistema MMQ, funciona de forma analoga
a funcao que cria a matrix do sistema MMQ | def create_right_side_MMQ(uarray, ut):
''''funcao que cria o lado direito do sistema MMQ, funciona de forma analoga
a funcao que cria a matrix do sistema MMQ'''
shape = uarray.shape[0]
matrix = np.zeros(shape)
for i in range(shape):
matrix[i] = prod_interno(uarray[i], ut)
return matrix | [
"def",
"create_right_side_MMQ",
"(",
"uarray",
",",
"ut",
")",
":",
"shape",
"=",
"uarray",
".",
"shape",
"[",
"0",
"]",
"matrix",
"=",
"np",
".",
"zeros",
"(",
"shape",
")",
"for",
"i",
"in",
"range",
"(",
"shape",
")",
":",
"matrix",
"[",
"i",
"]",
"=",
"prod_interno",
"(",
"uarray",
"[",
"i",
"]",
",",
"ut",
")",
"return",
"matrix"
] | [
57,
0
] | [
64,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
recua | (r = 0, valores = recuo) | return t | Dados uma posição de tabulação inicial inteira r e o dicionário valores ordenando inteiros e caracteres de indentação,
retorna uma string equivalente ao número fornecido orientado pelo índice na chave None. | Dados uma posição de tabulação inicial inteira r e o dicionário valores ordenando inteiros e caracteres de indentação,
retorna uma string equivalente ao número fornecido orientado pelo índice na chave None. | def recua (r = 0, valores = recuo):
'''Dados uma posição de tabulação inicial inteira r e o dicionário valores ordenando inteiros e caracteres de indentação,
retorna uma string equivalente ao número fornecido orientado pelo índice na chave None.'''
# r += contarecuo(p,r,valores)
t = ''
try:
for l in valores[None]:
t += valores[l]*(r//l)
r %= l
except TypeError:
warnings.warn('Os valores para recuo devem ser iteráveis e indicar os números das strings')
except KeyError:
warnings.warn('Os valores para recuo devem ter índice numérico ordenado coerente.')
return t | [
"def",
"recua",
"(",
"r",
"=",
"0",
",",
"valores",
"=",
"recuo",
")",
":",
"#\tr += contarecuo(p,r,valores)",
"t",
"=",
"''",
"try",
":",
"for",
"l",
"in",
"valores",
"[",
"None",
"]",
":",
"t",
"+=",
"valores",
"[",
"l",
"]",
"*",
"(",
"r",
"//",
"l",
")",
"r",
"%=",
"l",
"except",
"TypeError",
":",
"warnings",
".",
"warn",
"(",
"'Os valores para recuo devem ser iteráveis e indicar os números das strings')",
"",
"except",
"KeyError",
":",
"warnings",
".",
"warn",
"(",
"'Os valores para recuo devem ter índice numérico ordenado coerente.')",
"",
"return",
"t"
] | [
16,
0
] | [
29,
9
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
enumeration_ask | (X, e, bn) | return Q.normalize() | Retornar a distribuição de probabilidade condicional da variável X
Dadas evidências e, da BayesNet bn. | Retornar a distribuição de probabilidade condicional da variável X
Dadas evidências e, da BayesNet bn. | def enumeration_ask(X, e, bn):
"""Retornar a distribuição de probabilidade condicional da variável X
Dadas evidências e, da BayesNet bn."""
assert X not in e, "A variável de consulta deve ser distinta da evidência"
Q = ProbDist(X)
for xi in bn.variable_values(X):
Q[xi] = enumerate_all(bn.variables, extend(e, X, xi), bn)
return Q.normalize() | [
"def",
"enumeration_ask",
"(",
"X",
",",
"e",
",",
"bn",
")",
":",
"assert",
"X",
"not",
"in",
"e",
",",
"\"A variável de consulta deve ser distinta da evidência\"",
"Q",
"=",
"ProbDist",
"(",
"X",
")",
"for",
"xi",
"in",
"bn",
".",
"variable_values",
"(",
"X",
")",
":",
"Q",
"[",
"xi",
"]",
"=",
"enumerate_all",
"(",
"bn",
".",
"variables",
",",
"extend",
"(",
"e",
",",
"X",
",",
"xi",
")",
",",
"bn",
")",
"return",
"Q",
".",
"normalize",
"(",
")"
] | [
279,
0
] | [
286,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
InterfaceChannelResource.handle_get | (self, request, user, *args, **kwargs) | Trata uma requisição PUT para alterar informações de um channel.
URL: channel/get-by-name/
| Trata uma requisição PUT para alterar informações de um channel.
URL: channel/get-by-name/
| def handle_get(self, request, user, *args, **kwargs):
"""Trata uma requisição PUT para alterar informações de um channel.
URL: channel/get-by-name/
"""
# Get request data and check permission
try:
self.log.info('Get Channel')
# User permission
if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
self.log.error(
u'User does not have permission to perform the operation.')
raise UserNotAuthorizedError(None)
# Get XML data
xml_map, attrs_map = loads(request.raw_post_data)
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
return self.response_error(3, u'There is no networkapi tag in XML request.')
channel_name = kwargs.get('channel_name')
channel = PortChannel.get_by_name(channel_name)
try:
for ch in channel:
channel = model_to_dict(ch)
except:
channel = model_to_dict(channel)
pass
return self.response(dumps_networkapi({'channel': channel}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
except InterfaceError:
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get request data and check permission",
"try",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Get Channel'",
")",
"# User permission",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'User does not have permission to perform the operation.'",
")",
"raise",
"UserNotAuthorizedError",
"(",
"None",
")",
"# Get XML data",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"networkapi_map",
"=",
"xml_map",
".",
"get",
"(",
"'networkapi'",
")",
"if",
"networkapi_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'There is no networkapi tag in XML request.'",
")",
"channel_name",
"=",
"kwargs",
".",
"get",
"(",
"'channel_name'",
")",
"channel",
"=",
"PortChannel",
".",
"get_by_name",
"(",
"channel_name",
")",
"try",
":",
"for",
"ch",
"in",
"channel",
":",
"channel",
"=",
"model_to_dict",
"(",
"ch",
")",
"except",
":",
"channel",
"=",
"model_to_dict",
"(",
"channel",
")",
"pass",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'channel'",
":",
"channel",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisição.')",
"",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"InterfaceError",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
235,
4
] | [
276,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Extractor.calcular_histograma | (self, img) | return hist | Função para obter o vetor de histograma de uma imagem
Apenas escala de cinza
Retorna um vetor de 256 posições com o histograma da imagem
| Função para obter o vetor de histograma de uma imagem
Apenas escala de cinza
Retorna um vetor de 256 posições com o histograma da imagem
| def calcular_histograma(self, img):
"""Função para obter o vetor de histograma de uma imagem
Apenas escala de cinza
Retorna um vetor de 256 posições com o histograma da imagem
"""
hist = np.zeros(256)
qtdeLinhas, qtdeColunas = img.shape
for i in range(qtdeLinhas):
for j in range(qtdeColunas):
hist[img[i,j]] = hist[img[i,j]] + 1
return hist | [
"def",
"calcular_histograma",
"(",
"self",
",",
"img",
")",
":",
"hist",
"=",
"np",
".",
"zeros",
"(",
"256",
")",
"qtdeLinhas",
",",
"qtdeColunas",
"=",
"img",
".",
"shape",
"for",
"i",
"in",
"range",
"(",
"qtdeLinhas",
")",
":",
"for",
"j",
"in",
"range",
"(",
"qtdeColunas",
")",
":",
"hist",
"[",
"img",
"[",
"i",
",",
"j",
"]",
"]",
"=",
"hist",
"[",
"img",
"[",
"i",
",",
"j",
"]",
"]",
"+",
"1",
"return",
"hist"
] | [
47,
4
] | [
58,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
primalidade | () | Input: número inteiro positivo. Retorna: se é primo ou não. | Input: número inteiro positivo. Retorna: se é primo ou não. | def primalidade():
'''Input: número inteiro positivo. Retorna: se é primo ou não.'''
num = int(input("Digite um número inteiro positivo: "))
for i in range(2, num):
if num % i == 0:
print("não primo")
else:
print("primo") | [
"def",
"primalidade",
"(",
")",
":",
"num",
"=",
"int",
"(",
"input",
"(",
"\"Digite um número inteiro positivo: \")",
")",
"",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"num",
")",
":",
"if",
"num",
"%",
"i",
"==",
"0",
":",
"print",
"(",
"\"não primo\")",
"",
"else",
":",
"print",
"(",
"\"primo\"",
")"
] | [
9,
0
] | [
16,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TesteFuncionario.test_receber_aumento_padr | self): | Testa se o funcionário receberá 5000 ao valor anual. | Testa se o funcionário receberá 5000 ao valor anual. | def test_receber_aumento_padrão(self):
"""Testa se o funcionário receberá 5000 ao valor anual."""
self.alberto.receber_aumento()
self.assertEqual(self.alberto.salario, 55000) | [
"def",
"test_receber_aumento_padr",
"ão",
"(",
"s",
"elf)",
":",
"",
"self",
".",
"alberto",
".",
"receber_aumento",
"(",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"alberto",
".",
"salario",
",",
"55000",
")"
] | [
18,
4
] | [
21,
53
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
xml2dict | (x) | return d[0]['networkapi'] | Converte o XML com pai <networkapi> para um dicionario. O elemento raiz não é retornado | Converte o XML com pai <networkapi> para um dicionario. O elemento raiz não é retornado | def xml2dict(x):
""" Converte o XML com pai <networkapi> para um dicionario. O elemento raiz não é retornado """
d = loads(x)
return d[0]['networkapi'] | [
"def",
"xml2dict",
"(",
"x",
")",
":",
"d",
"=",
"loads",
"(",
"x",
")",
"return",
"d",
"[",
"0",
"]",
"[",
"'networkapi'",
"]"
] | [
39,
0
] | [
42,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Extractor.conv | (self, img, kernel) | return W | Operação de convolução entre a imagem e um kernel
| Operação de convolução entre a imagem e um kernel
| def conv(self, img, kernel):
"""Operação de convolução entre a imagem e um kernel
"""
kernel_qtdeLinhas, kernel_qtdeColunas = kernel.shape
img_qtdeLinhas, img_qtdeColunas = img.shape
k1 = round(kernel_qtdeLinhas/2)
k2 = round(kernel_qtdeColunas/2)
W = np.zeros((img_qtdeLinhas, img_qtdeColunas))
for i in range(k1, img_qtdeLinhas-k1):
for j in range(k2, img_qtdeColunas-k2):
soma = 0
for x in range(kernel_qtdeLinhas):
for y in range(kernel_qtdeColunas):
soma = soma + kernel[x,y]*img[(i-k1)+x, (j-k2)+y]
W[i,j] = soma
return W | [
"def",
"conv",
"(",
"self",
",",
"img",
",",
"kernel",
")",
":",
"kernel_qtdeLinhas",
",",
"kernel_qtdeColunas",
"=",
"kernel",
".",
"shape",
"img_qtdeLinhas",
",",
"img_qtdeColunas",
"=",
"img",
".",
"shape",
"k1",
"=",
"round",
"(",
"kernel_qtdeLinhas",
"/",
"2",
")",
"k2",
"=",
"round",
"(",
"kernel_qtdeColunas",
"/",
"2",
")",
"W",
"=",
"np",
".",
"zeros",
"(",
"(",
"img_qtdeLinhas",
",",
"img_qtdeColunas",
")",
")",
"for",
"i",
"in",
"range",
"(",
"k1",
",",
"img_qtdeLinhas",
"-",
"k1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"k2",
",",
"img_qtdeColunas",
"-",
"k2",
")",
":",
"soma",
"=",
"0",
"for",
"x",
"in",
"range",
"(",
"kernel_qtdeLinhas",
")",
":",
"for",
"y",
"in",
"range",
"(",
"kernel_qtdeColunas",
")",
":",
"soma",
"=",
"soma",
"+",
"kernel",
"[",
"x",
",",
"y",
"]",
"*",
"img",
"[",
"(",
"i",
"-",
"k1",
")",
"+",
"x",
",",
"(",
"j",
"-",
"k2",
")",
"+",
"y",
"]",
"W",
"[",
"i",
",",
"j",
"]",
"=",
"soma",
"return",
"W"
] | [
11,
4
] | [
30,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Pedido.resumo | (self) | return f'''
Pedido por: {self.usuario.nome_completo}
Valor: {self.valor}
Frete: {self.frete}
''' | Informações gerais sobre o pedido. | Informações gerais sobre o pedido. | def resumo(self):
"""Informações gerais sobre o pedido."""
return f'''
Pedido por: {self.usuario.nome_completo}
Valor: {self.valor}
Frete: {self.frete}
''' | [
"def",
"resumo",
"(",
"self",
")",
":",
"return",
"f'''\n Pedido por: {self.usuario.nome_completo}\n Valor: {self.valor}\n Frete: {self.frete}\n '''"
] | [
10,
4
] | [
16,
11
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Ship.update | (self) | Atualiza a posição da espaçonave de acordo com a flag de movimento | Atualiza a posição da espaçonave de acordo com a flag de movimento | def update(self):
"""Atualiza a posição da espaçonave de acordo com a flag de movimento"""
# Atualiza o valor do centro da espaçonave, e não o retângulo
# Não permite que a nave ultrapasse os cantos da tela.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_setting.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_setting.ship_speed_factor
if self.moving_top and self.rect.top > 0:
self.centery -= self.ai_setting.ship_speed_factor
if self.moving_bottom and self.rect.bottom < self.screen_rect.bottom:
self.centery += self.ai_setting.ship_speed_factor
# Atualiza o objeto rect de acordo com self.center
self.rect.centerx = self.center
self.rect.centery = self.centery | [
"def",
"update",
"(",
"self",
")",
":",
"# Atualiza o valor do centro da espaçonave, e não o retângulo",
"# Não permite que a nave ultrapasse os cantos da tela.",
"if",
"self",
".",
"moving_right",
"and",
"self",
".",
"rect",
".",
"right",
"<",
"self",
".",
"screen_rect",
".",
"right",
":",
"self",
".",
"center",
"+=",
"self",
".",
"ai_setting",
".",
"ship_speed_factor",
"if",
"self",
".",
"moving_left",
"and",
"self",
".",
"rect",
".",
"left",
">",
"0",
":",
"self",
".",
"center",
"-=",
"self",
".",
"ai_setting",
".",
"ship_speed_factor",
"if",
"self",
".",
"moving_top",
"and",
"self",
".",
"rect",
".",
"top",
">",
"0",
":",
"self",
".",
"centery",
"-=",
"self",
".",
"ai_setting",
".",
"ship_speed_factor",
"if",
"self",
".",
"moving_bottom",
"and",
"self",
".",
"rect",
".",
"bottom",
"<",
"self",
".",
"screen_rect",
".",
"bottom",
":",
"self",
".",
"centery",
"+=",
"self",
".",
"ai_setting",
".",
"ship_speed_factor",
"# Atualiza o objeto rect de acordo com self.center",
"self",
".",
"rect",
".",
"centerx",
"=",
"self",
".",
"center",
"self",
".",
"rect",
".",
"centery",
"=",
"self",
".",
"centery"
] | [
33,
4
] | [
48,
40
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
cadastrar_paciente | () | Realiza o cadastro de um paciente | Realiza o cadastro de um paciente | def cadastrar_paciente():
'''Realiza o cadastro de um paciente'''
form = CadastrarPaciente()
cidades = db.session.query(Cidade).all()
form.cidade.choices = [(c.id, c.nome) for c in cidades]
if request.method == 'GET':
return render_template('cadastrar_paciente.html', title='Cadastrar paciente', form=form)
if form.validate_on_submit():
cpf = request.form['cpf']
nome = request.form['nome']
nascimento = request.form['dataNasc']
cidade = request.form['cidade']
rua = request.form['rua']
telefone = request.form['telefone']
paciente = db.session.query(Pessoa).filter(Pessoa.cpf == cpf).first()
format = '%d/%m/%Y'
new_format = '%Y-%m-%d'
dataNasc = datetime.strptime(nascimento, format).strftime(new_format)
if paciente is not None:
flash('Paciente já possui cadastro')
return redirect(url_for('inicio'))
else:
# Cadastrando Pessoa
# Objeto Pessoa
p = Pessoa()
# Verificando se deve criar Telefone
telefone_existente = db.session.query(Telefone).filter(Telefone.numero == telefone).first()
telefone_max_id = db.session.query(func.max(Telefone.id)).scalar()
# Objeto telefone
t = Telefone()
if telefone_existente is None:
t.id = telefone_max_id + 1
t.numero = telefone
db.session.add(t)
p.idTelefone = telefone_max_id + 1
else:
p.idTelefone = telefone_existente.id
# Verifica se a rua já existe
rua_existente = db.session.query(Endereco).filter(Endereco.idCidade == cidade, Endereco.rua == rua).first()
rua_max_id = db.session.query(func.max(Endereco.id)).scalar()
pessoa_max_id = db.session.query(func.max(Pessoa.id)).scalar()
if rua_existente is None:
e = Endereco()
e.id = rua_max_id+1
e.rua = rua
e.idCidade = cidade
db.session.add(e)
p.idEndereco = rua_max_id+1
else:
p.idEndereco = rua_existente.id
p.id = pessoa_max_id + 1
p.cpf = cpf
p.nome = nome
p.nascimento = dataNasc
db.session.add(p)
db.session.commit()
db.session.close()
return redirect(url_for('inicio')) | [
"def",
"cadastrar_paciente",
"(",
")",
":",
"form",
"=",
"CadastrarPaciente",
"(",
")",
"cidades",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Cidade",
")",
".",
"all",
"(",
")",
"form",
".",
"cidade",
".",
"choices",
"=",
"[",
"(",
"c",
".",
"id",
",",
"c",
".",
"nome",
")",
"for",
"c",
"in",
"cidades",
"]",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render_template",
"(",
"'cadastrar_paciente.html'",
",",
"title",
"=",
"'Cadastrar paciente'",
",",
"form",
"=",
"form",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"cpf",
"=",
"request",
".",
"form",
"[",
"'cpf'",
"]",
"nome",
"=",
"request",
".",
"form",
"[",
"'nome'",
"]",
"nascimento",
"=",
"request",
".",
"form",
"[",
"'dataNasc'",
"]",
"cidade",
"=",
"request",
".",
"form",
"[",
"'cidade'",
"]",
"rua",
"=",
"request",
".",
"form",
"[",
"'rua'",
"]",
"telefone",
"=",
"request",
".",
"form",
"[",
"'telefone'",
"]",
"paciente",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Pessoa",
")",
".",
"filter",
"(",
"Pessoa",
".",
"cpf",
"==",
"cpf",
")",
".",
"first",
"(",
")",
"format",
"=",
"'%d/%m/%Y'",
"new_format",
"=",
"'%Y-%m-%d'",
"dataNasc",
"=",
"datetime",
".",
"strptime",
"(",
"nascimento",
",",
"format",
")",
".",
"strftime",
"(",
"new_format",
")",
"if",
"paciente",
"is",
"not",
"None",
":",
"flash",
"(",
"'Paciente já possui cadastro')",
"",
"return",
"redirect",
"(",
"url_for",
"(",
"'inicio'",
")",
")",
"else",
":",
"# Cadastrando Pessoa",
"# Objeto Pessoa",
"p",
"=",
"Pessoa",
"(",
")",
"# Verificando se deve criar Telefone",
"telefone_existente",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Telefone",
")",
".",
"filter",
"(",
"Telefone",
".",
"numero",
"==",
"telefone",
")",
".",
"first",
"(",
")",
"telefone_max_id",
"=",
"db",
".",
"session",
".",
"query",
"(",
"func",
".",
"max",
"(",
"Telefone",
".",
"id",
")",
")",
".",
"scalar",
"(",
")",
"# Objeto telefone",
"t",
"=",
"Telefone",
"(",
")",
"if",
"telefone_existente",
"is",
"None",
":",
"t",
".",
"id",
"=",
"telefone_max_id",
"+",
"1",
"t",
".",
"numero",
"=",
"telefone",
"db",
".",
"session",
".",
"add",
"(",
"t",
")",
"p",
".",
"idTelefone",
"=",
"telefone_max_id",
"+",
"1",
"else",
":",
"p",
".",
"idTelefone",
"=",
"telefone_existente",
".",
"id",
"# Verifica se a rua já existe",
"rua_existente",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Endereco",
")",
".",
"filter",
"(",
"Endereco",
".",
"idCidade",
"==",
"cidade",
",",
"Endereco",
".",
"rua",
"==",
"rua",
")",
".",
"first",
"(",
")",
"rua_max_id",
"=",
"db",
".",
"session",
".",
"query",
"(",
"func",
".",
"max",
"(",
"Endereco",
".",
"id",
")",
")",
".",
"scalar",
"(",
")",
"pessoa_max_id",
"=",
"db",
".",
"session",
".",
"query",
"(",
"func",
".",
"max",
"(",
"Pessoa",
".",
"id",
")",
")",
".",
"scalar",
"(",
")",
"if",
"rua_existente",
"is",
"None",
":",
"e",
"=",
"Endereco",
"(",
")",
"e",
".",
"id",
"=",
"rua_max_id",
"+",
"1",
"e",
".",
"rua",
"=",
"rua",
"e",
".",
"idCidade",
"=",
"cidade",
"db",
".",
"session",
".",
"add",
"(",
"e",
")",
"p",
".",
"idEndereco",
"=",
"rua_max_id",
"+",
"1",
"else",
":",
"p",
".",
"idEndereco",
"=",
"rua_existente",
".",
"id",
"p",
".",
"id",
"=",
"pessoa_max_id",
"+",
"1",
"p",
".",
"cpf",
"=",
"cpf",
"p",
".",
"nome",
"=",
"nome",
"p",
".",
"nascimento",
"=",
"dataNasc",
"db",
".",
"session",
".",
"add",
"(",
"p",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"db",
".",
"session",
".",
"close",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'inicio'",
")",
")"
] | [
96,
0
] | [
170,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
import_journals | (json_file: str, session: Session) | Fachada com passo a passo de processamento e carga de periódicos
em formato JSON para a base Kernel | Fachada com passo a passo de processamento e carga de periódicos
em formato JSON para a base Kernel | def import_journals(json_file: str, session: Session):
"""Fachada com passo a passo de processamento e carga de periódicos
em formato JSON para a base Kernel"""
try:
journals_as_json = reading.read_json_file(json_file)
manifests = conversion.conversion_journals_to_kernel(journals=journals_as_json)
for manifest in manifests:
journal = Journal(manifest=manifest)
try:
add_journal(session, journal)
except AlreadyExists as exc:
logger.info(exc)
except (FileNotFoundError, ValueError) as exc:
logger.debug(exc) | [
"def",
"import_journals",
"(",
"json_file",
":",
"str",
",",
"session",
":",
"Session",
")",
":",
"try",
":",
"journals_as_json",
"=",
"reading",
".",
"read_json_file",
"(",
"json_file",
")",
"manifests",
"=",
"conversion",
".",
"conversion_journals_to_kernel",
"(",
"journals",
"=",
"journals_as_json",
")",
"for",
"manifest",
"in",
"manifests",
":",
"journal",
"=",
"Journal",
"(",
"manifest",
"=",
"manifest",
")",
"try",
":",
"add_journal",
"(",
"session",
",",
"journal",
")",
"except",
"AlreadyExists",
"as",
"exc",
":",
"logger",
".",
"info",
"(",
"exc",
")",
"except",
"(",
"FileNotFoundError",
",",
"ValueError",
")",
"as",
"exc",
":",
"logger",
".",
"debug",
"(",
"exc",
")"
] | [
65,
0
] | [
80,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Chess.xadspec_join | (self, ctx, match_code : str) | Começa a espectar uma partida de xadrez. | Começa a espectar uma partida de xadrez. | async def xadspec_join(self, ctx, match_code : str):
"""Começa a espectar uma partida de xadrez."""
match_data = self.get_match_by_id(match_code)
if match_data is None:
return await ctx.reply(f"{CROSS_EMOJI} Essa partida não existe ou já terminou.")
if ctx.author.id in match_data.spectators:
return await ctx.reply(f"{CROSS_EMOJI} Você já está espectando essa partida.")
if ctx.author in match_data:
return await ctx.reply(f"{CROSS_EMOJI} Você é um dos participantes da partida.")
# legal é que não estamos fazendo nenhuma verificação
# pra caso um dos jogadores saia do servidor.
channel = match_data.channel
black, white = ctx.guild.get_member(match_data.black), ctx.guild.get_member(match_data.white)
ov = {
ctx.author: discord.PermissionOverwrite(add_reactions=True, read_messages=True, send_messages=False),
}
if sys.version_info >= (3,9):
ov |= match_data.overwrites
else:
ov.update(match_data.overwrites)
if black is not None:
ov[black] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
if white is not None:
ov[white] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
await channel.edit(overwrites=ov)
match_data.add_spectator(ctx.author)
await ctx.reply(f"O chat de xadrez é o {channel.mention}")
match_data.set_overwrites(ov)
await channel.edit(overwrites=ov)
match_data.add_spectator(ctx.author)
await ctx.reply(f"O chat de xadrez é o {channel.mention}")
| [
"async",
"def",
"xadspec_join",
"(",
"self",
",",
"ctx",
",",
"match_code",
":",
"str",
")",
":",
"match_data",
"=",
"self",
".",
"get_match_by_id",
"(",
"match_code",
")",
"if",
"match_data",
"is",
"None",
":",
"return",
"await",
"ctx",
".",
"reply",
"(",
"f\"{CROSS_EMOJI} Essa partida não existe ou já terminou.\")\r",
"",
"if",
"ctx",
".",
"author",
".",
"id",
"in",
"match_data",
".",
"spectators",
":",
"return",
"await",
"ctx",
".",
"reply",
"(",
"f\"{CROSS_EMOJI} Você já está espectando essa partida.\")\r",
"",
"if",
"ctx",
".",
"author",
"in",
"match_data",
":",
"return",
"await",
"ctx",
".",
"reply",
"(",
"f\"{CROSS_EMOJI} Você é um dos participantes da partida.\")\r",
"",
"# legal é que não estamos fazendo nenhuma verificação\r",
"# pra caso um dos jogadores saia do servidor.\r",
"channel",
"=",
"match_data",
".",
"channel",
"black",
",",
"white",
"=",
"ctx",
".",
"guild",
".",
"get_member",
"(",
"match_data",
".",
"black",
")",
",",
"ctx",
".",
"guild",
".",
"get_member",
"(",
"match_data",
".",
"white",
")",
"ov",
"=",
"{",
"ctx",
".",
"author",
":",
"discord",
".",
"PermissionOverwrite",
"(",
"add_reactions",
"=",
"True",
",",
"read_messages",
"=",
"True",
",",
"send_messages",
"=",
"False",
")",
",",
"}",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"9",
")",
":",
"ov",
"|=",
"match_data",
".",
"overwrites",
"else",
":",
"ov",
".",
"update",
"(",
"match_data",
".",
"overwrites",
")",
"if",
"black",
"is",
"not",
"None",
":",
"ov",
"[",
"black",
"]",
"=",
"discord",
".",
"PermissionOverwrite",
"(",
"read_messages",
"=",
"True",
",",
"send_messages",
"=",
"True",
")",
"if",
"white",
"is",
"not",
"None",
":",
"ov",
"[",
"white",
"]",
"=",
"discord",
".",
"PermissionOverwrite",
"(",
"read_messages",
"=",
"True",
",",
"send_messages",
"=",
"True",
")",
"await",
"channel",
".",
"edit",
"(",
"overwrites",
"=",
"ov",
")",
"match_data",
".",
"add_spectator",
"(",
"ctx",
".",
"author",
")",
"await",
"ctx",
".",
"reply",
"(",
"f\"O chat de xadrez é o {channel.mention}\")",
"\r",
"match_data",
".",
"set_overwrites",
"(",
"ov",
")",
"await",
"channel",
".",
"edit",
"(",
"overwrites",
"=",
"ov",
")",
"match_data",
".",
"add_spectator",
"(",
"ctx",
".",
"author",
")",
"await",
"ctx",
".",
"reply",
"(",
"f\"O chat de xadrez é o {channel.mention}\")",
"\r"
] | [
212,
4
] | [
247,
67
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
get | (config: str) | return os.environ.get(config, _default.get(config, "")) | Recupera configurações do sistema, caso a configuração não
esteja definida como uma variável de ambiente deve-se retornar a
configuração padrão.
| Recupera configurações do sistema, caso a configuração não
esteja definida como uma variável de ambiente deve-se retornar a
configuração padrão.
| def get(config: str):
"""Recupera configurações do sistema, caso a configuração não
esteja definida como uma variável de ambiente deve-se retornar a
configuração padrão.
"""
return os.environ.get(config, _default.get(config, "")) | [
"def",
"get",
"(",
"config",
":",
"str",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"config",
",",
"_default",
".",
"get",
"(",
"config",
",",
"\"\"",
")",
")"
] | [
105,
0
] | [
110,
59
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
SistemaLivros.excluir_livro | (self) | Pede ao usuario uma referencia para
selecionar um livro, após isso, o exclui | Pede ao usuario uma referencia para
selecionar um livro, após isso, o exclui | def excluir_livro(self):
""" Pede ao usuario uma referencia para
selecionar um livro, após isso, o exclui """
cont = 0
print("Todos os livros registrados no sistema : \n")
for registro in self.dados:
print(f"Número de identificação [{cont}]")
for item in registro.items():
print(f"{item[0]} : {item[1]}")
cont += 1
print('='*55)
numero_id = int(input("""Digite o número de identificação
do livro que deseja excluir : """))
self.dados.remove(self.dados[numero_id]) | [
"def",
"excluir_livro",
"(",
"self",
")",
":",
"cont",
"=",
"0",
"print",
"(",
"\"Todos os livros registrados no sistema : \\n\"",
")",
"for",
"registro",
"in",
"self",
".",
"dados",
":",
"print",
"(",
"f\"Número de identificação [{cont}]\")",
"",
"for",
"item",
"in",
"registro",
".",
"items",
"(",
")",
":",
"print",
"(",
"f\"{item[0]} : {item[1]}\"",
")",
"cont",
"+=",
"1",
"print",
"(",
"'='",
"*",
"55",
")",
"numero_id",
"=",
"int",
"(",
"input",
"(",
"\"\"\"Digite o número de identificação\n do livro que deseja excluir : \"\"\"",
")",
")",
"self",
".",
"dados",
".",
"remove",
"(",
"self",
".",
"dados",
"[",
"numero_id",
"]",
")"
] | [
122,
4
] | [
136,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ambiente.remove | (cls, authenticated_user, pk) | Efetua a remoção de um Ambiente.
@return: Nothing
@raise AmbienteError: Falha ao remover um HealthCheckExpect ou Ambiente Config associado ou o Ambiente.
@raise AmbienteNotFoundError: Não existe um Ambiente para a pk pesquisada.
@raise AmbienteUsedByEquipmentVlanError: Existe Equipamento ou Vlan associado ao ambiente que não pode ser removido.
| Efetua a remoção de um Ambiente. | def remove(cls, authenticated_user, pk):
"""Efetua a remoção de um Ambiente.
@return: Nothing
@raise AmbienteError: Falha ao remover um HealthCheckExpect ou Ambiente Config associado ou o Ambiente.
@raise AmbienteNotFoundError: Não existe um Ambiente para a pk pesquisada.
@raise AmbienteUsedByEquipmentVlanError: Existe Equipamento ou Vlan associado ao ambiente que não pode ser removido.
"""
environment = Ambiente().get_by_pk(pk)
from networkapi.ip.models import IpCantBeRemovedFromVip
from networkapi.vlan.models import VlanCantDeallocate
from networkapi.equipamento.models import EquipamentoAmbiente, EquipamentoAmbienteNotFoundError, EquipamentoError
from networkapi.healthcheckexpect.models import HealthcheckExpect, HealthcheckExpectError
# Remove every vlan associated with this environment
for vlan in environment.vlan_set.all():
try:
if vlan.ativada:
vlan.remove(authenticated_user)
vlan.delete()
except VlanCantDeallocate, e:
raise AmbienteUsedByEquipmentVlanError(e.cause, e.message)
except IpCantBeRemovedFromVip, e:
raise AmbienteUsedByEquipmentVlanError(e.cause, e.message)
# Remove every association between equipment and this environment
for equip_env in environment.equipamentoambiente_set.all():
try:
EquipamentoAmbiente.remove(
authenticated_user, equip_env.equipamento_id, equip_env.ambiente_id)
except EquipamentoAmbienteNotFoundError, e:
raise AmbienteUsedByEquipmentVlanError(e, e.message)
except EquipamentoError, e:
raise AmbienteUsedByEquipmentVlanError(e, e.message)
# Dissociate or remove healthcheck expects
try:
HealthcheckExpect.dissociate_environment_and_delete(
authenticated_user, pk)
except HealthcheckExpectError, e:
cls.log.error(u'Falha ao desassociar algum HealthCheckExpect.')
raise AmbienteError(
e, u'Falha ao desassociar algum HealthCheckExpect.')
# Remove ConfigEnvironments associated with environment
try:
ConfigEnvironment.remove_by_environment(authenticated_user, pk)
except (ConfigEnvironmentError, OperationalError, ConfigEnvironmentNotFoundError), e:
cls.log.error(u'Falha ao remover algum Ambiente Config.')
raise AmbienteError(e, u'Falha ao remover algum Ambiente Config.')
# Remove the environment
try:
environment.delete()
delete_cached_searches_list(ENVIRONMENT_CACHE_ENTRY)
except Exception, e:
cls.log.error(u'Falha ao remover o Ambiente.')
raise AmbienteError(e, u'Falha ao remover o Ambiente.') | [
"def",
"remove",
"(",
"cls",
",",
"authenticated_user",
",",
"pk",
")",
":",
"environment",
"=",
"Ambiente",
"(",
")",
".",
"get_by_pk",
"(",
"pk",
")",
"from",
"networkapi",
".",
"ip",
".",
"models",
"import",
"IpCantBeRemovedFromVip",
"from",
"networkapi",
".",
"vlan",
".",
"models",
"import",
"VlanCantDeallocate",
"from",
"networkapi",
".",
"equipamento",
".",
"models",
"import",
"EquipamentoAmbiente",
",",
"EquipamentoAmbienteNotFoundError",
",",
"EquipamentoError",
"from",
"networkapi",
".",
"healthcheckexpect",
".",
"models",
"import",
"HealthcheckExpect",
",",
"HealthcheckExpectError",
"# Remove every vlan associated with this environment",
"for",
"vlan",
"in",
"environment",
".",
"vlan_set",
".",
"all",
"(",
")",
":",
"try",
":",
"if",
"vlan",
".",
"ativada",
":",
"vlan",
".",
"remove",
"(",
"authenticated_user",
")",
"vlan",
".",
"delete",
"(",
")",
"except",
"VlanCantDeallocate",
",",
"e",
":",
"raise",
"AmbienteUsedByEquipmentVlanError",
"(",
"e",
".",
"cause",
",",
"e",
".",
"message",
")",
"except",
"IpCantBeRemovedFromVip",
",",
"e",
":",
"raise",
"AmbienteUsedByEquipmentVlanError",
"(",
"e",
".",
"cause",
",",
"e",
".",
"message",
")",
"# Remove every association between equipment and this environment",
"for",
"equip_env",
"in",
"environment",
".",
"equipamentoambiente_set",
".",
"all",
"(",
")",
":",
"try",
":",
"EquipamentoAmbiente",
".",
"remove",
"(",
"authenticated_user",
",",
"equip_env",
".",
"equipamento_id",
",",
"equip_env",
".",
"ambiente_id",
")",
"except",
"EquipamentoAmbienteNotFoundError",
",",
"e",
":",
"raise",
"AmbienteUsedByEquipmentVlanError",
"(",
"e",
",",
"e",
".",
"message",
")",
"except",
"EquipamentoError",
",",
"e",
":",
"raise",
"AmbienteUsedByEquipmentVlanError",
"(",
"e",
",",
"e",
".",
"message",
")",
"# Dissociate or remove healthcheck expects",
"try",
":",
"HealthcheckExpect",
".",
"dissociate_environment_and_delete",
"(",
"authenticated_user",
",",
"pk",
")",
"except",
"HealthcheckExpectError",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao desassociar algum HealthCheckExpect.'",
")",
"raise",
"AmbienteError",
"(",
"e",
",",
"u'Falha ao desassociar algum HealthCheckExpect.'",
")",
"# Remove ConfigEnvironments associated with environment",
"try",
":",
"ConfigEnvironment",
".",
"remove_by_environment",
"(",
"authenticated_user",
",",
"pk",
")",
"except",
"(",
"ConfigEnvironmentError",
",",
"OperationalError",
",",
"ConfigEnvironmentNotFoundError",
")",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao remover algum Ambiente Config.'",
")",
"raise",
"AmbienteError",
"(",
"e",
",",
"u'Falha ao remover algum Ambiente Config.'",
")",
"# Remove the environment",
"try",
":",
"environment",
".",
"delete",
"(",
")",
"delete_cached_searches_list",
"(",
"ENVIRONMENT_CACHE_ENTRY",
")",
"except",
"Exception",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao remover o Ambiente.'",
")",
"raise",
"AmbienteError",
"(",
"e",
",",
"u'Falha ao remover o Ambiente.'",
")"
] | [
1274,
4
] | [
1335,
67
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
GrupoEquipamentoRemoveAssociationEquipResource.handle_get | (self, request, user, *args, **kwargs) | Trata as requisições de GET remover a associação entre um grupo de equipamento e um equipamento.
URL: egrupo/equipamento/id_equip/egrupo/id_egrupo/
| Trata as requisições de GET remover a associação entre um grupo de equipamento e um equipamento. | def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições de GET remover a associação entre um grupo de equipamento e um equipamento.
URL: egrupo/equipamento/id_equip/egrupo/id_egrupo/
"""
try:
id_equip = kwargs.get('id_equipamento')
id_egrupo = kwargs.get('id_egrupo')
if not is_valid_int_greater_zero_param(id_egrupo):
raise InvalidValueError(None, 'id_egrupo', id_egrupo)
if not is_valid_int_greater_zero_param(id_equip):
raise InvalidValueError(None, 'id_equip', id_equip)
equip = Equipamento.get_by_pk(id_equip)
EGrupo.get_by_pk(id_egrupo)
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION,
id_egrupo,
id_equip,
AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'User does not have permission to perform the operation.')
with distributedlock(LOCK_EQUIPMENT_GROUP % id_egrupo):
EquipamentoGrupo.remove(user, equip.id, id_egrupo)
return self.response(dumps_networkapi({}))
except InvalidValueError, e:
self.log.error(
u'Parameter %s is invalid. Value: %s.', e.param, e.value)
return self.response_error(269, e.param, e.value)
except UserNotAuthorizedError:
return self.not_authorized()
except EquipamentoGrupoNotFoundError, e:
return self.response_error(185, id_equip, id_egrupo)
except EquipamentoNotFoundError, e:
return self.response_error(117, id_equip)
except EGrupoNotFoundError, e:
return self.response_error(102)
except EquipamentoError, e:
return self.response_error(1)
except (XMLError):
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"id_equip",
"=",
"kwargs",
".",
"get",
"(",
"'id_equipamento'",
")",
"id_egrupo",
"=",
"kwargs",
".",
"get",
"(",
"'id_egrupo'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_egrupo",
")",
":",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_egrupo'",
",",
"id_egrupo",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_equip",
")",
":",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_equip'",
",",
"id_equip",
")",
"equip",
"=",
"Equipamento",
".",
"get_by_pk",
"(",
"id_equip",
")",
"EGrupo",
".",
"get_by_pk",
"(",
"id_egrupo",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"id_egrupo",
",",
"id_equip",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"raise",
"UserNotAuthorizedError",
"(",
"None",
",",
"u'User does not have permission to perform the operation.'",
")",
"with",
"distributedlock",
"(",
"LOCK_EQUIPMENT_GROUP",
"%",
"id_egrupo",
")",
":",
"EquipamentoGrupo",
".",
"remove",
"(",
"user",
",",
"equip",
".",
"id",
",",
"id_egrupo",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter %s is invalid. Value: %s.'",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"EquipamentoGrupoNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"185",
",",
"id_equip",
",",
"id_egrupo",
")",
"except",
"EquipamentoNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"id_equip",
")",
"except",
"EGrupoNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"102",
")",
"except",
"EquipamentoError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")",
"except",
"(",
"XMLError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
43,
4
] | [
92,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Poller.despache | (self) | Espera por eventos indefinidamente, tratando-os com seus
callbacks. Termina se nenhum evento pude ser gerado pelos callbacks.
Isso pode ocorrer se todos os callbacks estiverem desativados (monitoramento
do descritor e timeout) | Espera por eventos indefinidamente, tratando-os com seus
callbacks. Termina se nenhum evento pude ser gerado pelos callbacks.
Isso pode ocorrer se todos os callbacks estiverem desativados (monitoramento
do descritor e timeout) | def despache(self):
'''Espera por eventos indefinidamente, tratando-os com seus
callbacks. Termina se nenhum evento pude ser gerado pelos callbacks.
Isso pode ocorrer se todos os callbacks estiverem desativados (monitoramento
do descritor e timeout)'''
while self.despache_simples():
pass | [
"def",
"despache",
"(",
"self",
")",
":",
"while",
"self",
".",
"despache_simples",
"(",
")",
":",
"pass"
] | [
126,
4
] | [
132,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
parse_definite_clause | (s) | Devolver os antecedentes eo consequente de uma cláusula definitiva. | Devolver os antecedentes eo consequente de uma cláusula definitiva. | def parse_definite_clause(s):
"Devolver os antecedentes eo consequente de uma cláusula definitiva."
assert is_definite_clause(s)
if is_symbol(s.op):
return [], s
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent | [
"def",
"parse_definite_clause",
"(",
"s",
")",
":",
"assert",
"is_definite_clause",
"(",
"s",
")",
"if",
"is_symbol",
"(",
"s",
".",
"op",
")",
":",
"return",
"[",
"]",
",",
"s",
"else",
":",
"antecedent",
",",
"consequent",
"=",
"s",
".",
"args",
"return",
"conjuncts",
"(",
"antecedent",
")",
",",
"consequent"
] | [
159,
0
] | [
166,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Callback.handle_timeout | (self) | Trata um timeout associado a este callback. Classes
derivadas devem sobrescrever este método. | Trata um timeout associado a este callback. Classes
derivadas devem sobrescrever este método. | def handle_timeout(self):
'''Trata um timeout associado a este callback. Classes
derivadas devem sobrescrever este método.'''
pass | [
"def",
"handle_timeout",
"(",
"self",
")",
":",
"pass"
] | [
37,
4
] | [
40,
12
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
NetworkData.get_one_global_adress | (cls, scope_name) | return _global_address | Retorna somente os itens de endereço de um router. | Retorna somente os itens de endereço de um router. | def get_one_global_adress(cls, scope_name):
""" Retorna somente os itens de endereço de um router. """
_globals = NetworkData.get_global_network()
for line in _globals:
if line['scope_name'] == scope_name:
_global_address = (f"{line['address']}/{line['mask']}")
print(type(_global_address))
return _global_address | [
"def",
"get_one_global_adress",
"(",
"cls",
",",
"scope_name",
")",
":",
"_globals",
"=",
"NetworkData",
".",
"get_global_network",
"(",
")",
"for",
"line",
"in",
"_globals",
":",
"if",
"line",
"[",
"'scope_name'",
"]",
"==",
"scope_name",
":",
"_global_address",
"=",
"(",
"f\"{line['address']}/{line['mask']}\"",
")",
"print",
"(",
"type",
"(",
"_global_address",
")",
")",
"return",
"_global_address"
] | [
67,
4
] | [
76,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Problem.__init__ | (self, initial, goal=None) | O construtor especifica o estado inicial e possivelmente um esdado objetivo,
se houver uma meta única. O construtor da sua subclasse pode adicionar
outros argumentos. | O construtor especifica o estado inicial e possivelmente um esdado objetivo,
se houver uma meta única. O construtor da sua subclasse pode adicionar
outros argumentos. | def __init__(self, initial, goal=None):
"""O construtor especifica o estado inicial e possivelmente um esdado objetivo,
se houver uma meta única. O construtor da sua subclasse pode adicionar
outros argumentos."""
self.initial = initial
self.goal = goal | [
"def",
"__init__",
"(",
"self",
",",
"initial",
",",
"goal",
"=",
"None",
")",
":",
"self",
".",
"initial",
"=",
"initial",
"self",
".",
"goal",
"=",
"goal"
] | [
25,
4
] | [
30,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestCpf.test_special_case | (self) | Verifica os casos especiais de CPF | Verifica os casos especiais de CPF | def test_special_case(self):
""" Verifica os casos especiais de CPF """
cpfs_repeated_digits = [
'000.000.000-00',
'111.111.111-11',
'222.222.222-22',
'333.333.333-33',
'444.444.444-44',
'555.555.555-55',
'666.666.666-66',
'777.777.777-77',
'888.888.888-88',
'999.999.999-99',
]
# Entrada consideradas invalidas
for cpf in cpfs_repeated_digits:
self.assertFalse(self.cpf.validate(cpf))
# Entrada consideradas validas
self.cpf.repeated_digits = True
for cpf in cpfs_repeated_digits:
self.assertTrue(self.cpf.validate(cpf))
cases = [
('AAA.AAA.AAA+AA', False),
('04255791000144', False),
]
for cpf, is_valid in cases:
self.assertEqual(self.cpf.validate(cpf), is_valid) | [
"def",
"test_special_case",
"(",
"self",
")",
":",
"cpfs_repeated_digits",
"=",
"[",
"'000.000.000-00'",
",",
"'111.111.111-11'",
",",
"'222.222.222-22'",
",",
"'333.333.333-33'",
",",
"'444.444.444-44'",
",",
"'555.555.555-55'",
",",
"'666.666.666-66'",
",",
"'777.777.777-77'",
",",
"'888.888.888-88'",
",",
"'999.999.999-99'",
",",
"]",
"# Entrada consideradas invalidas",
"for",
"cpf",
"in",
"cpfs_repeated_digits",
":",
"self",
".",
"assertFalse",
"(",
"self",
".",
"cpf",
".",
"validate",
"(",
"cpf",
")",
")",
"# Entrada consideradas validas",
"self",
".",
"cpf",
".",
"repeated_digits",
"=",
"True",
"for",
"cpf",
"in",
"cpfs_repeated_digits",
":",
"self",
".",
"assertTrue",
"(",
"self",
".",
"cpf",
".",
"validate",
"(",
"cpf",
")",
")",
"cases",
"=",
"[",
"(",
"'AAA.AAA.AAA+AA'",
",",
"False",
")",
",",
"(",
"'04255791000144'",
",",
"False",
")",
",",
"]",
"for",
"cpf",
",",
"is_valid",
"in",
"cases",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"cpf",
".",
"validate",
"(",
"cpf",
")",
",",
"is_valid",
")"
] | [
29,
4
] | [
56,
62
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
delete_streamer | (idt) | return | Função que elimina streamer da DB com base no id | Função que elimina streamer da DB com base no id | def delete_streamer(idt):
""" Função que elimina streamer da DB com base no id"""
delete = livecoders.delete().where(livecoders.c.id == int(idt))
engine.execute(delete)
return | [
"def",
"delete_streamer",
"(",
"idt",
")",
":",
"delete",
"=",
"livecoders",
".",
"delete",
"(",
")",
".",
"where",
"(",
"livecoders",
".",
"c",
".",
"id",
"==",
"int",
"(",
"idt",
")",
")",
"engine",
".",
"execute",
"(",
"delete",
")",
"return"
] | [
106,
0
] | [
111,
10
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
GradientFrame._draw_gradient | (self, event=None) | Desenhando o gradiente | Desenhando o gradiente | def _draw_gradient(self, event=None):
'''Desenhando o gradiente'''
self.delete("gradient")
width = self.winfo_width()
height = self.winfo_height()
limit = width
(r1,g1,b1) = self.winfo_rgb(self._color1)
(r2,g2,b2) = self.winfo_rgb(self._color2)
r_ratio = float(r2-r1) / limit
g_ratio = float(g2-g1) / limit
b_ratio = float(b2-b1) / limit
for i in range(limit):
nr = int(r1 + (r_ratio * i))
ng = int(g1 + (g_ratio * i))
nb = int(b1 + (b_ratio * i))
color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
self.create_line(i,0,i,height, tags=("gradient"), fill=color)
self.lower("gradient") | [
"def",
"_draw_gradient",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"delete",
"(",
"\"gradient\"",
")",
"width",
"=",
"self",
".",
"winfo_width",
"(",
")",
"height",
"=",
"self",
".",
"winfo_height",
"(",
")",
"limit",
"=",
"width",
"(",
"r1",
",",
"g1",
",",
"b1",
")",
"=",
"self",
".",
"winfo_rgb",
"(",
"self",
".",
"_color1",
")",
"(",
"r2",
",",
"g2",
",",
"b2",
")",
"=",
"self",
".",
"winfo_rgb",
"(",
"self",
".",
"_color2",
")",
"r_ratio",
"=",
"float",
"(",
"r2",
"-",
"r1",
")",
"/",
"limit",
"g_ratio",
"=",
"float",
"(",
"g2",
"-",
"g1",
")",
"/",
"limit",
"b_ratio",
"=",
"float",
"(",
"b2",
"-",
"b1",
")",
"/",
"limit",
"for",
"i",
"in",
"range",
"(",
"limit",
")",
":",
"nr",
"=",
"int",
"(",
"r1",
"+",
"(",
"r_ratio",
"*",
"i",
")",
")",
"ng",
"=",
"int",
"(",
"g1",
"+",
"(",
"g_ratio",
"*",
"i",
")",
")",
"nb",
"=",
"int",
"(",
"b1",
"+",
"(",
"b_ratio",
"*",
"i",
")",
")",
"color",
"=",
"\"#%4.4x%4.4x%4.4x\"",
"%",
"(",
"nr",
",",
"ng",
",",
"nb",
")",
"self",
".",
"create_line",
"(",
"i",
",",
"0",
",",
"i",
",",
"height",
",",
"tags",
"=",
"(",
"\"gradient\"",
")",
",",
"fill",
"=",
"color",
")",
"self",
".",
"lower",
"(",
"\"gradient\"",
")"
] | [
9,
4
] | [
27,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Scope.return_debug | (self) | Retorna status de criação do objeto. | Retorna status de criação do objeto. | def return_debug(self):
""" Retorna status de criação do objeto."""
if self:
return f'ADDR: Criada rede {self.name} com endereço {self.global_address}/{self.global_mask}'
else:
return f'ADDR: Objeto ADDR não criado!' | [
"def",
"return_debug",
"(",
"self",
")",
":",
"if",
"self",
":",
"return",
"f'ADDR: Criada rede {self.name} com endereço {self.global_address}/{self.global_mask}'",
"else",
":",
"return",
"f'ADDR: Objeto ADDR não criado!'"
] | [
48,
4
] | [
54,
52
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Factor.p | (self, e) | return self.cpt[event_values(e, self.variables)] | Procure meu valor tabulado para e. | Procure meu valor tabulado para e. | def p(self, e):
"Procure meu valor tabulado para e."
return self.cpt[event_values(e, self.variables)] | [
"def",
"p",
"(",
"self",
",",
"e",
")",
":",
"return",
"self",
".",
"cpt",
"[",
"event_values",
"(",
"e",
",",
"self",
".",
"variables",
")",
"]"
] | [
385,
4
] | [
387,
56
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Pesquisador.getDadosUFCG | (self, CPF) | return DadosUFCG | Caso seja desejada informação da base de dados da SRH, obtem SIAPE e lotação do servidor a partir do CPF.
Args:
CPF (type): str `CPF`.
Returns:
type: Array [Matrícula, Lotação].
| Caso seja desejada informação da base de dados da SRH, obtem SIAPE e lotação do servidor a partir do CPF. | def getDadosUFCG(self, CPF):
"""Caso seja desejada informação da base de dados da SRH, obtem SIAPE e lotação do servidor a partir do CPF.
Args:
CPF (type): str `CPF`.
Returns:
type: Array [Matrícula, Lotação].
"""
self.carregaDadosGlobais()
if self.__UFCG:
paths = self.validaPath()
df = pd.read_excel(paths['pathUFCG'])
df['CPF'] = df['CPF'].astype(str)
#----Se não encontrar retorna empty dataframe que pode ser manipulado.
DadosUFCG = df[df['CPF']==CPF][['CPF','Matrícula','Lotação']]
else:
DadosUFCG = None
return DadosUFCG | [
"def",
"getDadosUFCG",
"(",
"self",
",",
"CPF",
")",
":",
"self",
".",
"carregaDadosGlobais",
"(",
")",
"if",
"self",
".",
"__UFCG",
":",
"paths",
"=",
"self",
".",
"validaPath",
"(",
")",
"df",
"=",
"pd",
".",
"read_excel",
"(",
"paths",
"[",
"'pathUFCG'",
"]",
")",
"df",
"[",
"'CPF'",
"]",
"=",
"df",
"[",
"'CPF'",
"]",
".",
"astype",
"(",
"str",
")",
"#----Se não encontrar retorna empty dataframe que pode ser manipulado.",
"DadosUFCG",
"=",
"df",
"[",
"df",
"[",
"'CPF'",
"]",
"==",
"CPF",
"]",
"[",
"[",
"'CPF'",
",",
"'Matrícula',",
"'",
"Lotação']]",
"",
"",
"else",
":",
"DadosUFCG",
"=",
"None",
"return",
"DadosUFCG"
] | [
422,
4
] | [
441,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Battery.get_range | (self) | Exibe uma frase sobre a distância que o carro é capaz de percorrer com essa bateria. | Exibe uma frase sobre a distância que o carro é capaz de percorrer com essa bateria. | def get_range(self):
"""Exibe uma frase sobre a distância que o carro é capaz de percorrer com essa bateria."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = 'This car can go approximately ' + str(range) + ' miles on a full charge.'
print('\t' + message) | [
"def",
"get_range",
"(",
"self",
")",
":",
"if",
"self",
".",
"battery_size",
"==",
"70",
":",
"range",
"=",
"240",
"elif",
"self",
".",
"battery_size",
"==",
"85",
":",
"range",
"=",
"270",
"message",
"=",
"'This car can go approximately '",
"+",
"str",
"(",
"range",
")",
"+",
"' miles on a full charge.'",
"print",
"(",
"'\\t'",
"+",
"message",
")"
] | [
45,
4
] | [
53,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TraceAgent | (agent) | return agent | Acompanha o programa do agente para imprimir sua entrada e saída. Isso deixará
Você ver o que o agente está fazendo no ambiente. | Acompanha o programa do agente para imprimir sua entrada e saída. Isso deixará
Você ver o que o agente está fazendo no ambiente. | def TraceAgent(agent):
"""Acompanha o programa do agente para imprimir sua entrada e saída. Isso deixará
Você ver o que o agente está fazendo no ambiente."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print('{} percebe {} e faz {}'.format(agent, percept, action))
return action
agent.program = new_program
return agent | [
"def",
"TraceAgent",
"(",
"agent",
")",
":",
"old_program",
"=",
"agent",
".",
"program",
"def",
"new_program",
"(",
"percept",
")",
":",
"action",
"=",
"old_program",
"(",
"percept",
")",
"print",
"(",
"'{} percebe {} e faz {}'",
".",
"format",
"(",
"agent",
",",
"percept",
",",
"action",
")",
")",
"return",
"action",
"agent",
".",
"program",
"=",
"new_program",
"return",
"agent"
] | [
63,
0
] | [
73,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update | (tree, index, value) | Atualiza o valor de um determinado indice.
:param index: indice do elemento que se deseja atualizar.
:param value: valor que se deseja colocar no indice.
:param tree: arvore de fenwick, lista/vetor aonde estão os elementos.
| Atualiza o valor de um determinado indice.
:param index: indice do elemento que se deseja atualizar.
:param value: valor que se deseja colocar no indice.
:param tree: arvore de fenwick, lista/vetor aonde estão os elementos.
| def update(tree, index, value):
""" Atualiza o valor de um determinado indice.
:param index: indice do elemento que se deseja atualizar.
:param value: valor que se deseja colocar no indice.
:param tree: arvore de fenwick, lista/vetor aonde estão os elementos.
"""
while index < len(tree):
tree[index] += value
index += (index & -index) | [
"def",
"update",
"(",
"tree",
",",
"index",
",",
"value",
")",
":",
"while",
"index",
"<",
"len",
"(",
"tree",
")",
":",
"tree",
"[",
"index",
"]",
"+=",
"value",
"index",
"+=",
"(",
"index",
"&",
"-",
"index",
")"
] | [
16,
0
] | [
25,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Subcamada.conecta | (self, superior) | Conexão entre camadas | Conexão entre camadas | def conecta(self, superior):
'''Conexão entre camadas'''
self.upper = superior
superior.lower = self | [
"def",
"conecta",
"(",
"self",
",",
"superior",
")",
":",
"self",
".",
"upper",
"=",
"superior",
"superior",
".",
"lower",
"=",
"self"
] | [
18,
4
] | [
21,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
sudoku | () | return sc | A função sudoku tem como objetivo gerar um sudoku aleatório e completo e armazenar o valor na variável em que foi chamado a função, irá armazenar em apenas uma variável, uma lista com 9 listas contendo os números de 1 a 9 em casa uma, de forma que complete um sudoku, sendo o primeiro índice a primeira linha, o segundo índice a segunda linha e assim por diante | A função sudoku tem como objetivo gerar um sudoku aleatório e completo e armazenar o valor na variável em que foi chamado a função, irá armazenar em apenas uma variável, uma lista com 9 listas contendo os números de 1 a 9 em casa uma, de forma que complete um sudoku, sendo o primeiro índice a primeira linha, o segundo índice a segunda linha e assim por diante | def sudoku():
"""A função sudoku tem como objetivo gerar um sudoku aleatório e completo e armazenar o valor na variável em que foi chamado a função, irá armazenar em apenas uma variável, uma lista com 9 listas contendo os números de 1 a 9 em casa uma, de forma que complete um sudoku, sendo o primeiro índice a primeira linha, o segundo índice a segunda linha e assim por diante"""
n = (1, 2, 3, 4, 5, 6, 7, 8, 9)
c = 0
loop = 0
#cada linha do sudoku
l1 = [0,0,0,0,0,0,0,0,0]
l2 = [0,0,0,0,0,0,0,0,0]
l3 = [0,0,0,0,0,0,0,0,0]
l4 = [0,0,0,0,0,0,0,0,0]
l5 = [0,0,0,0,0,0,0,0,0]
l6 = [0,0,0,0,0,0,0,0,0]
l7 = [0,0,0,0,0,0,0,0,0]
l8 = [0,0,0,0,0,0,0,0,0]
l9 = [0,0,0,0,0,0,0,0,0]
nl = 0
while nl < 10:
#sorteando os numeros de cada linha
for i in range(0, 9): #linha 1
l1[i] = random.choice(n)
veri = i
while l1[veri] in l1[:veri]:
l1[i] = random.choice(n)
#adicionando os dados para comparar nos próximos sorteios
bloco1 = l1[0:3]
bloco2 = l1[3:6]
bloco3 = l1[6:9]
i = 0
loop = 0
while i < 9: #linha 2
l2[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l2[veri] in l2[:veri] or l2[veri] in bloco1:
l2[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l2[veri] in l2[:veri] or l2[veri] in bloco2:
l2[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l2[veri] in l2[:veri] or l2[veri] in bloco3:
l2[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100: #caso entre em loop a linha será reiniciada
c = c - c
i = 0
if loop > 1000:
break
bloco1 = bloco1 + l2[0:3]
bloco2 = bloco2 + l2[3:6]
bloco3 = bloco3 + l2[6:9]
i = 0
loop = 0
while i < 9: #linha 3
l3[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l3[veri] in l3[:veri] or l3[veri] in bloco1:
l3[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l3[veri] in l3[:veri] or l3[veri] in bloco2:
l3[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l3[veri] in l3[:veri] or l3[veri] in bloco3:
l3[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco1 = bloco1 + l3[0:3]
bloco2 = bloco2 + l3[3:6]
bloco3 = bloco3 + l3[6:9]
c1 = [l1[0], l2[0], l3[0]]
c2 = [l1[1], l2[1], l3[1]]
c3 = [l1[2], l2[2], l3[2]]
c4 = [l1[3], l2[3], l3[3]]
c5 = [l1[4], l2[4], l3[4]]
c6 = [l1[5], l2[5], l3[5]]
c7 = [l1[6], l2[6], l3[6]]
c8 = [l1[7], l2[7], l3[7]]
c9 = [l1[8], l2[8], l3[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 4
l4[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l4[veri] in l4[:veri] or l4[veri] in llista[veri]:
l4[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l4[veri] in l4[:veri] or l4[veri] in llista[veri]:
l4[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l4[veri] in l4[:veri] or l4[veri] in llista[veri]:
l4[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco4 = l4[0:3]
bloco5 = l4[3:6]
bloco6 = l4[6:9]
c1 = c1 + [l4[0]]
c2 = c2 + [l4[1]]
c3 = c3 + [l4[2]]
c4 = c4 + [l4[3]]
c5 = c5 + [l4[4]]
c6 = c6 + [l4[5]]
c7 = c7 + [l4[6]]
c8 = c8 + [l4[7]]
c9 = c9 + [l4[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 5
l5[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l5[veri] in l5[:veri] or l5[veri] in bloco4 or l5[veri] in llista[veri]:
l5[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l5[veri] in l5[:veri] or l5[veri] in bloco5 or l5[veri] in llista[veri]:
l5[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l5[veri] in l5[:veri] or l5[veri] in bloco6 or l5[veri] in llista[veri]:
l5[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco4 = bloco4 + l5[0:3]
bloco5 = bloco5 + l5[3:6]
bloco6 = bloco6 + l5[6:9]
c1 = c1 + [l5[0]]
c2 = c2 + [l5[1]]
c3 = c3 + [l5[2]]
c4 = c4 + [l5[3]]
c5 = c5 + [l5[4]]
c6 = c6 + [l5[5]]
c7 = c7 + [l5[6]]
c8 = c8 + [l5[7]]
c9 = c9 + [l5[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 6
l6[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l6[veri] in l6[:veri] or l6[veri] in bloco4 or l6[veri] in llista[veri]:
l6[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l6[veri] in l6[:veri] or l6[veri] in bloco5 or l6[veri] in llista[veri]:
l6[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l6[veri] in l6[:veri] or l6[veri] in bloco6 or l6[veri] in llista[veri]:
l6[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco4 = bloco4 + l6[0:3]
bloco5 = bloco5 + l6[3:6]
bloco6 = bloco6 + l6[6:9]
c1 = c1 + [l6[0]]
c2 = c2 + [l6[1]]
c3 = c3 + [l6[2]]
c4 = c4 + [l6[3]]
c5 = c5 + [l6[4]]
c6 = c6 + [l6[5]]
c7 = c7 + [l6[6]]
c8 = c8 + [l6[7]]
c9 = c9 + [l6[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 7
l7[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l7[veri] in l7[:veri] or l7[veri] in llista[veri]:
l7[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l7[veri] in l7[:veri] or l7[veri] in llista[veri]:
l7[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l7[veri] in l7[:veri] or l7[veri] in llista[veri]:
l7[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco7 = l7[0:3]
bloco8 = l7[3:6]
bloco9 = l7[6:9]
c1 = c1 + [l7[0]]
c2 = c2 + [l7[1]]
c3 = c3 + [l7[2]]
c4 = c4 + [l7[3]]
c5 = c5 + [l7[4]]
c6 = c6 + [l7[5]]
c7 = c7 + [l7[6]]
c8 = c8 + [l7[7]]
c9 = c9 + [l7[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 8
l8[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l8[veri] in l8[:veri] or l8[veri] in bloco7 or l8[veri] in llista[veri]:
l8[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l8[veri] in l8[:veri] or l8[veri] in bloco8 or l8[veri] in llista[veri]:
l8[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l8[veri] in l8[:veri] or l8[veri] in bloco9 or l8[veri] in llista[veri]:
l8[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco7 = bloco7 + l8[0:3]
bloco8 = bloco8 + l8[3:6]
bloco9 = bloco9 + l8[6:9]
c1 = c1 + [l8[0]]
c2 = c2 + [l8[1]]
c3 = c3 + [l8[2]]
c4 = c4 + [l8[3]]
c5 = c5 + [l8[4]]
c6 = c6 + [l8[5]]
c7 = c7 + [l8[6]]
c8 = c8 + [l8[7]]
c9 = c9 + [l8[8]]
llista = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
i = 0
loop = 0
while i < 9: #linha 9
l9[i] = random.choice(n)
veri = i
c = 0
if i < 3:
while l9[veri] in l9[:veri] or l9[veri] in bloco7 or l9[veri] in llista[veri]:
l9[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 3 and i <6:
while l9[veri] in l9[:veri] or l9[veri] in bloco8 or l9[veri] in llista[veri]:
l9[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
c = 0
if i >= 6 and i < 9:
while l9[veri] in l9[:veri] or l9[veri] in bloco9 or l9[veri] in llista[veri]:
l9[i] = random.choice(n)
c = c + 1
loop = loop + 1
if c > 100:
i = 0
break
i = i + 1
if c > 100:
c = c - c
i = 0
if loop > 1000:
break
bloco7 = bloco7 + l9[0:3]
bloco8 = bloco8 + l9[3:6]
bloco9 = bloco9 + l9[6:9]
c1 = c1 + [l9[0]]
c2 = c2 + [l9[1]]
c3 = c3 + [l9[2]]
c4 = c4 + [l9[3]]
c5 = c5 + [l9[4]]
c6 = c6 + [l9[5]]
c7 = c7 + [l9[6]]
c8 = c8 + [l9[7]]
c9 = c9 + [l9[8]]
nl = nl + 1
if loop <= 1000:
break
loop = 0
#sudoku completo
sc = [l1, l2, l3, l4, l5, l6, l7, l8, l9]
return sc | [
"def",
"sudoku",
"(",
")",
":",
"n",
"=",
"(",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
")",
"c",
"=",
"0",
"loop",
"=",
"0",
"#cada linha do sudoku",
"l1",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l2",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l3",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l4",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l5",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l6",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l7",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l8",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"l9",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"nl",
"=",
"0",
"while",
"nl",
"<",
"10",
":",
"#sorteando os numeros de cada linha",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"9",
")",
":",
"#linha 1",
"l1",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"while",
"l1",
"[",
"veri",
"]",
"in",
"l1",
"[",
":",
"veri",
"]",
":",
"l1",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"#adicionando os dados para comparar nos próximos sorteios",
"bloco1",
"=",
"l1",
"[",
"0",
":",
"3",
"]",
"bloco2",
"=",
"l1",
"[",
"3",
":",
"6",
"]",
"bloco3",
"=",
"l1",
"[",
"6",
":",
"9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 2",
"l2",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l2",
"[",
"veri",
"]",
"in",
"l2",
"[",
":",
"veri",
"]",
"or",
"l2",
"[",
"veri",
"]",
"in",
"bloco1",
":",
"l2",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l2",
"[",
"veri",
"]",
"in",
"l2",
"[",
":",
"veri",
"]",
"or",
"l2",
"[",
"veri",
"]",
"in",
"bloco2",
":",
"l2",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l2",
"[",
"veri",
"]",
"in",
"l2",
"[",
":",
"veri",
"]",
"or",
"l2",
"[",
"veri",
"]",
"in",
"bloco3",
":",
"l2",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"#caso entre em loop a linha será reiniciada",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco1",
"=",
"bloco1",
"+",
"l2",
"[",
"0",
":",
"3",
"]",
"bloco2",
"=",
"bloco2",
"+",
"l2",
"[",
"3",
":",
"6",
"]",
"bloco3",
"=",
"bloco3",
"+",
"l2",
"[",
"6",
":",
"9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 3",
"l3",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l3",
"[",
"veri",
"]",
"in",
"l3",
"[",
":",
"veri",
"]",
"or",
"l3",
"[",
"veri",
"]",
"in",
"bloco1",
":",
"l3",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l3",
"[",
"veri",
"]",
"in",
"l3",
"[",
":",
"veri",
"]",
"or",
"l3",
"[",
"veri",
"]",
"in",
"bloco2",
":",
"l3",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l3",
"[",
"veri",
"]",
"in",
"l3",
"[",
":",
"veri",
"]",
"or",
"l3",
"[",
"veri",
"]",
"in",
"bloco3",
":",
"l3",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco1",
"=",
"bloco1",
"+",
"l3",
"[",
"0",
":",
"3",
"]",
"bloco2",
"=",
"bloco2",
"+",
"l3",
"[",
"3",
":",
"6",
"]",
"bloco3",
"=",
"bloco3",
"+",
"l3",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"[",
"l1",
"[",
"0",
"]",
",",
"l2",
"[",
"0",
"]",
",",
"l3",
"[",
"0",
"]",
"]",
"c2",
"=",
"[",
"l1",
"[",
"1",
"]",
",",
"l2",
"[",
"1",
"]",
",",
"l3",
"[",
"1",
"]",
"]",
"c3",
"=",
"[",
"l1",
"[",
"2",
"]",
",",
"l2",
"[",
"2",
"]",
",",
"l3",
"[",
"2",
"]",
"]",
"c4",
"=",
"[",
"l1",
"[",
"3",
"]",
",",
"l2",
"[",
"3",
"]",
",",
"l3",
"[",
"3",
"]",
"]",
"c5",
"=",
"[",
"l1",
"[",
"4",
"]",
",",
"l2",
"[",
"4",
"]",
",",
"l3",
"[",
"4",
"]",
"]",
"c6",
"=",
"[",
"l1",
"[",
"5",
"]",
",",
"l2",
"[",
"5",
"]",
",",
"l3",
"[",
"5",
"]",
"]",
"c7",
"=",
"[",
"l1",
"[",
"6",
"]",
",",
"l2",
"[",
"6",
"]",
",",
"l3",
"[",
"6",
"]",
"]",
"c8",
"=",
"[",
"l1",
"[",
"7",
"]",
",",
"l2",
"[",
"7",
"]",
",",
"l3",
"[",
"7",
"]",
"]",
"c9",
"=",
"[",
"l1",
"[",
"8",
"]",
",",
"l2",
"[",
"8",
"]",
",",
"l3",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 4",
"l4",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l4",
"[",
"veri",
"]",
"in",
"l4",
"[",
":",
"veri",
"]",
"or",
"l4",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l4",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l4",
"[",
"veri",
"]",
"in",
"l4",
"[",
":",
"veri",
"]",
"or",
"l4",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l4",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l4",
"[",
"veri",
"]",
"in",
"l4",
"[",
":",
"veri",
"]",
"or",
"l4",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l4",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco4",
"=",
"l4",
"[",
"0",
":",
"3",
"]",
"bloco5",
"=",
"l4",
"[",
"3",
":",
"6",
"]",
"bloco6",
"=",
"l4",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l4",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l4",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l4",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l4",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l4",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l4",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l4",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l4",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l4",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 5",
"l5",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l5",
"[",
"veri",
"]",
"in",
"l5",
"[",
":",
"veri",
"]",
"or",
"l5",
"[",
"veri",
"]",
"in",
"bloco4",
"or",
"l5",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l5",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l5",
"[",
"veri",
"]",
"in",
"l5",
"[",
":",
"veri",
"]",
"or",
"l5",
"[",
"veri",
"]",
"in",
"bloco5",
"or",
"l5",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l5",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l5",
"[",
"veri",
"]",
"in",
"l5",
"[",
":",
"veri",
"]",
"or",
"l5",
"[",
"veri",
"]",
"in",
"bloco6",
"or",
"l5",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l5",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco4",
"=",
"bloco4",
"+",
"l5",
"[",
"0",
":",
"3",
"]",
"bloco5",
"=",
"bloco5",
"+",
"l5",
"[",
"3",
":",
"6",
"]",
"bloco6",
"=",
"bloco6",
"+",
"l5",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l5",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l5",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l5",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l5",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l5",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l5",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l5",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l5",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l5",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 6",
"l6",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l6",
"[",
"veri",
"]",
"in",
"l6",
"[",
":",
"veri",
"]",
"or",
"l6",
"[",
"veri",
"]",
"in",
"bloco4",
"or",
"l6",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l6",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l6",
"[",
"veri",
"]",
"in",
"l6",
"[",
":",
"veri",
"]",
"or",
"l6",
"[",
"veri",
"]",
"in",
"bloco5",
"or",
"l6",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l6",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l6",
"[",
"veri",
"]",
"in",
"l6",
"[",
":",
"veri",
"]",
"or",
"l6",
"[",
"veri",
"]",
"in",
"bloco6",
"or",
"l6",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l6",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco4",
"=",
"bloco4",
"+",
"l6",
"[",
"0",
":",
"3",
"]",
"bloco5",
"=",
"bloco5",
"+",
"l6",
"[",
"3",
":",
"6",
"]",
"bloco6",
"=",
"bloco6",
"+",
"l6",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l6",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l6",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l6",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l6",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l6",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l6",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l6",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l6",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l6",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 7",
"l7",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l7",
"[",
"veri",
"]",
"in",
"l7",
"[",
":",
"veri",
"]",
"or",
"l7",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l7",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l7",
"[",
"veri",
"]",
"in",
"l7",
"[",
":",
"veri",
"]",
"or",
"l7",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l7",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l7",
"[",
"veri",
"]",
"in",
"l7",
"[",
":",
"veri",
"]",
"or",
"l7",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l7",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco7",
"=",
"l7",
"[",
"0",
":",
"3",
"]",
"bloco8",
"=",
"l7",
"[",
"3",
":",
"6",
"]",
"bloco9",
"=",
"l7",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l7",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l7",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l7",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l7",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l7",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l7",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l7",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l7",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l7",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 8",
"l8",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l8",
"[",
"veri",
"]",
"in",
"l8",
"[",
":",
"veri",
"]",
"or",
"l8",
"[",
"veri",
"]",
"in",
"bloco7",
"or",
"l8",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l8",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l8",
"[",
"veri",
"]",
"in",
"l8",
"[",
":",
"veri",
"]",
"or",
"l8",
"[",
"veri",
"]",
"in",
"bloco8",
"or",
"l8",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l8",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l8",
"[",
"veri",
"]",
"in",
"l8",
"[",
":",
"veri",
"]",
"or",
"l8",
"[",
"veri",
"]",
"in",
"bloco9",
"or",
"l8",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l8",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco7",
"=",
"bloco7",
"+",
"l8",
"[",
"0",
":",
"3",
"]",
"bloco8",
"=",
"bloco8",
"+",
"l8",
"[",
"3",
":",
"6",
"]",
"bloco9",
"=",
"bloco9",
"+",
"l8",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l8",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l8",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l8",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l8",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l8",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l8",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l8",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l8",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l8",
"[",
"8",
"]",
"]",
"llista",
"=",
"[",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"]",
"i",
"=",
"0",
"loop",
"=",
"0",
"while",
"i",
"<",
"9",
":",
"#linha 9",
"l9",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"veri",
"=",
"i",
"c",
"=",
"0",
"if",
"i",
"<",
"3",
":",
"while",
"l9",
"[",
"veri",
"]",
"in",
"l9",
"[",
":",
"veri",
"]",
"or",
"l9",
"[",
"veri",
"]",
"in",
"bloco7",
"or",
"l9",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l9",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"3",
"and",
"i",
"<",
"6",
":",
"while",
"l9",
"[",
"veri",
"]",
"in",
"l9",
"[",
":",
"veri",
"]",
"or",
"l9",
"[",
"veri",
"]",
"in",
"bloco8",
"or",
"l9",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l9",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"c",
"=",
"0",
"if",
"i",
">=",
"6",
"and",
"i",
"<",
"9",
":",
"while",
"l9",
"[",
"veri",
"]",
"in",
"l9",
"[",
":",
"veri",
"]",
"or",
"l9",
"[",
"veri",
"]",
"in",
"bloco9",
"or",
"l9",
"[",
"veri",
"]",
"in",
"llista",
"[",
"veri",
"]",
":",
"l9",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"n",
")",
"c",
"=",
"c",
"+",
"1",
"loop",
"=",
"loop",
"+",
"1",
"if",
"c",
">",
"100",
":",
"i",
"=",
"0",
"break",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
">",
"100",
":",
"c",
"=",
"c",
"-",
"c",
"i",
"=",
"0",
"if",
"loop",
">",
"1000",
":",
"break",
"bloco7",
"=",
"bloco7",
"+",
"l9",
"[",
"0",
":",
"3",
"]",
"bloco8",
"=",
"bloco8",
"+",
"l9",
"[",
"3",
":",
"6",
"]",
"bloco9",
"=",
"bloco9",
"+",
"l9",
"[",
"6",
":",
"9",
"]",
"c1",
"=",
"c1",
"+",
"[",
"l9",
"[",
"0",
"]",
"]",
"c2",
"=",
"c2",
"+",
"[",
"l9",
"[",
"1",
"]",
"]",
"c3",
"=",
"c3",
"+",
"[",
"l9",
"[",
"2",
"]",
"]",
"c4",
"=",
"c4",
"+",
"[",
"l9",
"[",
"3",
"]",
"]",
"c5",
"=",
"c5",
"+",
"[",
"l9",
"[",
"4",
"]",
"]",
"c6",
"=",
"c6",
"+",
"[",
"l9",
"[",
"5",
"]",
"]",
"c7",
"=",
"c7",
"+",
"[",
"l9",
"[",
"6",
"]",
"]",
"c8",
"=",
"c8",
"+",
"[",
"l9",
"[",
"7",
"]",
"]",
"c9",
"=",
"c9",
"+",
"[",
"l9",
"[",
"8",
"]",
"]",
"nl",
"=",
"nl",
"+",
"1",
"if",
"loop",
"<=",
"1000",
":",
"break",
"loop",
"=",
"0",
"#sudoku completo",
"sc",
"=",
"[",
"l1",
",",
"l2",
",",
"l3",
",",
"l4",
",",
"l5",
",",
"l6",
",",
"l7",
",",
"l8",
",",
"l9",
"]",
"return",
"sc"
] | [
2,
0
] | [
490,
10
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Gatinho.dormir | (self) | Muda o estado do gato para dormindo. | Muda o estado do gato para dormindo. | def dormir(self):
"""Muda o estado do gato para dormindo."""
if not self.dormindo:
self.dormindo = True
print('zzZzZzzzz')
else:
print(f'{self.nome} já está dormindo!') | [
"def",
"dormir",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"dormindo",
":",
"self",
".",
"dormindo",
"=",
"True",
"print",
"(",
"'zzZzZzzzz'",
")",
"else",
":",
"print",
"(",
"f'{self.nome} já está dormindo!')",
""
] | [
40,
4
] | [
47,
53
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
SistemaLivros.editar_livro | (self) | Pede ao usuario uma referencia para selecionar
um livro, após isso, é possivel alterar parametros
existentes ou adicionar novos dentro do dicionario
que armazena informações sobre o livro | Pede ao usuario uma referencia para selecionar
um livro, após isso, é possivel alterar parametros
existentes ou adicionar novos dentro do dicionario
que armazena informações sobre o livro | def editar_livro(self):
""" Pede ao usuario uma referencia para selecionar
um livro, após isso, é possivel alterar parametros
existentes ou adicionar novos dentro do dicionario
que armazena informações sobre o livro """
cont = 0
print("Todos os livros registrados no sistema : \n")
for registro in self.dados:
print(f"Número de identificação [{cont}]")
for item in registro.items():
print(f"{item[0]} : {item[1]}")
cont += 1
print('='*55)
numero_id = int(input("""Digite o número de identificação
do livro que deseja alterar : """))
chave = input("""Digite qual informação deseja alterar ou adicionar
(Caso essa informação ainda não esteja cadastrada, o sistema irá adicionar,
caso esteja, irá alterar : """)
valor = input("Digite agora a informação em sí :")
self.dados[numero_id].update({chave.lower().replace(" ","_"):valor}) | [
"def",
"editar_livro",
"(",
"self",
")",
":",
"cont",
"=",
"0",
"print",
"(",
"\"Todos os livros registrados no sistema : \\n\"",
")",
"for",
"registro",
"in",
"self",
".",
"dados",
":",
"print",
"(",
"f\"Número de identificação [{cont}]\")",
"",
"for",
"item",
"in",
"registro",
".",
"items",
"(",
")",
":",
"print",
"(",
"f\"{item[0]} : {item[1]}\"",
")",
"cont",
"+=",
"1",
"print",
"(",
"'='",
"*",
"55",
")",
"numero_id",
"=",
"int",
"(",
"input",
"(",
"\"\"\"Digite o número de identificação\n do livro que deseja alterar : \"\"\"",
")",
")",
"chave",
"=",
"input",
"(",
"\"\"\"Digite qual informação deseja alterar ou adicionar\n (Caso essa informação ainda não esteja cadastrada, o sistema irá adicionar,\n caso esteja, irá alterar : \"\"\")",
"",
"valor",
"=",
"input",
"(",
"\"Digite agora a informação em sí :\")",
"",
"self",
".",
"dados",
"[",
"numero_id",
"]",
".",
"update",
"(",
"{",
"chave",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
":",
"valor",
"}",
")"
] | [
100,
4
] | [
120,
76
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Interface.get_server_switch_or_router_interface_from_host_interface | (self, protegida=None) | return interface | A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH.
@param protegida: Indicação do campo 'protegida' da interface do switch.
@return: Interface ligada a um equipamento do tipo SWITCH.
@raise InterfaceError: Falha ao pesquisar a interface do switch
@raise InterfaceNotFoundError: Interface do switch não encontrada.
@raise InterfaceProtectedError: A interface do switch está com o campo protegida diferente do parâmetro.
| A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH. | def get_server_switch_or_router_interface_from_host_interface(self, protegida=None):
"""A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH.
@param protegida: Indicação do campo 'protegida' da interface do switch.
@return: Interface ligada a um equipamento do tipo SWITCH.
@raise InterfaceError: Falha ao pesquisar a interface do switch
@raise InterfaceNotFoundError: Interface do switch não encontrada.
@raise InterfaceProtectedError: A interface do switch está com o campo protegida diferente do parâmetro.
"""
interface_ids = []
from_interface = self
interface = self.ligacao_front
try:
while (interface is not None) \
and (interface.equipamento.tipo_equipamento_id != TipoEquipamento.TIPO_EQUIPAMENTO_SWITCH) \
and (interface.equipamento.tipo_equipamento_id != TipoEquipamento.TIPO_EQUIPAMENTO_ROUTER)\
and (interface.equipamento.tipo_equipamento_id != TipoEquipamento.TIPO_EQUIPAMENTO_SERVIDOR):
interface_ids.append(interface.id)
if (interface.ligacao_back is not None) and (from_interface.id != interface.ligacao_back_id):
from_interface = interface
interface = interface.ligacao_back
elif (interface.ligacao_front is not None) and (from_interface.id != interface.ligacao_front_id):
from_interface = interface
interface = interface.ligacao_front
else:
interface = None
if interface is not None:
if interface.id in interface_ids:
raise InterfaceNotFoundError(None,
u'Interface do tipo switch não encontrada a partir do front da '
u'interface %d.' % self.id)
except InterfaceNotFoundError, e:
raise e
except Exception, e:
self.log.error(u'Falha ao pesquisar a interface do switch.')
raise InterfaceError(
e, u'Falha ao pesquisar a interface do switch.')
if interface is None:
raise InterfaceNotFoundError(
None, u'Interface do tipo switch não encontrada a partir do front da interface %d.' % self.id)
if (protegida is not None) and (interface.protegida != protegida):
raise InterfaceProtectedError(
None, u'Interface do switch com o campo protegida diferente de %s.' % protegida)
return interface | [
"def",
"get_server_switch_or_router_interface_from_host_interface",
"(",
"self",
",",
"protegida",
"=",
"None",
")",
":",
"interface_ids",
"=",
"[",
"]",
"from_interface",
"=",
"self",
"interface",
"=",
"self",
".",
"ligacao_front",
"try",
":",
"while",
"(",
"interface",
"is",
"not",
"None",
")",
"and",
"(",
"interface",
".",
"equipamento",
".",
"tipo_equipamento_id",
"!=",
"TipoEquipamento",
".",
"TIPO_EQUIPAMENTO_SWITCH",
")",
"and",
"(",
"interface",
".",
"equipamento",
".",
"tipo_equipamento_id",
"!=",
"TipoEquipamento",
".",
"TIPO_EQUIPAMENTO_ROUTER",
")",
"and",
"(",
"interface",
".",
"equipamento",
".",
"tipo_equipamento_id",
"!=",
"TipoEquipamento",
".",
"TIPO_EQUIPAMENTO_SERVIDOR",
")",
":",
"interface_ids",
".",
"append",
"(",
"interface",
".",
"id",
")",
"if",
"(",
"interface",
".",
"ligacao_back",
"is",
"not",
"None",
")",
"and",
"(",
"from_interface",
".",
"id",
"!=",
"interface",
".",
"ligacao_back_id",
")",
":",
"from_interface",
"=",
"interface",
"interface",
"=",
"interface",
".",
"ligacao_back",
"elif",
"(",
"interface",
".",
"ligacao_front",
"is",
"not",
"None",
")",
"and",
"(",
"from_interface",
".",
"id",
"!=",
"interface",
".",
"ligacao_front_id",
")",
":",
"from_interface",
"=",
"interface",
"interface",
"=",
"interface",
".",
"ligacao_front",
"else",
":",
"interface",
"=",
"None",
"if",
"interface",
"is",
"not",
"None",
":",
"if",
"interface",
".",
"id",
"in",
"interface_ids",
":",
"raise",
"InterfaceNotFoundError",
"(",
"None",
",",
"u'Interface do tipo switch não encontrada a partir do front da '",
"u'interface %d.'",
"%",
"self",
".",
"id",
")",
"except",
"InterfaceNotFoundError",
",",
"e",
":",
"raise",
"e",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Falha ao pesquisar a interface do switch.'",
")",
"raise",
"InterfaceError",
"(",
"e",
",",
"u'Falha ao pesquisar a interface do switch.'",
")",
"if",
"interface",
"is",
"None",
":",
"raise",
"InterfaceNotFoundError",
"(",
"None",
",",
"u'Interface do tipo switch não encontrada a partir do front da interface %d.' ",
" ",
"elf.",
"i",
"d)",
"",
"if",
"(",
"protegida",
"is",
"not",
"None",
")",
"and",
"(",
"interface",
".",
"protegida",
"!=",
"protegida",
")",
":",
"raise",
"InterfaceProtectedError",
"(",
"None",
",",
"u'Interface do switch com o campo protegida diferente de %s.'",
"%",
"protegida",
")",
"return",
"interface"
] | [
331,
4
] | [
384,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
AmbienteEquipamentoResource.handle_get | (self, request, user, *args, **kwargs) | Trata as requisições de GET para consulta de um ambiente.
Consulta o ambiente de um IP associado a um Equipamento.
URL: /ambiente/equipamento/<nome_equip>/ip/<x1>.<x2>.<x3>.<x4>/
| Trata as requisições de GET para consulta de um ambiente. | def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições de GET para consulta de um ambiente.
Consulta o ambiente de um IP associado a um Equipamento.
URL: /ambiente/equipamento/<nome_equip>/ip/<x1>.<x2>.<x3>.<x4>/
"""
equipment_name = kwargs.get('nome_equip')
oct1 = kwargs.get('x1')
oct2 = kwargs.get('x2')
oct3 = kwargs.get('x3')
oct4 = kwargs.get('x4')
if equipment_name is None or oct1 is None or oct2 is None or oct3 is None or oct4 is None:
return super(AmbienteEquipamentoResource, self).handle_get(request, user, *args, **kwargs)
self.log.debug('nome_equip = %s', equipment_name)
self.log.debug('x1 = %s', oct1)
self.log.debug('x2 = %s', oct2)
self.log.debug('x3 = %s', oct3)
self.log.debug('x4 = %s', oct4)
try:
equip = Equipamento().get_by_name(equipment_name)
if not has_perm(user,
AdminPermission.ENVIRONMENT_MANAGEMENT,
AdminPermission.READ_OPERATION,
None,
equip.id,
AdminPermission.EQUIP_READ_OPERATION):
return self.not_authorized()
ip = Ip().get_by_octs_equipment(oct1, oct2, oct3, oct4, equip.id)
environment_map = get_environment_map(ip.vlan.ambiente)
map = dict()
map['ambiente'] = environment_map
return self.response(dumps_networkapi(map))
except EquipamentoNotFoundError:
return self.response_error(117, equipment_name)
except IpNotFoundError:
return self.response_error(118, oct1 + '.' + oct2 + '.' + oct3 + '.' + oct4, equip.id)
except (IpError, EquipamentoError, GrupoError):
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"equipment_name",
"=",
"kwargs",
".",
"get",
"(",
"'nome_equip'",
")",
"oct1",
"=",
"kwargs",
".",
"get",
"(",
"'x1'",
")",
"oct2",
"=",
"kwargs",
".",
"get",
"(",
"'x2'",
")",
"oct3",
"=",
"kwargs",
".",
"get",
"(",
"'x3'",
")",
"oct4",
"=",
"kwargs",
".",
"get",
"(",
"'x4'",
")",
"if",
"equipment_name",
"is",
"None",
"or",
"oct1",
"is",
"None",
"or",
"oct2",
"is",
"None",
"or",
"oct3",
"is",
"None",
"or",
"oct4",
"is",
"None",
":",
"return",
"super",
"(",
"AmbienteEquipamentoResource",
",",
"self",
")",
".",
"handle_get",
"(",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'nome_equip = %s'",
",",
"equipment_name",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'x1 = %s'",
",",
"oct1",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'x2 = %s'",
",",
"oct2",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'x3 = %s'",
",",
"oct3",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'x4 = %s'",
",",
"oct4",
")",
"try",
":",
"equip",
"=",
"Equipamento",
"(",
")",
".",
"get_by_name",
"(",
"equipment_name",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"ENVIRONMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
",",
"None",
",",
"equip",
".",
"id",
",",
"AdminPermission",
".",
"EQUIP_READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"ip",
"=",
"Ip",
"(",
")",
".",
"get_by_octs_equipment",
"(",
"oct1",
",",
"oct2",
",",
"oct3",
",",
"oct4",
",",
"equip",
".",
"id",
")",
"environment_map",
"=",
"get_environment_map",
"(",
"ip",
".",
"vlan",
".",
"ambiente",
")",
"map",
"=",
"dict",
"(",
")",
"map",
"[",
"'ambiente'",
"]",
"=",
"environment_map",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"map",
")",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"equipment_name",
")",
"except",
"IpNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"118",
",",
"oct1",
"+",
"'.'",
"+",
"oct2",
"+",
"'.'",
"+",
"oct3",
"+",
"'.'",
"+",
"oct4",
",",
"equip",
".",
"id",
")",
"except",
"(",
"IpError",
",",
"EquipamentoError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
661,
4
] | [
707,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
OverlapCommunity.calcula_fitness_v2 | (self, modulo, grafo) | V2 do calculo de fitness | V2 do calculo de fitness | def calcula_fitness_v2(self, modulo, grafo):
"""V2 do calculo de fitness"""
sub_grafo = grafo.subgraph(modulo)
k_interno = sub_grafo.number_of_edges()
# print("\nV2 K interno",k_interno)
# print(modulo)
k_externo = 0
for i in modulo:
diferenca = set(grafo.adj[i]).difference(set(modulo))
k_externo += len(diferenca)
# print("V2 K-externo",k_externo)
try:
return k_interno / (pow(k_externo + k_interno, self.alfa))
except Exception as e:
return k_interno / (pow(k_externo + k_interno, self.alfa)) | [
"def",
"calcula_fitness_v2",
"(",
"self",
",",
"modulo",
",",
"grafo",
")",
":",
"sub_grafo",
"=",
"grafo",
".",
"subgraph",
"(",
"modulo",
")",
"k_interno",
"=",
"sub_grafo",
".",
"number_of_edges",
"(",
")",
"# print(\"\\nV2 K interno\",k_interno)",
"# print(modulo)",
"k_externo",
"=",
"0",
"for",
"i",
"in",
"modulo",
":",
"diferenca",
"=",
"set",
"(",
"grafo",
".",
"adj",
"[",
"i",
"]",
")",
".",
"difference",
"(",
"set",
"(",
"modulo",
")",
")",
"k_externo",
"+=",
"len",
"(",
"diferenca",
")",
"# print(\"V2 K-externo\",k_externo)",
"try",
":",
"return",
"k_interno",
"/",
"(",
"pow",
"(",
"k_externo",
"+",
"k_interno",
",",
"self",
".",
"alfa",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"k_interno",
"/",
"(",
"pow",
"(",
"k_externo",
"+",
"k_interno",
",",
"self",
".",
"alfa",
")",
")"
] | [
134,
4
] | [
148,
70
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Log.warning | (self, msg, *args) | Imprime uma mensagem de advertência no log | Imprime uma mensagem de advertência no log | def warning(self, msg, *args):
"""Imprime uma mensagem de advertência no log"""
self.__emit(self.logger.warning, msg, args) | [
"def",
"warning",
"(",
"self",
",",
"msg",
",",
"*",
"args",
")",
":",
"self",
".",
"__emit",
"(",
"self",
".",
"logger",
".",
"warning",
",",
"msg",
",",
"args",
")"
] | [
240,
4
] | [
242,
51
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Room.__repr__ | (self) | return str([self.wumpus.value, self.pit.value, self.gold.value]) | Retorna a representação de sequência de caracteres dessa instância. | Retorna a representação de sequência de caracteres dessa instância. | def __repr__(self):
"""Retorna a representação de sequência de caracteres dessa instância."""
return str([self.wumpus.value, self.pit.value, self.gold.value]) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"str",
"(",
"[",
"self",
".",
"wumpus",
".",
"value",
",",
"self",
".",
"pit",
".",
"value",
",",
"self",
".",
"gold",
".",
"value",
"]",
")"
] | [
26,
2
] | [
30,
68
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Ship.__init__ | (self,ai_settings,screen) | inicializa a espaçonave e define sua posição inicial. | inicializa a espaçonave e define sua posição inicial. | def __init__(self,ai_settings,screen):
'''inicializa a espaçonave e define sua posição inicial.'''
self.screen = screen
self.ai_settings = ai_settings
#carrega a imagem da espaçonave e obtem seu rect
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#inicia cada nova espaçonave na parte inferior central da tela
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#Armazena um valor decimal para o centro da espaçonave
self.center = float(self.rect.centerx)
#Flag de movimento
self.moving_right = False
self.moving_left = False | [
"def",
"__init__",
"(",
"self",
",",
"ai_settings",
",",
"screen",
")",
":",
"self",
".",
"screen",
"=",
"screen",
"self",
".",
"ai_settings",
"=",
"ai_settings",
"#carrega a imagem da espaçonave e obtem seu rect",
"self",
".",
"image",
"=",
"pygame",
".",
"image",
".",
"load",
"(",
"'images/ship.bmp'",
")",
"self",
".",
"rect",
"=",
"self",
".",
"image",
".",
"get_rect",
"(",
")",
"self",
".",
"screen_rect",
"=",
"screen",
".",
"get_rect",
"(",
")",
"#inicia cada nova espaçonave na parte inferior central da tela",
"self",
".",
"rect",
".",
"centerx",
"=",
"self",
".",
"screen_rect",
".",
"centerx",
"self",
".",
"rect",
".",
"bottom",
"=",
"self",
".",
"screen_rect",
".",
"bottom",
"#Armazena um valor decimal para o centro da espaçonave",
"self",
".",
"center",
"=",
"float",
"(",
"self",
".",
"rect",
".",
"centerx",
")",
"#Flag de movimento",
"self",
".",
"moving_right",
"=",
"False",
"self",
".",
"moving_left",
"=",
"False"
] | [
4,
4
] | [
23,
32
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ProbDist.__init__ | (self, varname="?", freqs=None) | Se freqs é dado, é um dicionário de valor: pares de frequência,
e o ProbDist então é normalizado. | Se freqs é dado, é um dicionário de valor: pares de frequência,
e o ProbDist então é normalizado. | def __init__(self, varname="?", freqs=None):
"""Se freqs é dado, é um dicionário de valor: pares de frequência,
e o ProbDist então é normalizado."""
self.prob = {}
self.varname = varname
self.values = []
if freqs:
for (v, p) in freqs.items():
self[v] = p
self.normalize() | [
"def",
"__init__",
"(",
"self",
",",
"varname",
"=",
"\"?\"",
",",
"freqs",
"=",
"None",
")",
":",
"self",
".",
"prob",
"=",
"{",
"}",
"self",
".",
"varname",
"=",
"varname",
"self",
".",
"values",
"=",
"[",
"]",
"if",
"freqs",
":",
"for",
"(",
"v",
",",
"p",
")",
"in",
"freqs",
".",
"items",
"(",
")",
":",
"self",
"[",
"v",
"]",
"=",
"p",
"self",
".",
"normalize",
"(",
")"
] | [
47,
4
] | [
56,
28
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Configuracoes.descrever | (self) | Descreve as configurações na saída padrão ou no terminal, se
houver um.
| Descreve as configurações na saída padrão ou no terminal, se
houver um.
| def descrever(self):
"""Descreve as configurações na saída padrão ou no terminal, se
houver um.
"""
import sathub
_verbose(u'SATHub versão {}', sathub.__version__)
_verbose(u'[-] "{:s}"', self.descricao)
_verbose(u'[-] Biblioteca "{:s}"', self.caminho_biblioteca)
_verbose(u'[-] Convencao Chamada {:d} - {:s}',
self.convencao_chamada,
self.nome_convencao_chamada)
_verbose('[-] ')
_verbose('') | [
"def",
"descrever",
"(",
"self",
")",
":",
"import",
"sathub",
"_verbose",
"(",
"u'SATHub versão {}',",
" ",
"athub.",
"_",
"_version__)",
"",
"_verbose",
"(",
"u'[-] \"{:s}\"'",
",",
"self",
".",
"descricao",
")",
"_verbose",
"(",
"u'[-] Biblioteca \"{:s}\"'",
",",
"self",
".",
"caminho_biblioteca",
")",
"_verbose",
"(",
"u'[-] Convencao Chamada {:d} - {:s}'",
",",
"self",
".",
"convencao_chamada",
",",
"self",
".",
"nome_convencao_chamada",
")",
"_verbose",
"(",
"'[-] '",
")",
"_verbose",
"(",
"''",
")"
] | [
224,
4
] | [
236,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update | (id) | return render_template('editora/update.html', editora=editora, error=error) | Atualiza uma editora pelo seu respectivo id. | Atualiza uma editora pelo seu respectivo id. | def update(id):
"""Atualiza uma editora pelo seu respectivo id."""
editora = get_editora(id)
error = None
if request.method == 'POST':
nome = request.form['nome']
error = None
if not nome:
error = 'Nome é obrigatório.'
if nome == editora['nome']:
return redirect(url_for('editora.index'))
else:
try:
if verifica_editora_bd(nome):
error = 'Essa editora já está registrada!'
else:
db.insert_bd('UPDATE editora set nome = "%s" where id = %d' % (nome, id))
return redirect(url_for('editora.index'))
except:
return render_template('404.html')
return render_template('editora/update.html', editora=editora, error=error) | [
"def",
"update",
"(",
"id",
")",
":",
"editora",
"=",
"get_editora",
"(",
"id",
")",
"error",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"nome",
"=",
"request",
".",
"form",
"[",
"'nome'",
"]",
"error",
"=",
"None",
"if",
"not",
"nome",
":",
"error",
"=",
"'Nome é obrigatório.'",
"if",
"nome",
"==",
"editora",
"[",
"'nome'",
"]",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'editora.index'",
")",
")",
"else",
":",
"try",
":",
"if",
"verifica_editora_bd",
"(",
"nome",
")",
":",
"error",
"=",
"'Essa editora já está registrada!'",
"else",
":",
"db",
".",
"insert_bd",
"(",
"'UPDATE editora set nome = \"%s\" where id = %d'",
"%",
"(",
"nome",
",",
"id",
")",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'editora.index'",
")",
")",
"except",
":",
"return",
"render_template",
"(",
"'404.html'",
")",
"return",
"render_template",
"(",
"'editora/update.html'",
",",
"editora",
"=",
"editora",
",",
"error",
"=",
"error",
")"
] | [
80,
0
] | [
103,
79
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TipoRedeResource.handle_get | (self, request, user, *args, **kwargs) | Trata as requisições GET para consulta de tipos de rede.
Permite a consulta de tipos de rede existentes.
URL: /tiporede/
| Trata as requisições GET para consulta de tipos de rede. | def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições GET para consulta de tipos de rede.
Permite a consulta de tipos de rede existentes.
URL: /tiporede/
"""
try:
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
# Efetua a consulta de todos os tipos de rede
results = TipoRede.search()
if results.count() > 0:
# Monta lista com dados retornados
map_list = []
for item in results:
item_map = self.get_tipo_rede_map(item)
map_list.append(item_map)
# Gera response (XML) com resultados
return self.response(dumps_networkapi({'tipo_rede': map_list}))
else:
# Gera response (XML) para resultado vazio
return self.response(dumps_networkapi({}))
except (VlanError, GrupoError):
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"NETWORK_TYPE_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"# Efetua a consulta de todos os tipos de rede",
"results",
"=",
"TipoRede",
".",
"search",
"(",
")",
"if",
"results",
".",
"count",
"(",
")",
">",
"0",
":",
"# Monta lista com dados retornados",
"map_list",
"=",
"[",
"]",
"for",
"item",
"in",
"results",
":",
"item_map",
"=",
"self",
".",
"get_tipo_rede_map",
"(",
"item",
")",
"map_list",
".",
"append",
"(",
"item_map",
")",
"# Gera response (XML) com resultados",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'tipo_rede'",
":",
"map_list",
"}",
")",
")",
"else",
":",
"# Gera response (XML) para resultado vazio",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"(",
"VlanError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
37,
4
] | [
66,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
renegados | (ctx) | lista os players que marcaram e tiraram a marcação | lista os players que marcaram e tiraram a marcação | async def renegados(ctx):
'''lista os players que marcaram e tiraram a marcação'''
separator = '\n-'
await ctx.send("```diff\nRENEGADOS (" + str(len(renegades)) + "): \n-"+separator.join(renegades)+"```") | [
"async",
"def",
"renegados",
"(",
"ctx",
")",
":",
"separator",
"=",
"'\\n-'",
"await",
"ctx",
".",
"send",
"(",
"\"```diff\\nRENEGADOS (\"",
"+",
"str",
"(",
"len",
"(",
"renegades",
")",
")",
"+",
"\"): \\n-\"",
"+",
"separator",
".",
"join",
"(",
"renegades",
")",
"+",
"\"```\"",
")"
] | [
114,
0
] | [
117,
104
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update_aliens | (ai_settings,stats, screen, sb, ship, aliens, bullets) | Verifica se a frota esta em duas bordas
e entao atualiza as posicoes de todos os alienigenas da frota. | Verifica se a frota esta em duas bordas
e entao atualiza as posicoes de todos os alienigenas da frota. | def update_aliens(ai_settings,stats, screen, sb, ship, aliens, bullets):
"""Verifica se a frota esta em duas bordas
e entao atualiza as posicoes de todos os alienigenas da frota."""
check_fleet_edges(ai_settings, aliens)
aliens.update()
# Verifica se houve colisoes entre alienigenas e a espaconave
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)
# Verifica se ha algum alienigena que atingiu a parte inferior da tela
check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets) | [
"def",
"update_aliens",
"(",
"ai_settings",
",",
"stats",
",",
"screen",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
":",
"check_fleet_edges",
"(",
"ai_settings",
",",
"aliens",
")",
"aliens",
".",
"update",
"(",
")",
"# Verifica se houve colisoes entre alienigenas e a espaconave",
"if",
"pygame",
".",
"sprite",
".",
"spritecollideany",
"(",
"ship",
",",
"aliens",
")",
":",
"ship_hit",
"(",
"ai_settings",
",",
"stats",
",",
"screen",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
"# Verifica se ha algum alienigena que atingiu a parte inferior da tela",
"check_aliens_bottom",
"(",
"ai_settings",
",",
"stats",
",",
"screen",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")"
] | [
201,
0
] | [
213,
78
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Main.brincar | (self) | Ações principais da ação brincar no menu. | Ações principais da ação brincar no menu. | def brincar(self):
"""Ações principais da ação brincar no menu."""
cfunc.mudar_titulo('Escolher brinquedo')
janela = cjane.JanelaTable({'##': 4, 'Nome': 58, 'Felicidade': 14})
# imprime os brinquedos disponíveis para brincar em ordem de felicidade
brinqs = self.bau.brinquedosort()
for i in range(len(brinqs)):
janela.add_linha([i+1, brinqs[i].nome, brinqs[i].feliz])
janela.mostrar_janela(show_input=False)
brinq = input('Digite o número do brinquedo para jogar (ENTER para voltar): ')
while brinq != '' and (not brinq.isnumeric() or int(brinq) not in range(1, len(brinqs)+1)):
janela.mostrar_janela(show_input=False)
if not brinq.isnumeric():
brinq = input('Digite um valor numérico (ENTER para voltar): ')
else:
brinq = input('Digite um número válido (ENTER para voltar): ')
if brinq != '':
# seleciona o brinquedo com menor durabilidade dentre os do tipo escolhido para brincar
brinq_nome = brinqs[int(brinq) - 1].nome
menor_dura = min(self.bau[brinq_nome])
cfunc.mudar_titulo(f'Brincando com {brinq_nome}')
self.gato.brincar(self.bau, menor_dura)
return True
else:
return False | [
"def",
"brincar",
"(",
"self",
")",
":",
"cfunc",
".",
"mudar_titulo",
"(",
"'Escolher brinquedo'",
")",
"janela",
"=",
"cjane",
".",
"JanelaTable",
"(",
"{",
"'##'",
":",
"4",
",",
"'Nome'",
":",
"58",
",",
"'Felicidade'",
":",
"14",
"}",
")",
"# imprime os brinquedos disponíveis para brincar em ordem de felicidade",
"brinqs",
"=",
"self",
".",
"bau",
".",
"brinquedosort",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"brinqs",
")",
")",
":",
"janela",
".",
"add_linha",
"(",
"[",
"i",
"+",
"1",
",",
"brinqs",
"[",
"i",
"]",
".",
"nome",
",",
"brinqs",
"[",
"i",
"]",
".",
"feliz",
"]",
")",
"janela",
".",
"mostrar_janela",
"(",
"show_input",
"=",
"False",
")",
"brinq",
"=",
"input",
"(",
"'Digite o número do brinquedo para jogar (ENTER para voltar): ')",
"",
"while",
"brinq",
"!=",
"''",
"and",
"(",
"not",
"brinq",
".",
"isnumeric",
"(",
")",
"or",
"int",
"(",
"brinq",
")",
"not",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"brinqs",
")",
"+",
"1",
")",
")",
":",
"janela",
".",
"mostrar_janela",
"(",
"show_input",
"=",
"False",
")",
"if",
"not",
"brinq",
".",
"isnumeric",
"(",
")",
":",
"brinq",
"=",
"input",
"(",
"'Digite um valor numérico (ENTER para voltar): ')",
"",
"else",
":",
"brinq",
"=",
"input",
"(",
"'Digite um número válido (ENTER para voltar): ')",
"",
"if",
"brinq",
"!=",
"''",
":",
"# seleciona o brinquedo com menor durabilidade dentre os do tipo escolhido para brincar",
"brinq_nome",
"=",
"brinqs",
"[",
"int",
"(",
"brinq",
")",
"-",
"1",
"]",
".",
"nome",
"menor_dura",
"=",
"min",
"(",
"self",
".",
"bau",
"[",
"brinq_nome",
"]",
")",
"cfunc",
".",
"mudar_titulo",
"(",
"f'Brincando com {brinq_nome}'",
")",
"self",
".",
"gato",
".",
"brincar",
"(",
"self",
".",
"bau",
",",
"menor_dura",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | [
354,
4
] | [
388,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
readFolder | (PATH="../../data/raw/CVs") | return files | Le todos os arquivos XML que estiverem no caminho indicado e em subpastas.
Args:
PATH (type): Caminho para arquivos XML de Curriculos Lattes `PATH`. Defaults to "../../data/raw/CVs".
Returns:
type: Lista com o nome dos arquivos em path absoluto.
| Le todos os arquivos XML que estiverem no caminho indicado e em subpastas. | def readFolder(PATH="../../data/raw/CVs"):
"""Le todos os arquivos XML que estiverem no caminho indicado e em subpastas.
Args:
PATH (type): Caminho para arquivos XML de Curriculos Lattes `PATH`. Defaults to "../../data/raw/CVs".
Returns:
type: Lista com o nome dos arquivos em path absoluto.
"""
path = pathHandler(PATH)
maskCV = str(path) + "/*.xml"
try:
files = glob(maskCV)
except OsError as error:
#LOG.error("readFolder: %s", error)
sys.exit(error)
n = len(files)
#LOG.info("readFolder: %s Arquivos XML lidos", n)
return files | [
"def",
"readFolder",
"(",
"PATH",
"=",
"\"../../data/raw/CVs\"",
")",
":",
"path",
"=",
"pathHandler",
"(",
"PATH",
")",
"maskCV",
"=",
"str",
"(",
"path",
")",
"+",
"\"/*.xml\"",
"try",
":",
"files",
"=",
"glob",
"(",
"maskCV",
")",
"except",
"OsError",
"as",
"error",
":",
"#LOG.error(\"readFolder: %s\", error)",
"sys",
".",
"exit",
"(",
"error",
")",
"n",
"=",
"len",
"(",
"files",
")",
"#LOG.info(\"readFolder: %s Arquivos XML lidos\", n)",
"return",
"files"
] | [
92,
0
] | [
111,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Anuncio.visualizacoes | (self) | return int(visualizacoes) | Retorna a quantidade máxima de visualizações do anúncio | Retorna a quantidade máxima de visualizações do anúncio | def visualizacoes(self) -> int:
"""Retorna a quantidade máxima de visualizações do anúncio"""
visualizacoes = calcula_alcance_anuncio(self.total_investido)
return int(visualizacoes) | [
"def",
"visualizacoes",
"(",
"self",
")",
"->",
"int",
":",
"visualizacoes",
"=",
"calcula_alcance_anuncio",
"(",
"self",
".",
"total_investido",
")",
"return",
"int",
"(",
"visualizacoes",
")"
] | [
90,
4
] | [
93,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
json_remove_vazio | (strJson) | return json.dumps(cp_dados) | remove linhas / elementos vazios de uma string Json | remove linhas / elementos vazios de uma string Json | def json_remove_vazio(strJson):
''' remove linhas / elementos vazios de uma string Json '''
strJson.replace("\n","")
try:
dados = json.loads(strJson) # converte string para dict
except Exception as e:
if e.__class__.__name__ == 'JSONDecodeError':
log.warning ("erro json.load: " + strJson)
else:
mostraErro(e, 40, "on_message")
cp_dados = json.loads(strJson) # cria uma copia
for k,v in dados.items():
if len(v) == 0:
cp_dados.pop(k) # remove vazio
return json.dumps(cp_dados) | [
"def",
"json_remove_vazio",
"(",
"strJson",
")",
":",
"strJson",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"try",
":",
"dados",
"=",
"json",
".",
"loads",
"(",
"strJson",
")",
"# converte string para dict",
"except",
"Exception",
"as",
"e",
":",
"if",
"e",
".",
"__class__",
".",
"__name__",
"==",
"'JSONDecodeError'",
":",
"log",
".",
"warning",
"(",
"\"erro json.load: \"",
"+",
"strJson",
")",
"else",
":",
"mostraErro",
"(",
"e",
",",
"40",
",",
"\"on_message\"",
")",
"cp_dados",
"=",
"json",
".",
"loads",
"(",
"strJson",
")",
"# cria uma copia",
"for",
"k",
",",
"v",
"in",
"dados",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"v",
")",
"==",
"0",
":",
"cp_dados",
".",
"pop",
"(",
"k",
")",
"# remove vazio",
"return",
"json",
".",
"dumps",
"(",
"cp_dados",
")"
] | [
330,
0
] | [
344,
31
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
media_matriz | (matriz) | return round(media,2) | Recebe uma matriz númerica. Com base no total
da somatória de todos os elementos e as dimensões
da matriz, calcula a média aritmética dos elementos
da matriz
list -> float | Recebe uma matriz númerica. Com base no total
da somatória de todos os elementos e as dimensões
da matriz, calcula a média aritmética dos elementos
da matriz
list -> float | def media_matriz(matriz):
""" Recebe uma matriz númerica. Com base no total
da somatória de todos os elementos e as dimensões
da matriz, calcula a média aritmética dos elementos
da matriz
list -> float """
linhas = float(len(matriz))
colunas = float(len(matriz[0]))
total = 0
for linha in matriz:
for coluna in linha:
total += float(coluna)
media = (total / (linhas * colunas))
return round(media,2) | [
"def",
"media_matriz",
"(",
"matriz",
")",
":",
"linhas",
"=",
"float",
"(",
"len",
"(",
"matriz",
")",
")",
"colunas",
"=",
"float",
"(",
"len",
"(",
"matriz",
"[",
"0",
"]",
")",
")",
"total",
"=",
"0",
"for",
"linha",
"in",
"matriz",
":",
"for",
"coluna",
"in",
"linha",
":",
"total",
"+=",
"float",
"(",
"coluna",
")",
"media",
"=",
"(",
"total",
"/",
"(",
"linhas",
"*",
"colunas",
")",
")",
"return",
"round",
"(",
"media",
",",
"2",
")"
] | [
2,
0
] | [
18,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
read | (filename) | return[
req.strip() # Comando retira o /n após a leitura do conteúdo do arquivo
for req
in open(filename).readlines()
] | Funçao responsável em ler os arquivos 'requirements.txt' e pegar o conteúdo do arquivo para posterior uso no 'setup.py | Funçao responsável em ler os arquivos 'requirements.txt' e pegar o conteúdo do arquivo para posterior uso no 'setup.py | def read(filename):
"""Funçao responsável em ler os arquivos 'requirements.txt' e pegar o conteúdo do arquivo para posterior uso no 'setup.py'"""
return[
req.strip() # Comando retira o /n após a leitura do conteúdo do arquivo
for req
in open(filename).readlines()
] | [
"def",
"read",
"(",
"filename",
")",
":",
"return",
"[",
"req",
".",
"strip",
"(",
")",
"# Comando retira o /n após a leitura do conteúdo do arquivo",
"for",
"req",
"in",
"open",
"(",
"filename",
")",
".",
"readlines",
"(",
")",
"]"
] | [
3,
0
] | [
9,
5
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
App.switch_frame | (self, frame, btn=None) | Recebe um frame como parâmetro, oculta os frames ativos e inicia o frame recebido | Recebe um frame como parâmetro, oculta os frames ativos e inicia o frame recebido | def switch_frame(self, frame, btn=None):
"""Recebe um frame como parâmetro, oculta os frames ativos e inicia o frame recebido"""
self.ocultar_paginas()
frame.iniciar_pagina()
self.switch_btn_color()
if btn:
btn['background'] = '#4444ff' | [
"def",
"switch_frame",
"(",
"self",
",",
"frame",
",",
"btn",
"=",
"None",
")",
":",
"self",
".",
"ocultar_paginas",
"(",
")",
"frame",
".",
"iniciar_pagina",
"(",
")",
"self",
".",
"switch_btn_color",
"(",
")",
"if",
"btn",
":",
"btn",
"[",
"'background'",
"]",
"=",
"'#4444ff'"
] | [
145,
4
] | [
151,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
minio_parser | (args) | return parser | Parser utilizado para capturar informações sobre conexão
com o Min.io | Parser utilizado para capturar informações sobre conexão
com o Min.io | def minio_parser(args):
"""Parser utilizado para capturar informações sobre conexão
com o Min.io"""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
"--minio_host",
required=True,
help="""Host to connect to Min.io ObjectStorage, e.g: "play.min.io:9000" """,
)
parser.add_argument(
"--minio_access_key", required=True, help="Access key to Min.io, e.g: minion"
)
parser.add_argument(
"--minio_secret_key", required=True, help="Secure key to Min.io, e.g: minion123"
)
parser.add_argument(
"--minio_is_secure",
default=False,
help="if connection wich to Min.io is secure, default False",
action="store_true",
)
return parser | [
"def",
"minio_parser",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"\"--minio_host\"",
",",
"required",
"=",
"True",
",",
"help",
"=",
"\"\"\"Host to connect to Min.io ObjectStorage, e.g: \"play.min.io:9000\" \"\"\"",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"--minio_access_key\"",
",",
"required",
"=",
"True",
",",
"help",
"=",
"\"Access key to Min.io, e.g: minion\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--minio_secret_key\"",
",",
"required",
"=",
"True",
",",
"help",
"=",
"\"Secure key to Min.io, e.g: minion123\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--minio_is_secure\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"if connection wich to Min.io is secure, default False\"",
",",
"action",
"=",
"\"store_true\"",
",",
")",
"return",
"parser"
] | [
31,
0
] | [
53,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
convert_tensor2array | (tensor) | return tensor.cpu().detach().numpy()[0] | Função para converter de tensor para array
Parâmetros:
tensor: tensor
| Função para converter de tensor para array
Parâmetros:
tensor: tensor
| def convert_tensor2array(tensor):
'''Função para converter de tensor para array
Parâmetros:
tensor: tensor
'''
return tensor.cpu().detach().numpy()[0] | [
"def",
"convert_tensor2array",
"(",
"tensor",
")",
":",
"return",
"tensor",
".",
"cpu",
"(",
")",
".",
"detach",
"(",
")",
".",
"numpy",
"(",
")",
"[",
"0",
"]"
] | [
1,
0
] | [
6,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Tarefa.votar | (self, username, respostas) | computa mais um voto para o usuario nesta tarefa | computa mais um voto para o usuario nesta tarefa | def votar(self, username, respostas):
"computa mais um voto para o usuario nesta tarefa"
trabalho = self.campanha.obter_trabalho(username)
# acrescenta a resposta
for resposta_informada in respostas:
resposta = Resposta()
resposta.username = username
resposta.tarefa = self
resposta.trabalho = trabalho
resposta.nome_campo = resposta_informada['nomecampo']
resposta.valor = resposta_informada['resposta']
resposta.save() | [
"def",
"votar",
"(",
"self",
",",
"username",
",",
"respostas",
")",
":",
"trabalho",
"=",
"self",
".",
"campanha",
".",
"obter_trabalho",
"(",
"username",
")",
"# acrescenta a resposta",
"for",
"resposta_informada",
"in",
"respostas",
":",
"resposta",
"=",
"Resposta",
"(",
")",
"resposta",
".",
"username",
"=",
"username",
"resposta",
".",
"tarefa",
"=",
"self",
"resposta",
".",
"trabalho",
"=",
"trabalho",
"resposta",
".",
"nome_campo",
"=",
"resposta_informada",
"[",
"'nomecampo'",
"]",
"resposta",
".",
"valor",
"=",
"resposta_informada",
"[",
"'resposta'",
"]",
"resposta",
".",
"save",
"(",
")"
] | [
140,
4
] | [
152,
27
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Settings.initialize_dynamic_settings | (self) | Inicializa as configurações que mudam no decorrer do jogo | Inicializa as configurações que mudam no decorrer do jogo | def initialize_dynamic_settings(self):
"""Inicializa as configurações que mudam no decorrer do jogo"""
self.ship_speed_factor = 2
self.bullet_speed_factor = 2
self.alien_speed_factor = 1
# Fleet_direction igual a 1 representa a direita; -1 representa a esquerda
self.fleet_direction = 1
# Pontuação
self.alien_points = 50 | [
"def",
"initialize_dynamic_settings",
"(",
"self",
")",
":",
"self",
".",
"ship_speed_factor",
"=",
"2",
"self",
".",
"bullet_speed_factor",
"=",
"2",
"self",
".",
"alien_speed_factor",
"=",
"1",
"# Fleet_direction igual a 1 representa a direita; -1 representa a esquerda",
"self",
".",
"fleet_direction",
"=",
"1",
"# Pontuação",
"self",
".",
"alien_points",
"=",
"50"
] | [
35,
4
] | [
44,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
is_prop_symbol | (s) | return is_symbol(s) and s[0].isupper() | Um símbolo de lógica de proposição é uma string inicial maiúscula. | Um símbolo de lógica de proposição é uma string inicial maiúscula. | def is_prop_symbol(s):
"""Um símbolo de lógica de proposição é uma string inicial maiúscula."""
return is_symbol(s) and s[0].isupper() | [
"def",
"is_prop_symbol",
"(",
"s",
")",
":",
"return",
"is_symbol",
"(",
"s",
")",
"and",
"s",
"[",
"0",
"]",
".",
"isupper",
"(",
")"
] | [
136,
0
] | [
138,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
check_dict | (items) | Verifica se há valores inválidos nos dicts.
Args:
items (List[Dict]): Dicts a serem verificados
Raises:
KeyError: Se existir algum valor inválido no dict.
| Verifica se há valores inválidos nos dicts. | def check_dict(items):
"""Verifica se há valores inválidos nos dicts.
Args:
items (List[Dict]): Dicts a serem verificados
Raises:
KeyError: Se existir algum valor inválido no dict.
"""
len_keys = None
for item in items:
if len_keys is None:
len_keys = len(item.keys())
invalid_item = any([
None in item.keys(),
None in item.values(),
'' in item.keys(),
'' in item.values(),
len_keys != len(item.keys())
])
if invalid_item:
raise KeyError('Dados inválidos nesse item:', item) | [
"def",
"check_dict",
"(",
"items",
")",
":",
"len_keys",
"=",
"None",
"for",
"item",
"in",
"items",
":",
"if",
"len_keys",
"is",
"None",
":",
"len_keys",
"=",
"len",
"(",
"item",
".",
"keys",
"(",
")",
")",
"invalid_item",
"=",
"any",
"(",
"[",
"None",
"in",
"item",
".",
"keys",
"(",
")",
",",
"None",
"in",
"item",
".",
"values",
"(",
")",
",",
"''",
"in",
"item",
".",
"keys",
"(",
")",
",",
"''",
"in",
"item",
".",
"values",
"(",
")",
",",
"len_keys",
"!=",
"len",
"(",
"item",
".",
"keys",
"(",
")",
")",
"]",
")",
"if",
"invalid_item",
":",
"raise",
"KeyError",
"(",
"'Dados inválidos nesse item:',",
" ",
"tem)",
""
] | [
15,
0
] | [
39,
64
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Interface.get_switch_interface_from_host_interface | (self, protegida=None) | return interface | A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH.
@param protegida: Indicação do campo 'protegida' da interface do switch
@return: Interface ligada a um equipamento do tipo SWITCH.
@raise InterfaceError: Falha ao pesquisar a interface do switch
@raise InterfaceNotFoundError: Interface do switch não encontrada.
@raise InterfaceProtectedError: A interface do switch está com o campo protegida diferente do parâmetr
| A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH.
| def get_switch_interface_from_host_interface(self, protegida=None):
"""A partir da ligacao_front da interface local busca uma interface ligada a um equipamento do tipo SWITCH.
@param protegida: Indicação do campo 'protegida' da interface do switch
@return: Interface ligada a um equipamento do tipo SWITCH.
@raise InterfaceError: Falha ao pesquisar a interface do switch
@raise InterfaceNotFoundError: Interface do switch não encontrada.
@raise InterfaceProtectedError: A interface do switch está com o campo protegida diferente do parâmetr
"""
interface_ids = []
from_interface = self
interface = self.ligacao_front
try:
while (interface is not None) and (
interface.equipamento.tipo_equipamento_id != TipoEquipamento.TIPO_EQUIPAMENTO_SWITCH):
interface_ids.append(interface.id)
if (interface.ligacao_back is not None) and (from_interface.id != interface.ligacao_back_id):
from_interface = interface
interface = interface.ligacao_back
elif (interface.ligacao_front is not None) and (from_interface.id != interface.ligacao_front_id):
from_interface = interface
interface = interface.ligacao_front
else:
interface = None
if interface is not None:
if interface.id in interface_ids:
raise InterfaceNotFoundError(
None,
u'Interface do tipo switch não encontrada a partir do front da interface %d.' % self.id)
except InterfaceNotFoundError, e:
raise e
except Exception, e:
self.log.error(u'Falha ao pesquisar a interface do switch.')
raise InterfaceError(
e, u'Falha ao pesquisar a interface do switch.')
if (interface is None):
raise InterfaceNotFoundError(
None, u'Interface do tipo switch não encontrada a partir do front da interface %d.' % self.id)
if ((protegida is not None) and (interface.protegida != protegida)):
raise InterfaceProtectedError(
None, u'Interface do switch com o campo protegida diferente de %s.' % protegida)
return interface | [
"def",
"get_switch_interface_from_host_interface",
"(",
"self",
",",
"protegida",
"=",
"None",
")",
":",
"interface_ids",
"=",
"[",
"]",
"from_interface",
"=",
"self",
"interface",
"=",
"self",
".",
"ligacao_front",
"try",
":",
"while",
"(",
"interface",
"is",
"not",
"None",
")",
"and",
"(",
"interface",
".",
"equipamento",
".",
"tipo_equipamento_id",
"!=",
"TipoEquipamento",
".",
"TIPO_EQUIPAMENTO_SWITCH",
")",
":",
"interface_ids",
".",
"append",
"(",
"interface",
".",
"id",
")",
"if",
"(",
"interface",
".",
"ligacao_back",
"is",
"not",
"None",
")",
"and",
"(",
"from_interface",
".",
"id",
"!=",
"interface",
".",
"ligacao_back_id",
")",
":",
"from_interface",
"=",
"interface",
"interface",
"=",
"interface",
".",
"ligacao_back",
"elif",
"(",
"interface",
".",
"ligacao_front",
"is",
"not",
"None",
")",
"and",
"(",
"from_interface",
".",
"id",
"!=",
"interface",
".",
"ligacao_front_id",
")",
":",
"from_interface",
"=",
"interface",
"interface",
"=",
"interface",
".",
"ligacao_front",
"else",
":",
"interface",
"=",
"None",
"if",
"interface",
"is",
"not",
"None",
":",
"if",
"interface",
".",
"id",
"in",
"interface_ids",
":",
"raise",
"InterfaceNotFoundError",
"(",
"None",
",",
"u'Interface do tipo switch não encontrada a partir do front da interface %d.' ",
" ",
"elf.",
"i",
"d)",
"",
"except",
"InterfaceNotFoundError",
",",
"e",
":",
"raise",
"e",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Falha ao pesquisar a interface do switch.'",
")",
"raise",
"InterfaceError",
"(",
"e",
",",
"u'Falha ao pesquisar a interface do switch.'",
")",
"if",
"(",
"interface",
"is",
"None",
")",
":",
"raise",
"InterfaceNotFoundError",
"(",
"None",
",",
"u'Interface do tipo switch não encontrada a partir do front da interface %d.' ",
" ",
"elf.",
"i",
"d)",
"",
"if",
"(",
"(",
"protegida",
"is",
"not",
"None",
")",
"and",
"(",
"interface",
".",
"protegida",
"!=",
"protegida",
")",
")",
":",
"raise",
"InterfaceProtectedError",
"(",
"None",
",",
"u'Interface do switch com o campo protegida diferente de %s.'",
"%",
"protegida",
")",
"return",
"interface"
] | [
440,
4
] | [
485,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Cadastral.download_inf_cadastral | (self) | Download do arquivo cadastral. | Download do arquivo cadastral. | def download_inf_cadastral(self):
"""Download do arquivo cadastral."""
file_name = "cad_fi.csv"
url = "{}/{}".format(URL_CADASTRAL_DIARIO, file_name)
local_file = "{}/{}".format(CSV_FILES_DIR, file_name)
if os.path.exists(local_file):
log.debug("Arquivo cadastral '%s' ja existe localmente", file_name)
self.filename = local_file
else:
log.debug("Tentando baixar arquivo: %s", url)
res = download_file(url, local_file)
if res.status_code == 404:
log.debug("Arquivo nao encontrado no site da cvm")
msg(
"red",
"Erro: Arquivo cadastral encontrado no site da CVM. {}".format(url),
1,
)
elif res.status_code == 200:
log.debug("Arquivo baixado com sucesso: %s", file_name)
self.filename = local_file | [
"def",
"download_inf_cadastral",
"(",
"self",
")",
":",
"file_name",
"=",
"\"cad_fi.csv\"",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"URL_CADASTRAL_DIARIO",
",",
"file_name",
")",
"local_file",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"CSV_FILES_DIR",
",",
"file_name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"local_file",
")",
":",
"log",
".",
"debug",
"(",
"\"Arquivo cadastral '%s' ja existe localmente\"",
",",
"file_name",
")",
"self",
".",
"filename",
"=",
"local_file",
"else",
":",
"log",
".",
"debug",
"(",
"\"Tentando baixar arquivo: %s\"",
",",
"url",
")",
"res",
"=",
"download_file",
"(",
"url",
",",
"local_file",
")",
"if",
"res",
".",
"status_code",
"==",
"404",
":",
"log",
".",
"debug",
"(",
"\"Arquivo nao encontrado no site da cvm\"",
")",
"msg",
"(",
"\"red\"",
",",
"\"Erro: Arquivo cadastral encontrado no site da CVM. {}\"",
".",
"format",
"(",
"url",
")",
",",
"1",
",",
")",
"elif",
"res",
".",
"status_code",
"==",
"200",
":",
"log",
".",
"debug",
"(",
"\"Arquivo baixado com sucesso: %s\"",
",",
"file_name",
")",
"self",
".",
"filename",
"=",
"local_file"
] | [
201,
4
] | [
222,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
linha.__ne__ | (self, outro) | return (self.cru != outro and self.ln != outro) or outro == None | Compara o .recuo e a .ln, se o outro objeto também for uma linha, se for instância de outra classe (diferente de None), verifica se .ln ou .cru se diferenciam a ele | Compara o .recuo e a .ln, se o outro objeto também for uma linha, se for instância de outra classe (diferente de None), verifica se .ln ou .cru se diferenciam a ele | def __ne__ (self, outro):
'''Compara o .recuo e a .ln, se o outro objeto também for uma linha, se for instância de outra classe (diferente de None), verifica se .ln ou .cru se diferenciam a ele'''
if self.__class__ == outro.__class__:
return self.recuo != outro.recuo or self.ln != outro.ln
return (self.cru != outro and self.ln != outro) or outro == None | [
"def",
"__ne__",
"(",
"self",
",",
"outro",
")",
":",
"if",
"self",
".",
"__class__",
"==",
"outro",
".",
"__class__",
":",
"return",
"self",
".",
"recuo",
"!=",
"outro",
".",
"recuo",
"or",
"self",
".",
"ln",
"!=",
"outro",
".",
"ln",
"return",
"(",
"self",
".",
"cru",
"!=",
"outro",
"and",
"self",
".",
"ln",
"!=",
"outro",
")",
"or",
"outro",
"==",
"None"
] | [
386,
1
] | [
390,
66
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Tun.__init__ | (self, name, ip, dstip, ** args) | Define uma interface tun, mas ainda não a cria. Os parâmetros de configuraçao dessa interface devem ser informados nos argumentos:
name: nome da interface tun
ip: endereço IPv4 desta interface
dstip: endereço IPv4 da outra ponta do enlace
args: "key arguments" opcionais
mask=máscara de rede (str)
mtu=MTU (int)
qlen=comprimento da fila de saída (int)
| Define uma interface tun, mas ainda não a cria. Os parâmetros de configuraçao dessa interface devem ser informados nos argumentos:
name: nome da interface tun
ip: endereço IPv4 desta interface
dstip: endereço IPv4 da outra ponta do enlace
args: "key arguments" opcionais
mask=máscara de rede (str)
mtu=MTU (int)
qlen=comprimento da fila de saída (int)
| def __init__(self, name, ip, dstip, ** args):
'''Define uma interface tun, mas ainda não a cria. Os parâmetros de configuraçao dessa interface devem ser informados nos argumentos:
name: nome da interface tun
ip: endereço IPv4 desta interface
dstip: endereço IPv4 da outra ponta do enlace
args: "key arguments" opcionais
mask=máscara de rede (str)
mtu=MTU (int)
qlen=comprimento da fila de saída (int)
'''
self.name = name.encode('ascii')
self.ip = IP(ip)
self.dstip = IP(dstip)
self.mask = IP(self._getarg('mask', args))
self.mtu = self._getarg('mtu', args)
self.qlen = self._getarg('qlen', args)
self.fd = -1 | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"ip",
",",
"dstip",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"name",
"=",
"name",
".",
"encode",
"(",
"'ascii'",
")",
"self",
".",
"ip",
"=",
"IP",
"(",
"ip",
")",
"self",
".",
"dstip",
"=",
"IP",
"(",
"dstip",
")",
"self",
".",
"mask",
"=",
"IP",
"(",
"self",
".",
"_getarg",
"(",
"'mask'",
",",
"args",
")",
")",
"self",
".",
"mtu",
"=",
"self",
".",
"_getarg",
"(",
"'mtu'",
",",
"args",
")",
"self",
".",
"qlen",
"=",
"self",
".",
"_getarg",
"(",
"'qlen'",
",",
"args",
")",
"self",
".",
"fd",
"=",
"-",
"1"
] | [
35,
4
] | [
51,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.