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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DTAgentProgram | (belief_state) | return program | Agente de decisão teórica | Agente de decisão teórica | def DTAgentProgram(belief_state):
"Agente de decisão teórica"
def program(percept):
belief_state.observe(program.action, percept)
program.action = argmax(
belief_state.actions(), key=belief_state.expected_outcome_utility
)
return program.action
program.action = None
return program | [
"def",
"DTAgentProgram",
"(",
"belief_state",
")",
":",
"def",
"program",
"(",
"percept",
")",
":",
"belief_state",
".",
"observe",
"(",
"program",
".",
"action",
",",
"percept",
")",
"program",
".",
"action",
"=",
"argmax",
"(",
"belief_state",
".",
"actions",
"(",
")",
",",
"key",
"=",
"belief_state",
".",
"expected_outcome_utility",
")",
"return",
"program",
".",
"action",
"program",
".",
"action",
"=",
"None",
"return",
"program"
] | [
25,
0
] | [
36,
18
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
to_cnf | (s) | return distribute_and_over_or(s) | Converte uma sentença lógica proposicional em forma conjuntiva normal.
Ou seja, para a forma: ((A | ~B | ...) & (B | C | ...) & ...)
>>> to_cnf('~(B | C)')
(~B & ~C)
| Converte uma sentença lógica proposicional em forma conjuntiva normal.
Ou seja, para a forma: ((A | ~B | ...) & (B | C | ...) & ...)
>>> to_cnf('~(B | C)')
(~B & ~C)
| def to_cnf(s):
"""Converte uma sentença lógica proposicional em forma conjuntiva normal.
Ou seja, para a forma: ((A | ~B | ...) & (B | C | ...) & ...)
>>> to_cnf('~(B | C)')
(~B & ~C)
"""
s = expr(s)
if isinstance(s, str):
s = expr(s)
s = eliminate_implications(s)
s = move_not_inwards(s)
return distribute_and_over_or(s) | [
"def",
"to_cnf",
"(",
"s",
")",
":",
"s",
"=",
"expr",
"(",
"s",
")",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"expr",
"(",
"s",
")",
"s",
"=",
"eliminate_implications",
"(",
"s",
")",
"s",
"=",
"move_not_inwards",
"(",
"s",
")",
"return",
"distribute_and_over_or",
"(",
"s",
")"
] | [
273,
0
] | [
284,
36
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Room.is_dangerous | (self, danger=None) | Retorna True se a sala pode conter o Wumpus ou um poço. | Retorna True se a sala pode conter o Wumpus ou um poço. | def is_dangerous(self, danger=None):
"""Retorna True se a sala pode conter o Wumpus ou um poço."""
if danger is None:
return self.wumpus == Status.LikelyPresent or self.pit == Status.LikelyPresent
if danger == Entity.Wumpus:
return self.wumpus == Status.LikelyPresent
if danger == Entity.Pit:
return self.pit == Status.LikelyPresent
raise ValueError | [
"def",
"is_dangerous",
"(",
"self",
",",
"danger",
"=",
"None",
")",
":",
"if",
"danger",
"is",
"None",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"LikelyPresent",
"or",
"self",
".",
"pit",
"==",
"Status",
".",
"LikelyPresent",
"if",
"danger",
"==",
"Entity",
".",
"Wumpus",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"LikelyPresent",
"if",
"danger",
"==",
"Entity",
".",
"Pit",
":",
"return",
"self",
".",
"pit",
"==",
"Status",
".",
"LikelyPresent",
"raise",
"ValueError"
] | [
53,
2
] | [
63,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Room.is_safe | (self, danger=None) | Retorna True se a sala não contém nem o Wumpus nem um poço. | Retorna True se a sala não contém nem o Wumpus nem um poço. | def is_safe(self, danger=None):
"""Retorna True se a sala não contém nem o Wumpus nem um poço."""
if danger is None:
return self.wumpus == Status.Absent and self.pit == Status.Absent
if danger == Entity.Wumpus:
return self.wumpus == Status.Absent
if danger == Entity.Pit:
return self.pit == Status.Absent
raise ValueError | [
"def",
"is_safe",
"(",
"self",
",",
"danger",
"=",
"None",
")",
":",
"if",
"danger",
"is",
"None",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"Absent",
"and",
"self",
".",
"pit",
"==",
"Status",
".",
"Absent",
"if",
"danger",
"==",
"Entity",
".",
"Wumpus",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"Absent",
"if",
"danger",
"==",
"Entity",
".",
"Pit",
":",
"return",
"self",
".",
"pit",
"==",
"Status",
".",
"Absent",
"raise",
"ValueError"
] | [
33,
2
] | [
43,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ship.blitme | (self) | Desenha a espaconave em sua posicao actual | Desenha a espaconave em sua posicao actual | def blitme(self):
"""Desenha a espaconave em sua posicao actual"""
self.screen.blit(self.image, self.rect) | [
"def",
"blitme",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"image",
",",
"self",
".",
"rect",
")"
] | [
41,
4
] | [
43,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ship.blitme | (self) | DESENHA A ESPAÇONAVE EM SUA POSIÇÃO ATUAL | DESENHA A ESPAÇONAVE EM SUA POSIÇÃO ATUAL | def blitme(self):
'''DESENHA A ESPAÇONAVE EM SUA POSIÇÃO ATUAL'''
self.screen.blit(self.image,self.rect) | [
"def",
"blitme",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"image",
",",
"self",
".",
"rect",
")"
] | [
36,
4
] | [
38,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
imprime_nf | (nota_fiscal: Any) | Imprime NF assim que uma NF é criada. Padrão observadores aplicado.
Args:
nota_fiscal.py (class Nota_fiscal): Cria Nota fiscal
| Imprime NF assim que uma NF é criada. Padrão observadores aplicado. | def imprime_nf(nota_fiscal: Any):
"""Imprime NF assim que uma NF é criada. Padrão observadores aplicado.
Args:
nota_fiscal.py (class Nota_fiscal): Cria Nota fiscal
"""
print(f'\nImprimindo nota fiscal {nota_fiscal.cnpj}.') | [
"def",
"imprime_nf",
"(",
"nota_fiscal",
":",
"Any",
")",
":",
"print",
"(",
"f'\\nImprimindo nota fiscal {nota_fiscal.cnpj}.'",
")"
] | [
23,
0
] | [
29,
58
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
kill_proc | () | Mata o processo ativo (em destaque na interface).
Exceptions:
NoSuchProcess: quando o processo referente ao pid não é
encontrado. | Mata o processo ativo (em destaque na interface). | def kill_proc():
""" Mata 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.terminate() | [
"def",
"kill_proc",
"(",
")",
":",
"pid",
"=",
"get_current_process",
"(",
")",
"p",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"p",
".",
"terminate",
"(",
")"
] | [
53,
0
] | [
62,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
extract_reference_order | (text: str) | return "" | Retorna o número indicativo de ordem a partir do texto da
referência.
Exemplo:
>>> text = "2. Referência X"
>>> number = extract_reference_order(text)
>>> number
>>> 2
| Retorna o número indicativo de ordem a partir do texto da
referência. | def extract_reference_order(text: str) -> str:
"""Retorna o número indicativo de ordem a partir do texto da
referência.
Exemplo:
>>> text = "2. Referência X"
>>> number = extract_reference_order(text)
>>> number
>>> 2
"""
for regex in NUMBER_REGEXS:
match = regex.match(text)
if match:
return match.group(1)
return "" | [
"def",
"extract_reference_order",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"for",
"regex",
"in",
"NUMBER_REGEXS",
":",
"match",
"=",
"regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")",
"return",
"\"\""
] | [
213,
0
] | [
229,
13
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Restaurant.__init__ | (self, name, cuisine) | Inicializa os atributos name e cuisine. | Inicializa os atributos name e cuisine. | def __init__(self, name, cuisine):
"""Inicializa os atributos name e cuisine."""
self.name = name
self.cuisine = cuisine
self.number_served = 0 | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"cuisine",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"cuisine",
"=",
"cuisine",
"self",
".",
"number_served",
"=",
"0"
] | [
11,
4
] | [
15,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
uploadchamado | (request) | return render(request, "uploadchamado.html", context) | Essa função carrega o arquivo do cliente
É chamada pelo cliente(específico) enviar o arquivo/chamado para o funcionário | Essa função carrega o arquivo do cliente
É chamada pelo cliente(específico) enviar o arquivo/chamado para o funcionário | def uploadchamado(request):
"""Essa função carrega o arquivo do cliente
É chamada pelo cliente(específico) enviar o arquivo/chamado para o funcionário"""
context = {}
if request.method == "POST":
uploaded_file = request.FILES["document"]
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
context["url"] = fs.url(name)
return render(request, "uploadchamado.html", context) | [
"def",
"uploadchamado",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"uploaded_file",
"=",
"request",
".",
"FILES",
"[",
"\"document\"",
"]",
"fs",
"=",
"FileSystemStorage",
"(",
")",
"name",
"=",
"fs",
".",
"save",
"(",
"uploaded_file",
".",
"name",
",",
"uploaded_file",
")",
"context",
"[",
"\"url\"",
"]",
"=",
"fs",
".",
"url",
"(",
"name",
")",
"return",
"render",
"(",
"request",
",",
"\"uploadchamado.html\"",
",",
"context",
")"
] | [
641,
0
] | [
651,
57
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Banco.persist | (self) | return False | Confirma a execução atual, gravando no banco de dados | Confirma a execução atual, gravando no banco de dados | def persist(self):
""" Confirma a execução atual, gravando no banco de dados """
if self.connected:
self.conn.commit()
return True
return False | [
"def",
"persist",
"(",
"self",
")",
":",
"if",
"self",
".",
"connected",
":",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"True",
"return",
"False"
] | [
37,
4
] | [
42,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Genetic.run | (self, func, DEBUG=None, **kwargs) | return self.results | Execute uma execução de otimização completa.
Faz a otimização com a execução da atualização das velocidades
e as coordenadas também verifica o critério interrompido para encontrar fitnnes.
Parameters
----------
func : callable
Function that calculates fitnnes.
Returns
-------
The dictionary that stores the optimization results.
| Execute uma execução de otimização completa. | def run(self, func, DEBUG=None, **kwargs):
"""Execute uma execução de otimização completa.
Faz a otimização com a execução da atualização das velocidades
e as coordenadas também verifica o critério interrompido para encontrar fitnnes.
Parameters
----------
func : callable
Function that calculates fitnnes.
Returns
-------
The dictionary that stores the optimization results.
"""
self.func = func
while (self.step_number < self.maxiter and self.improving):
self.do_full_step(func, **kwargs)
fitness_evaluation= self.fitness
self.calculate_best_fitness()
#self.fitness_variation(fitness_evaluation)
if DEBUG is not None:
with open(DEBUG, 'a') as dbg_file:
print(f"# {self.step_number} {self.fitness}")
print(f" {self.step_number} {self.fitness}",
file=dbg_file)
#np.savetxt(dbg_file,
# [(*p.chromosome, p.fitness)
# for p in self.population])
if self.fitness >= self.goal:
break
self.results = {}
self.results['fitness'] = self.fitness
return self.results | [
"def",
"run",
"(",
"self",
",",
"func",
",",
"DEBUG",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"func",
"=",
"func",
"while",
"(",
"self",
".",
"step_number",
"<",
"self",
".",
"maxiter",
"and",
"self",
".",
"improving",
")",
":",
"self",
".",
"do_full_step",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"fitness_evaluation",
"=",
"self",
".",
"fitness",
"self",
".",
"calculate_best_fitness",
"(",
")",
"#self.fitness_variation(fitness_evaluation)",
"if",
"DEBUG",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"DEBUG",
",",
"'a'",
")",
"as",
"dbg_file",
":",
"print",
"(",
"f\"# {self.step_number} {self.fitness}\"",
")",
"print",
"(",
"f\" {self.step_number} {self.fitness}\"",
",",
"file",
"=",
"dbg_file",
")",
"#np.savetxt(dbg_file,",
"# [(*p.chromosome, p.fitness)",
"# for p in self.population])",
"if",
"self",
".",
"fitness",
">=",
"self",
".",
"goal",
":",
"break",
"self",
".",
"results",
"=",
"{",
"}",
"self",
".",
"results",
"[",
"'fitness'",
"]",
"=",
"self",
".",
"fitness",
"return",
"self",
".",
"results"
] | [
583,
4
] | [
616,
27
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
reg2 | (y, x, name) | return res | Função que roda as regressões
Entre com x e y | Função que roda as regressões
Entre com x e y | def reg2(y, x, name):
""" Função que roda as regressões
Entre com x e y"""
x = sm.add_constant(x)
res = sm.OLS(y, x).fit()
sns.distplot(res.resid)
plt.title(name)
plt.show()
return res | [
"def",
"reg2",
"(",
"y",
",",
"x",
",",
"name",
")",
":",
"x",
"=",
"sm",
".",
"add_constant",
"(",
"x",
")",
"res",
"=",
"sm",
".",
"OLS",
"(",
"y",
",",
"x",
")",
".",
"fit",
"(",
")",
"sns",
".",
"distplot",
"(",
"res",
".",
"resid",
")",
"plt",
".",
"title",
"(",
"name",
")",
"plt",
".",
"show",
"(",
")",
"return",
"res"
] | [
45,
0
] | [
53,
14
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
get_city_council_updates | (formatted_date) | return response | Solicita atualizações ao webservice da Câmara. | Solicita atualizações ao webservice da Câmara. | def get_city_council_updates(formatted_date):
"""Solicita atualizações ao webservice da Câmara."""
target_date = datetime.strptime(formatted_date, "%Y-%m-%d").date()
sync_info, _ = SyncInformation.objects.get_or_create(
date=target_date, source="camara", defaults={"succeed": False}
)
response = requests.get(
settings.CITY_COUNCIL_WEBSERVICE_ENDPOINT,
params={
"data": formatted_date, # formato aaaa-mm-dd
"token": settings.CITY_COUNCIL_WEBSERVICE_TOKEN,
},
headers={"User-Agent": "Maria Quitéria"},
)
try:
response.raise_for_status()
sync_info.succeed = True
except HTTPError:
sync_info.succeed = False
sync_info.save()
raise HTTPError
response = response.json()
sync_info.response = response
if response.get("erro"):
sync_info.succeed = False
sync_info.save()
raise WebserviceException(response["erro"])
sync_info.save()
return response | [
"def",
"get_city_council_updates",
"(",
"formatted_date",
")",
":",
"target_date",
"=",
"datetime",
".",
"strptime",
"(",
"formatted_date",
",",
"\"%Y-%m-%d\"",
")",
".",
"date",
"(",
")",
"sync_info",
",",
"_",
"=",
"SyncInformation",
".",
"objects",
".",
"get_or_create",
"(",
"date",
"=",
"target_date",
",",
"source",
"=",
"\"camara\"",
",",
"defaults",
"=",
"{",
"\"succeed\"",
":",
"False",
"}",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"settings",
".",
"CITY_COUNCIL_WEBSERVICE_ENDPOINT",
",",
"params",
"=",
"{",
"\"data\"",
":",
"formatted_date",
",",
"# formato aaaa-mm-dd",
"\"token\"",
":",
"settings",
".",
"CITY_COUNCIL_WEBSERVICE_TOKEN",
",",
"}",
",",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"\"Maria Quitéria\"}",
",",
"",
")",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"sync_info",
".",
"succeed",
"=",
"True",
"except",
"HTTPError",
":",
"sync_info",
".",
"succeed",
"=",
"False",
"sync_info",
".",
"save",
"(",
")",
"raise",
"HTTPError",
"response",
"=",
"response",
".",
"json",
"(",
")",
"sync_info",
".",
"response",
"=",
"response",
"if",
"response",
".",
"get",
"(",
"\"erro\"",
")",
":",
"sync_info",
".",
"succeed",
"=",
"False",
"sync_info",
".",
"save",
"(",
")",
"raise",
"WebserviceException",
"(",
"response",
"[",
"\"erro\"",
"]",
")",
"sync_info",
".",
"save",
"(",
")",
"return",
"response"
] | [
90,
0
] | [
122,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Privileges.__init__ | (self, privileges='You are Admin and can add post, delete post and ban user') | Inicializa os atributos dos usuários administradores. | Inicializa os atributos dos usuários administradores. | def __init__(self, privileges='You are Admin and can add post, delete post and ban user'):
"""Inicializa os atributos dos usuários administradores."""
self.privileges = privileges | [
"def",
"__init__",
"(",
"self",
",",
"privileges",
"=",
"'You are Admin and can add post, delete post and ban user'",
")",
":",
"self",
".",
"privileges",
"=",
"privileges"
] | [
35,
4
] | [
37,
36
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
view | (tabela) | return rows | Função que recebe por parâmetro o nome da tabela
a ser consultada e retorna todas as linhas encontradas | Função que recebe por parâmetro o nome da tabela
a ser consultada e retorna todas as linhas encontradas | def view(tabela):
""" Função que recebe por parâmetro o nome da tabela
a ser consultada e retorna todas as linhas encontradas """
banco = Banco()
banco.connect()
banco.execute(f'SELECT * FROM {tabela}')
rows = banco.fetchall()
banco.disconnect()
return rows | [
"def",
"view",
"(",
"tabela",
")",
":",
"banco",
"=",
"Banco",
"(",
")",
"banco",
".",
"connect",
"(",
")",
"banco",
".",
"execute",
"(",
"f'SELECT * FROM {tabela}'",
")",
"rows",
"=",
"banco",
".",
"fetchall",
"(",
")",
"banco",
".",
"disconnect",
"(",
")",
"return",
"rows"
] | [
127,
0
] | [
135,
15
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Stack.pop | (self) | return self.__stack.pop() | Remove o último valor da pilha | Remove o último valor da pilha | def pop(self):
""" Remove o último valor da pilha """
return self.__stack.pop() | [
"def",
"pop",
"(",
"self",
")",
":",
"return",
"self",
".",
"__stack",
".",
"pop",
"(",
")"
] | [
17,
4
] | [
19,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
PackPOOII.subString | (self, palavra) | return total | Procura uma sub-string dentro de uma determinada string
Parametros
----------
palavra : str
Endereço da string
| Procura uma sub-string dentro de uma determinada string | def subString(self, palavra):
""" Procura uma sub-string dentro de uma determinada string
Parametros
----------
palavra : str
Endereço da string
"""
total = 0
for letras in range(len(palavra)):
if(palavra[letras: letras+6] == "banana"):
total += 1
return total | [
"def",
"subString",
"(",
"self",
",",
"palavra",
")",
":",
"total",
"=",
"0",
"for",
"letras",
"in",
"range",
"(",
"len",
"(",
"palavra",
")",
")",
":",
"if",
"(",
"palavra",
"[",
"letras",
":",
"letras",
"+",
"6",
"]",
"==",
"\"banana\"",
")",
":",
"total",
"+=",
"1",
"return",
"total"
] | [
9,
4
] | [
22,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
closure | (func) | return inner | A função (func) está no escopo da closure. | A função (func) está no escopo da closure. | def closure(func):
"""A função (func) está no escopo da closure."""
def inner(*args):
"""Os argumentos estão no escopo de inner."""
return print(func(*args))
return inner | [
"def",
"closure",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
")",
":",
"\"\"\"Os argumentos estão no escopo de inner.\"\"\"",
"return",
"print",
"(",
"func",
"(",
"*",
"args",
")",
")",
"return",
"inner"
] | [
5,
0
] | [
11,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
OverlapCommunity.escolha_semente | (self) | return semente | Escolhe a semente de uma lista predefinida | Escolhe a semente de uma lista predefinida | def escolha_semente(self):
"""Escolhe a semente de uma lista predefinida"""
semente = self.sementes_predefinidas[self.cont_semente]
self.cont_semente += 1
return semente | [
"def",
"escolha_semente",
"(",
"self",
")",
":",
"semente",
"=",
"self",
".",
"sementes_predefinidas",
"[",
"self",
".",
"cont_semente",
"]",
"self",
".",
"cont_semente",
"+=",
"1",
"return",
"semente"
] | [
75,
4
] | [
79,
22
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
CreateView.perform_create | (self, serializer) | Salva os dados do post e cria uma nova Sala. | Salva os dados do post e cria uma nova Sala. | def perform_create(self, serializer):
"""Salva os dados do post e cria uma nova Sala."""
serializer.save() | [
"def",
"perform_create",
"(",
"self",
",",
"serializer",
")",
":",
"serializer",
".",
"save",
"(",
")"
] | [
8,
4
] | [
10,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
test_fst_ap_transfer_session_no_params | (dev, apdev, test_params) | FST AP transfer session - no params | FST AP transfer session - no params | def test_fst_ap_transfer_session_no_params(dev, apdev, test_params):
"""FST AP transfer session - no params"""
fst_transfer_session(apdev, test_params,
bad_param_session_transfer_no_params, True) | [
"def",
"test_fst_ap_transfer_session_no_params",
"(",
"dev",
",",
"apdev",
",",
"test_params",
")",
":",
"fst_transfer_session",
"(",
"apdev",
",",
"test_params",
",",
"bad_param_session_transfer_no_params",
",",
"True",
")"
] | [
1304,
0
] | [
1307,
68
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Geladeira.tem_comida | (self, comida) | return comida.nome in self.alimentos.keys() | Verifica se a Comida está na geladeira. | Verifica se a Comida está na geladeira. | def tem_comida(self, comida):
"""Verifica se a Comida está na geladeira."""
return comida.nome in self.alimentos.keys() | [
"def",
"tem_comida",
"(",
"self",
",",
"comida",
")",
":",
"return",
"comida",
".",
"nome",
"in",
"self",
".",
"alimentos",
".",
"keys",
"(",
")"
] | [
42,
4
] | [
44,
51
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
primalidade | (num) | return True | Parâmetro: número inteiro positivo. Retorna True se primo. | Parâmetro: número inteiro positivo. Retorna True se primo. | def primalidade(num):
'''Parâmetro: número inteiro positivo. Retorna True se primo.'''
for i in range(2, num):
if num % i == 0:
return False
return True | [
"def",
"primalidade",
"(",
"num",
")",
":",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"num",
")",
":",
"if",
"num",
"%",
"i",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] | [
8,
0
] | [
13,
13
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Contrato.restaura_estado | (self, estado: Any) | Restaura um contrato com os dados do estado (class Estado()).
Args:
estado (class Estado): class Estado contendo historico de um
objeto Contrato()
| Restaura um contrato com os dados do estado (class Estado()). | def restaura_estado(self, estado: Any):
"""Restaura um contrato com os dados do estado (class Estado()).
Args:
estado (class Estado): class Estado contendo historico de um
objeto Contrato()
"""
self.__cliente = estado.contrato.cliente
self.__data = estado.contrato.data
self.__tipo = estado.contrato.tipo | [
"def",
"restaura_estado",
"(",
"self",
",",
"estado",
":",
"Any",
")",
":",
"self",
".",
"__cliente",
"=",
"estado",
".",
"contrato",
".",
"cliente",
"self",
".",
"__data",
"=",
"estado",
".",
"contrato",
".",
"data",
"self",
".",
"__tipo",
"=",
"estado",
".",
"contrato",
".",
"tipo"
] | [
65,
4
] | [
74,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Poller.adiciona | (self, cb) | Registra um callback | Registra um callback | def adiciona(self, cb):
'Registra um callback'
if cb.isTimer and not cb in self.cbs_to:
self.cbs_to.append(cb)
else:
self.cbs.add(cb) | [
"def",
"adiciona",
"(",
"self",
",",
"cb",
")",
":",
"if",
"cb",
".",
"isTimer",
"and",
"not",
"cb",
"in",
"self",
".",
"cbs_to",
":",
"self",
".",
"cbs_to",
".",
"append",
"(",
"cb",
")",
"else",
":",
"self",
".",
"cbs",
".",
"add",
"(",
"cb",
")"
] | [
104,
4
] | [
109,
28
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CreateView.perform_create | (self, serializer) | Salva os dados do post e cria uma nova Agenda. | Salva os dados do post e cria uma nova Agenda. | def perform_create(self, serializer):
"""Salva os dados do post e cria uma nova Agenda."""
serializer.save() | [
"def",
"perform_create",
"(",
"self",
",",
"serializer",
")",
":",
"serializer",
".",
"save",
"(",
")"
] | [
13,
4
] | [
15,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
RuspyTransformer.and_e | (self, x, y) | return self.eval(x) and self.eval(y) | Esta é a forma mais simples. Avaliamos explicitamente cada argumento. | Esta é a forma mais simples. Avaliamos explicitamente cada argumento. | def and_e(self, x, y):
"""Esta é a forma mais simples. Avaliamos explicitamente cada argumento."""
"""Note que "x and y" em Python avalia x e somente avalia y caso o primeiro"""
"""argumento seja verdadeiro. Este é exatamente o comportamento desejado."""
return self.eval(x) and self.eval(y) | [
"def",
"and_e",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"\"\"\"Note que \"x and y\" em Python avalia x e somente avalia y caso o primeiro\"\"\"",
"\"\"\"argumento seja verdadeiro. Este é exatamente o comportamento desejado.\"\"\"",
"return",
"self",
".",
"eval",
"(",
"x",
")",
"and",
"self",
".",
"eval",
"(",
"y",
")"
] | [
116,
4
] | [
120,
44
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
data_iter | (batch_size, features, labels) | Funcao que gerar os minibatch, para utilizar no gradient descente, nao precisamos rodar o conjunto todo a cada iteracao | Funcao que gerar os minibatch, para utilizar no gradient descente, nao precisamos rodar o conjunto todo a cada iteracao | def data_iter(batch_size, features, labels):
"""Funcao que gerar os minibatch, para utilizar no gradient descente, nao precisamos rodar o conjunto todo a cada iteracao"""
num_examples = len(features)
indices = list(range(num_examples))
# The examples are read at random, in no particular order
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(indices[i: min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices] | [
"def",
"data_iter",
"(",
"batch_size",
",",
"features",
",",
"labels",
")",
":",
"num_examples",
"=",
"len",
"(",
"features",
")",
"indices",
"=",
"list",
"(",
"range",
"(",
"num_examples",
")",
")",
"# The examples are read at random, in no particular order",
"random",
".",
"shuffle",
"(",
"indices",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_examples",
",",
"batch_size",
")",
":",
"batch_indices",
"=",
"torch",
".",
"tensor",
"(",
"indices",
"[",
"i",
":",
"min",
"(",
"i",
"+",
"batch_size",
",",
"num_examples",
")",
"]",
")",
"yield",
"features",
"[",
"batch_indices",
"]",
",",
"labels",
"[",
"batch_indices",
"]"
] | [
112,
0
] | [
120,
60
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
criar_senha_sha256 | (senha: str, token: str = 'AmueDFGuyVsce8524') | return hashlib.sha256(str.encode(token+senha)).hexdigest() | Transforma senha em uma hash sha256.
Args:
senha (str utf-8): Senha string utf-8 que será transformada em hash
sha256.
token (str, optional): Token que será agregado a sua senha. Defaults
to 'AmueDFGuyVsce8524'.
Returns:
str: senha codificada em hash sha256 hexadecimal.
| Transforma senha em uma hash sha256. | def criar_senha_sha256(senha: str, token: str = 'AmueDFGuyVsce8524') -> str:
"""Transforma senha em uma hash sha256.
Args:
senha (str utf-8): Senha string utf-8 que será transformada em hash
sha256.
token (str, optional): Token que será agregado a sua senha. Defaults
to 'AmueDFGuyVsce8524'.
Returns:
str: senha codificada em hash sha256 hexadecimal.
"""
return hashlib.sha256(str.encode(token+senha)).hexdigest() | [
"def",
"criar_senha_sha256",
"(",
"senha",
":",
"str",
",",
"token",
":",
"str",
"=",
"'AmueDFGuyVsce8524'",
")",
"->",
"str",
":",
"return",
"hashlib",
".",
"sha256",
"(",
"str",
".",
"encode",
"(",
"token",
"+",
"senha",
")",
")",
".",
"hexdigest",
"(",
")"
] | [
3,
0
] | [
15,
62
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Environment.delete_thing | (self, thing) | Remove uma coisa no ambiente. | Remove uma coisa no ambiente. | def delete_thing(self, thing):
"""Remove uma coisa no ambiente."""
try:
self.things.remove(thing)
except ValueError as e:
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}" .format(thing, thing.location))
print(" from list: {}" .format([(thing, thing.location) for thing in self.things]))
if thing in self.agents:
self.agents.remove(thing) | [
"def",
"delete_thing",
"(",
"self",
",",
"thing",
")",
":",
"try",
":",
"self",
".",
"things",
".",
"remove",
"(",
"thing",
")",
"except",
"ValueError",
"as",
"e",
":",
"print",
"(",
"e",
")",
"print",
"(",
"\" in Environment delete_thing\"",
")",
"print",
"(",
"\" Thing to be removed: {} at {}\"",
".",
"format",
"(",
"thing",
",",
"thing",
".",
"location",
")",
")",
"print",
"(",
"\" from list: {}\"",
".",
"format",
"(",
"[",
"(",
"thing",
",",
"thing",
".",
"location",
")",
"for",
"thing",
"in",
"self",
".",
"things",
"]",
")",
")",
"if",
"thing",
"in",
"self",
".",
"agents",
":",
"self",
".",
"agents",
".",
"remove",
"(",
"thing",
")"
] | [
211,
4
] | [
221,
37
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
cmd_informes_fundo | (args) | Busa informes dos fundos. | Busa informes dos fundos. | def cmd_informes_fundo(args):
"""Busa informes dos fundos."""
range_datas = retorna_datas(args.datainicio, args.datafim)
# Mostra informacoes cadastral do fundo
inf_cadastral = Cadastral()
inf_cadastral.cria_df_cadastral()
try:
inf_cadastral.busca_fundo_cnpj(args.cnpj)
except KeyError:
msg("red", "Erro: Fundo com cnpj {} nao encontrado".format(args.cnpj), 1)
msg("cyan", "Denominacao Social: ", end="")
msg("nocolor", inf_cadastral.fundo_social_nome(args.cnpj))
msg("cyan", "Nome do Gestor: ", end="")
msg("nocolor", inf_cadastral.fundo_gestor_nome(args.cnpj))
msg("", "")
# Informes
informe = Informe()
for data in range_datas:
informe.download_informe_mensal(data)
# Carrega arquivo csv e cria o dataframe
if not informe.cria_df_informe(cnpj=args.cnpj):
msg("red", "Erro: cnpj '{}' nao encontrado".format(args.cnpj), 1)
print(informe.mostra_informe_fundo())
# Calculo do periodo (cota, saldo cotistas, etc)
msg("cyan", "Saldo no periodo")
for key, value in informe.calc_saldo_periodo().items():
msg("cyan", key, end=": ")
msg("nocolor", "{}".format(value))
# Rentabilidade mensal
if args.mensal:
msg("cyan", "Estatistica mensal:")
print(informe.calc_estatistica_mensal()) | [
"def",
"cmd_informes_fundo",
"(",
"args",
")",
":",
"range_datas",
"=",
"retorna_datas",
"(",
"args",
".",
"datainicio",
",",
"args",
".",
"datafim",
")",
"# Mostra informacoes cadastral do fundo",
"inf_cadastral",
"=",
"Cadastral",
"(",
")",
"inf_cadastral",
".",
"cria_df_cadastral",
"(",
")",
"try",
":",
"inf_cadastral",
".",
"busca_fundo_cnpj",
"(",
"args",
".",
"cnpj",
")",
"except",
"KeyError",
":",
"msg",
"(",
"\"red\"",
",",
"\"Erro: Fundo com cnpj {} nao encontrado\"",
".",
"format",
"(",
"args",
".",
"cnpj",
")",
",",
"1",
")",
"msg",
"(",
"\"cyan\"",
",",
"\"Denominacao Social: \"",
",",
"end",
"=",
"\"\"",
")",
"msg",
"(",
"\"nocolor\"",
",",
"inf_cadastral",
".",
"fundo_social_nome",
"(",
"args",
".",
"cnpj",
")",
")",
"msg",
"(",
"\"cyan\"",
",",
"\"Nome do Gestor: \"",
",",
"end",
"=",
"\"\"",
")",
"msg",
"(",
"\"nocolor\"",
",",
"inf_cadastral",
".",
"fundo_gestor_nome",
"(",
"args",
".",
"cnpj",
")",
")",
"msg",
"(",
"\"\"",
",",
"\"\"",
")",
"# Informes",
"informe",
"=",
"Informe",
"(",
")",
"for",
"data",
"in",
"range_datas",
":",
"informe",
".",
"download_informe_mensal",
"(",
"data",
")",
"# Carrega arquivo csv e cria o dataframe",
"if",
"not",
"informe",
".",
"cria_df_informe",
"(",
"cnpj",
"=",
"args",
".",
"cnpj",
")",
":",
"msg",
"(",
"\"red\"",
",",
"\"Erro: cnpj '{}' nao encontrado\"",
".",
"format",
"(",
"args",
".",
"cnpj",
")",
",",
"1",
")",
"print",
"(",
"informe",
".",
"mostra_informe_fundo",
"(",
")",
")",
"# Calculo do periodo (cota, saldo cotistas, etc)",
"msg",
"(",
"\"cyan\"",
",",
"\"Saldo no periodo\"",
")",
"for",
"key",
",",
"value",
"in",
"informe",
".",
"calc_saldo_periodo",
"(",
")",
".",
"items",
"(",
")",
":",
"msg",
"(",
"\"cyan\"",
",",
"key",
",",
"end",
"=",
"\": \"",
")",
"msg",
"(",
"\"nocolor\"",
",",
"\"{}\"",
".",
"format",
"(",
"value",
")",
")",
"# Rentabilidade mensal",
"if",
"args",
".",
"mensal",
":",
"msg",
"(",
"\"cyan\"",
",",
"\"Estatistica mensal:\"",
")",
"print",
"(",
"informe",
".",
"calc_estatistica_mensal",
"(",
")",
")"
] | [
776,
0
] | [
813,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
LinkedList.append | (self, element) | Insere um elemento no final da lista | Insere um elemento no final da lista | def append(self, element):
""" Insere um elemento no final da lista """
if self.head is not None:
pointer = self.head
while pointer.next is not None:
pointer = pointer.next
pointer.next = Node(element)
else:
self.head = Node(element) # primeiro elemento inserido na lista
self._size += 1 | [
"def",
"append",
"(",
"self",
",",
"element",
")",
":",
"if",
"self",
".",
"head",
"is",
"not",
"None",
":",
"pointer",
"=",
"self",
".",
"head",
"while",
"pointer",
".",
"next",
"is",
"not",
"None",
":",
"pointer",
"=",
"pointer",
".",
"next",
"pointer",
".",
"next",
"=",
"Node",
"(",
"element",
")",
"else",
":",
"self",
".",
"head",
"=",
"Node",
"(",
"element",
")",
"# primeiro elemento inserido na lista\r",
"self",
".",
"_size",
"+=",
"1"
] | [
19,
4
] | [
32,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
conversion_issues_to_kernel | (issues: List[Issue]) | return [xylose_converter.issue_to_kernel(issue) for issue in issues] | Converte uma lista de issues em formato xylose para uma lista
de issues em formato Kernel | Converte uma lista de issues em formato xylose para uma lista
de issues em formato Kernel | def conversion_issues_to_kernel(issues: List[Issue]) -> List[dict]:
"""Converte uma lista de issues em formato xylose para uma lista
de issues em formato Kernel"""
return [xylose_converter.issue_to_kernel(issue) for issue in issues] | [
"def",
"conversion_issues_to_kernel",
"(",
"issues",
":",
"List",
"[",
"Issue",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"return",
"[",
"xylose_converter",
".",
"issue_to_kernel",
"(",
"issue",
")",
"for",
"issue",
"in",
"issues",
"]"
] | [
168,
0
] | [
172,
72
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TestLambdas.test_lambda_anyany_and_splitabble_value | (self) | Teste da funcao any e any quando o valor tem espacos | Teste da funcao any e any quando o valor tem espacos | def test_lambda_anyany_and_splitabble_value(self):
"""Teste da funcao any e any quando o valor tem espacos"""
expected = (
"customFieldValues/any(x: x/items/any"
"(y: y/customFieldItem eq 'MGSSUSTR6-06R e MGSSUSTR6-06P'))"
)
result = AnyAny(
self.properties["customFieldValues"].items.customFieldItem
== "MGSSUSTR6-06R e MGSSUSTR6-06P"
)
self.assertEqual(result, expected) | [
"def",
"test_lambda_anyany_and_splitabble_value",
"(",
"self",
")",
":",
"expected",
"=",
"(",
"\"customFieldValues/any(x: x/items/any\"",
"\"(y: y/customFieldItem eq 'MGSSUSTR6-06R e MGSSUSTR6-06P'))\"",
")",
"result",
"=",
"AnyAny",
"(",
"self",
".",
"properties",
"[",
"\"customFieldValues\"",
"]",
".",
"items",
".",
"customFieldItem",
"==",
"\"MGSSUSTR6-06R e MGSSUSTR6-06P\"",
")",
"self",
".",
"assertEqual",
"(",
"result",
",",
"expected",
")"
] | [
51,
4
] | [
61,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EvaluateKruskalBased.vertices_from_chromosome | (self, chromosome) | return vertices | Identifica todos os vértices da solução candidata (terminais e não terminais)
| Identifica todos os vértices da solução candidata (terminais e não terminais)
| def vertices_from_chromosome(self, chromosome):
''' Identifica todos os vértices da solução candidata (terminais e não terminais)
'''
nro_vertices = self.STPG.nro_nodes
terminals = self.STPG.terminals
non_terminals = (v for v in range(1, nro_vertices+1) if v not in terminals)
vertices = set(v for v, g in zip(non_terminals, chromosome) if int(g)).union(terminals)
return vertices | [
"def",
"vertices_from_chromosome",
"(",
"self",
",",
"chromosome",
")",
":",
"nro_vertices",
"=",
"self",
".",
"STPG",
".",
"nro_nodes",
"terminals",
"=",
"self",
".",
"STPG",
".",
"terminals",
"non_terminals",
"=",
"(",
"v",
"for",
"v",
"in",
"range",
"(",
"1",
",",
"nro_vertices",
"+",
"1",
")",
"if",
"v",
"not",
"in",
"terminals",
")",
"vertices",
"=",
"set",
"(",
"v",
"for",
"v",
",",
"g",
"in",
"zip",
"(",
"non_terminals",
",",
"chromosome",
")",
"if",
"int",
"(",
"g",
")",
")",
".",
"union",
"(",
"terminals",
")",
"return",
"vertices"
] | [
15,
4
] | [
26,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Moderation.nick | (self, ctx, user: discord.Member, *, new_nick: str) | Altera o apelido de um usuário. | Altera o apelido de um usuário. | async def nick(self, ctx, user: discord.Member, *, new_nick: str):
"""Altera o apelido de um usuário."""
await user.edit(nick=new_nick)
await ctx.reply(f"Alterado nick de {user} para {new_nick}!") | [
"async",
"def",
"nick",
"(",
"self",
",",
"ctx",
",",
"user",
":",
"discord",
".",
"Member",
",",
"*",
",",
"new_nick",
":",
"str",
")",
":",
"await",
"user",
".",
"edit",
"(",
"nick",
"=",
"new_nick",
")",
"await",
"ctx",
".",
"reply",
"(",
"f\"Alterado nick de {user} para {new_nick}!\"",
")"
] | [
80,
4
] | [
84,
68
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Interface.search_interfaces | (self, from_interface) | return interfaces | Retorna a interface e as todas as interfaces ligadas no front ou no back da mesma.
Se a interface do front é a interface "from_interface" então deverá seguir a ligação pelo back,
caso contrário, deverá seguir pelo front.
A busca encerra quando não tem mais ligação ou quando encontra um "loop" por erro
na configuração do banco de dados.
@param from_interface: Interface de origem da consulta.
@return: Lista de interfaces.
@raise InterfaceError: Falha na consulta de interfaces.
| Retorna a interface e as todas as interfaces ligadas no front ou no back da mesma. | def search_interfaces(self, from_interface):
"""Retorna a interface e as todas as interfaces ligadas no front ou no back da mesma.
Se a interface do front é a interface "from_interface" então deverá seguir a ligação pelo back,
caso contrário, deverá seguir pelo front.
A busca encerra quando não tem mais ligação ou quando encontra um "loop" por erro
na configuração do banco de dados.
@param from_interface: Interface de origem da consulta.
@return: Lista de interfaces.
@raise InterfaceError: Falha na consulta de interfaces.
"""
interfaces = []
try:
interface = self
while (interface is not None):
interfaces.append(interface)
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) and (interface in interfaces):
break
except Exception, e:
self.log.error(
u'Falha ao pesquisar as interfaces de uma interface.')
raise InterfaceError(
e, u'Falha ao pesquisar as interfaces de uma interface.')
return interfaces | [
"def",
"search_interfaces",
"(",
"self",
",",
"from_interface",
")",
":",
"interfaces",
"=",
"[",
"]",
"try",
":",
"interface",
"=",
"self",
"while",
"(",
"interface",
"is",
"not",
"None",
")",
":",
"interfaces",
".",
"append",
"(",
"interface",
")",
"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",
")",
"and",
"(",
"interface",
"in",
"interfaces",
")",
":",
"break",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Falha ao pesquisar as interfaces de uma interface.'",
")",
"raise",
"InterfaceError",
"(",
"e",
",",
"u'Falha ao pesquisar as interfaces de uma interface.'",
")",
"return",
"interfaces"
] | [
265,
4
] | [
304,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Topicos.__iter__ | (self) | Modelo LDA para cada k. | Modelo LDA para cada k. | def __iter__(self):
"""Modelo LDA para cada k."""
for k in self.kas:
modelo = self.crear_modelo(k, [b.get("sparsed") for b in self.bags])
score = self.evaluar(modelo, [b.get("tokens") for b in self.bags])
logger.info(f"Modelo de {k} tópicos creado y evaluado.")
if score > self.score:
self.score = score
self.best = k
yield dict(k=k, modelo=modelo, score=score) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
".",
"kas",
":",
"modelo",
"=",
"self",
".",
"crear_modelo",
"(",
"k",
",",
"[",
"b",
".",
"get",
"(",
"\"sparsed\"",
")",
"for",
"b",
"in",
"self",
".",
"bags",
"]",
")",
"score",
"=",
"self",
".",
"evaluar",
"(",
"modelo",
",",
"[",
"b",
".",
"get",
"(",
"\"tokens\"",
")",
"for",
"b",
"in",
"self",
".",
"bags",
"]",
")",
"logger",
".",
"info",
"(",
"f\"Modelo de {k} tópicos creado y evaluado.\")",
"",
"if",
"score",
">",
"self",
".",
"score",
":",
"self",
".",
"score",
"=",
"score",
"self",
".",
"best",
"=",
"k",
"yield",
"dict",
"(",
"k",
"=",
"k",
",",
"modelo",
"=",
"modelo",
",",
"score",
"=",
"score",
")"
] | [
192,
4
] | [
204,
55
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ViewTestCase.test_api_can_create_a_agenda | (self) | Testando a criacao da agenda via post | Testando a criacao da agenda via post | def test_api_can_create_a_agenda(self):
"""Testando a criacao da agenda via post"""
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)
agenda = Agenda.objects.get()
self.assertEqual(agenda.sala, self.sala) | [
"def",
"test_api_can_create_a_agenda",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"response",
".",
"status_code",
",",
"status",
".",
"HTTP_201_CREATED",
")",
"agenda",
"=",
"Agenda",
".",
"objects",
".",
"get",
"(",
")",
"self",
".",
"assertEqual",
"(",
"agenda",
".",
"sala",
",",
"self",
".",
"sala",
")"
] | [
91,
4
] | [
95,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
tarefa | (request, idcampanha) | return JsonResponse({'ok': True}) | Importa uma lista de tarefas via POST | Importa uma lista de tarefas via POST | def tarefa(request, idcampanha):
"Importa uma lista de tarefas via POST"
tarefas = json.loads(request.body.decode('utf-8'))
campanha = get_object_or_404(Campanha, id=idcampanha)
Tarefa.importar_tarefas(campanha, tarefas)
return JsonResponse({'ok': True}) | [
"def",
"tarefa",
"(",
"request",
",",
"idcampanha",
")",
":",
"tarefas",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"campanha",
"=",
"get_object_or_404",
"(",
"Campanha",
",",
"id",
"=",
"idcampanha",
")",
"Tarefa",
".",
"importar_tarefas",
"(",
"campanha",
",",
"tarefas",
")",
"return",
"JsonResponse",
"(",
"{",
"'ok'",
":",
"True",
"}",
")"
] | [
11,
0
] | [
18,
37
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
AtorTestes.assert_nao_colisao | (self, ator, ator2) | Se certifica que não colisão entre dois atores | Se certifica que não colisão entre dois atores | def assert_nao_colisao(self, ator, ator2):
'Se certifica que não colisão entre dois atores'
tempo_da_colisao = 2
# Armazenando status antes da colisão
status_inicial_ator = ator.status(tempo_da_colisao)
status_inicial_ator_2 = ator2.status(tempo_da_colisao)
ator.colidir(ator2, tempo_da_colisao)
# Conferindo se status ficaram inalterados
self.assertEqual(status_inicial_ator, ator.status(tempo_da_colisao), 'Status de ator não deveria mudar')
self.assertEqual(status_inicial_ator_2, ator2.status(tempo_da_colisao), 'Status de ator2 não deveria mudar') | [
"def",
"assert_nao_colisao",
"(",
"self",
",",
"ator",
",",
"ator2",
")",
":",
"tempo_da_colisao",
"=",
"2",
"# Armazenando status antes da colisão",
"status_inicial_ator",
"=",
"ator",
".",
"status",
"(",
"tempo_da_colisao",
")",
"status_inicial_ator_2",
"=",
"ator2",
".",
"status",
"(",
"tempo_da_colisao",
")",
"ator",
".",
"colidir",
"(",
"ator2",
",",
"tempo_da_colisao",
")",
"# Conferindo se status ficaram inalterados",
"self",
".",
"assertEqual",
"(",
"status_inicial_ator",
",",
"ator",
".",
"status",
"(",
"tempo_da_colisao",
")",
",",
"'Status de ator não deveria mudar')",
"",
"self",
".",
"assertEqual",
"(",
"status_inicial_ator_2",
",",
"ator2",
".",
"status",
"(",
"tempo_da_colisao",
")",
",",
"'Status de ator2 não deveria mudar')",
""
] | [
124,
4
] | [
135,
117
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
linha.find | (self, *item) | Retorna o índice do item conforme .ln.index
Caso seja encontrado problema, retorna -1;
Caso não haja .index em .ln, retorna -2; | Retorna o índice do item conforme .ln.index
Caso seja encontrado problema, retorna -1;
Caso não haja .index em .ln, retorna -2; | def find (self, *item):
'''Retorna o índice do item conforme .ln.index
Caso seja encontrado problema, retorna -1;
Caso não haja .index em .ln, retorna -2; '''
try:
return self.index(*item)
# return self.ln.find(*item)
except AttributeError:
return -2
except:
return -1 | [
"def",
"find",
"(",
"self",
",",
"*",
"item",
")",
":",
"try",
":",
"return",
"self",
".",
"index",
"(",
"*",
"item",
")",
"#\treturn self.ln.find(*item)",
"except",
"AttributeError",
":",
"return",
"-",
"2",
"except",
":",
"return",
"-",
"1"
] | [
278,
1
] | [
288,
12
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Genetic.calculate_best_fitness | (self) | return self.fitness | Calcula a melhor aptidão entre todas as populações e salva na lista da classe genética.
Returns:
:return: void
| Calcula a melhor aptidão entre todas as populações e salva na lista da classe genética. | def calculate_best_fitness(self):
"""Calcula a melhor aptidão entre todas as populações e salva na lista da classe genética.
Returns:
:return: void
"""
self.fitness = max([k.fitness for k in self.population])
return self.fitness | [
"def",
"calculate_best_fitness",
"(",
"self",
")",
":",
"self",
".",
"fitness",
"=",
"max",
"(",
"[",
"k",
".",
"fitness",
"for",
"k",
"in",
"self",
".",
"population",
"]",
")",
"return",
"self",
".",
"fitness"
] | [
216,
4
] | [
225,
27
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
load | (caminho) | return componentes_todos | Carrega todos os componentes especificados pelo caminho do arquivo passado como parâmetro. | Carrega todos os componentes especificados pelo caminho do arquivo passado como parâmetro. | def load(caminho):
"""Carrega todos os componentes especificados pelo caminho do arquivo passado como parâmetro."""
p = Path(caminho)
componentes_todos = []
for x in p.iterdir():
with x.open('r', encoding='utf8') as file:
componentes_todos.append(json.load(file))
return componentes_todos | [
"def",
"load",
"(",
"caminho",
")",
":",
"p",
"=",
"Path",
"(",
"caminho",
")",
"componentes_todos",
"=",
"[",
"]",
"for",
"x",
"in",
"p",
".",
"iterdir",
"(",
")",
":",
"with",
"x",
".",
"open",
"(",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"file",
":",
"componentes_todos",
".",
"append",
"(",
"json",
".",
"load",
"(",
"file",
")",
")",
"return",
"componentes_todos"
] | [
30,
0
] | [
37,
28
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
test_put_interventions_permission | (client) | Teste put /intervention - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado | Teste put /intervention - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado | def test_put_interventions_permission(client):
"""Teste put /intervention - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado"""
access_token = get_access(client)
idPrescriptionDrug = '20'
data = {
"status": "s",
"admissionNumber": "5"
}
url = 'intervention/' + idPrescriptionDrug
response = client.put(url, data=json.dumps(data), headers=make_headers(access_token))
assert response.status_code == 401 | [
"def",
"test_put_interventions_permission",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"idPrescriptionDrug",
"=",
"'20'",
"data",
"=",
"{",
"\"status\"",
":",
"\"s\"",
",",
"\"admissionNumber\"",
":",
"\"5\"",
"}",
"url",
"=",
"'intervention/'",
"+",
"idPrescriptionDrug",
"response",
"=",
"client",
".",
"put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"assert",
"response",
".",
"status_code",
"==",
"401"
] | [
59,
0
] | [
72,
38
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EquipamentoAmbienteResource.handle_post | (self, request, user, *args, **kwargs) | Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente.
URL: equipamentoambiente/$
| Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente. | def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente.
URL: equipamentoambiente/$
"""
try:
xml_map, attrs_map = loads(request.raw_post_data)
self.log.debug('XML_MAP: %s', xml_map)
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.')
equipenviron_map = networkapi_map.get('equipamento_ambiente')
if equipenviron_map is None:
return self.response_error(3, u'Não existe valor para a tag equipamento_ambiente do XML de requisição.')
equip_id = equipenviron_map.get('id_equipamento')
# Valid ID Equipment
if not is_valid_int_greater_zero_param(equip_id):
self.log.error(
u'The equip_id parameter is not a valid value: %s.', equip_id)
raise InvalidValueError(None, 'equip_id', equip_id)
environment_id = equipenviron_map.get('id_ambiente')
# Valid ID Environment
if not is_valid_int_greater_zero_param(environment_id):
self.log.error(
u'The environment_id parameter is not a valid value: %s.', environment_id)
raise InvalidValueError(None, 'environment_id', environment_id)
is_router = int(equipenviron_map.get('is_router', 0))
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION,
None,
equip_id,
AdminPermission.EQUIP_WRITE_OPERATION):
return self.not_authorized()
equip_environment = EquipamentoAmbiente(equipamento=Equipamento(id=equip_id),
ambiente=Ambiente(
id=environment_id),
is_router=is_router)
equip_environment.create(user)
equip_environment_map = dict()
equip_environment_map['id'] = equip_environment.id
networkapi_map = dict()
networkapi_map['equipamento_ambiente'] = equip_environment_map
return self.response(dumps_networkapi(networkapi_map))
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisicao.')
return self.response_error(3, x)
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except EquipamentoAmbienteDuplicatedError:
return self.response_error(156, equip_id, environment_id)
except AmbienteNotFoundError:
return self.response_error(112)
except EquipamentoNotFoundError:
return self.response_error(117, equip_id)
except (EquipamentoError, RoteiroError, GrupoError):
return self.response_error(1) | [
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'XML_MAP: %s'",
",",
"xml_map",
")",
"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.')",
"",
"equipenviron_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'equipamento_ambiente'",
")",
"if",
"equipenviron_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag equipamento_ambiente do XML de requisição.')",
"",
"equip_id",
"=",
"equipenviron_map",
".",
"get",
"(",
"'id_equipamento'",
")",
"# Valid ID Equipment",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"equip_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The equip_id parameter is not a valid value: %s.'",
",",
"equip_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'equip_id'",
",",
"equip_id",
")",
"environment_id",
"=",
"equipenviron_map",
".",
"get",
"(",
"'id_ambiente'",
")",
"# Valid ID Environment",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"environment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The environment_id parameter is not a valid value: %s.'",
",",
"environment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'environment_id'",
",",
"environment_id",
")",
"is_router",
"=",
"int",
"(",
"equipenviron_map",
".",
"get",
"(",
"'is_router'",
",",
"0",
")",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"None",
",",
"equip_id",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"equip_environment",
"=",
"EquipamentoAmbiente",
"(",
"equipamento",
"=",
"Equipamento",
"(",
"id",
"=",
"equip_id",
")",
",",
"ambiente",
"=",
"Ambiente",
"(",
"id",
"=",
"environment_id",
")",
",",
"is_router",
"=",
"is_router",
")",
"equip_environment",
".",
"create",
"(",
"user",
")",
"equip_environment_map",
"=",
"dict",
"(",
")",
"equip_environment_map",
"[",
"'id'",
"]",
"=",
"equip_environment",
".",
"id",
"networkapi_map",
"=",
"dict",
"(",
")",
"networkapi_map",
"[",
"'equipamento_ambiente'",
"]",
"=",
"equip_environment_map",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"networkapi_map",
")",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisicao.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"EquipamentoAmbienteDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"156",
",",
"equip_id",
",",
"environment_id",
")",
"except",
"AmbienteNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"112",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"equip_id",
")",
"except",
"(",
"EquipamentoError",
",",
"RoteiroError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
407,
4
] | [
479,
41
] | 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
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor
# Atualiza o objeto rect de acordo com self.center
self.rect.centerx = self.center | [
"def",
"update",
"(",
"self",
")",
":",
"# Atualiza o valor do centro da espaçonave, e não o retângulo",
"if",
"self",
".",
"moving_right",
"and",
"self",
".",
"rect",
".",
"right",
"<",
"self",
".",
"screen_rect",
".",
"right",
":",
"self",
".",
"center",
"+=",
"self",
".",
"ai_settings",
".",
"ship_speed_factor",
"if",
"self",
".",
"moving_left",
"and",
"self",
".",
"rect",
".",
"left",
">",
"0",
":",
"self",
".",
"center",
"-=",
"self",
".",
"ai_settings",
".",
"ship_speed_factor",
"# Atualiza o objeto rect de acordo com self.center",
"self",
".",
"rect",
".",
"centerx",
"=",
"self",
".",
"center"
] | [
25,
1
] | [
36,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Callback.handle | (self) | Trata o evento associado a este callback. Tipicamente
deve-se ler o fileobj e processar os dados lidos. Classes
derivadas devem sobrescrever este método. | Trata o evento associado a este callback. Tipicamente
deve-se ler o fileobj e processar os dados lidos. Classes
derivadas devem sobrescrever este método. | def handle(self):
'''Trata o evento associado a este callback. Tipicamente
deve-se ler o fileobj e processar os dados lidos. Classes
derivadas devem sobrescrever este método.'''
pass | [
"def",
"handle",
"(",
"self",
")",
":",
"pass"
] | [
31,
4
] | [
35,
12
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Alien.blitme | (self) | Desenha o alienigena em sua posicao actual. | Desenha o alienigena em sua posicao actual. | def blitme(self):
"""Desenha o alienigena em sua posicao actual."""
self.screen.blit(self.image, self.rect) | [
"def",
"blitme",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"image",
",",
"self",
".",
"rect",
")"
] | [
38,
4
] | [
40,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TipoRedeResource.handle_put | (self, request, user, *args, **kwargs) | Trata uma requisição PUT para alterar tipos de rede.
URL: /tiporede/<id_tipo_rede>/
| Trata uma requisição PUT para alterar tipos de rede. | def handle_put(self, request, user, *args, **kwargs):
"""Trata uma requisição PUT para alterar tipos de rede.
URL: /tiporede/<id_tipo_rede>/
"""
# Obtém dados do request e verifica acesso
try:
# Verificar a permissão
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
# Obtém argumentos passados na URL
id_tipo_rede = kwargs.get('id_tipo_rede')
if id_tipo_rede is None:
return self.response_error(256)
# 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 "tipo_rede"
tipo_rede_map = networkapi_map.get('tipo_rede')
if tipo_rede_map is None:
return self.response_error(3, u'Não existe valor para a tag tipo_rede do XML de requisição.')
# Verifica a existência do valor "fqdn"
nome = tipo_rede_map.get('nome')
if nome is None:
return self.response_error(176)
# Altera o tipo de redeconforme dados recebidos no XML
TipoRede.update(user,
id_tipo_rede,
tipo_rede=nome
)
# 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 TipoRedeNotFoundError:
return self.response_error(111)
except TipoRedeNameDuplicatedError:
return self.response_error(253, nome)
except (GrupoError, VlanError):
return self.response_error(1) | [
"def",
"handle_put",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Obtém dados do request e verifica acesso",
"try",
":",
"# Verificar a permissão",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"NETWORK_TYPE_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"# Obtém argumentos passados na URL",
"id_tipo_rede",
"=",
"kwargs",
".",
"get",
"(",
"'id_tipo_rede'",
")",
"if",
"id_tipo_rede",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"256",
")",
"# 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 \"tipo_rede\"",
"tipo_rede_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'tipo_rede'",
")",
"if",
"tipo_rede_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag tipo_rede do XML de requisição.')",
"",
"# Verifica a existência do valor \"fqdn\"",
"nome",
"=",
"tipo_rede_map",
".",
"get",
"(",
"'nome'",
")",
"if",
"nome",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"176",
")",
"# Altera o tipo de redeconforme dados recebidos no XML",
"TipoRede",
".",
"update",
"(",
"user",
",",
"id_tipo_rede",
",",
"tipo_rede",
"=",
"nome",
")",
"# 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",
"TipoRedeNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"111",
")",
"except",
"TipoRedeNameDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"253",
",",
"nome",
")",
"except",
"(",
"GrupoError",
",",
"VlanError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
120,
4
] | [
173,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DocumentoEletronico.processar_documento | (self, edoc) | Processar documento executa o envio do documento fiscal de forma
completa ao serviço relacionado, esta é um método padrão que
segue o seguinte workflow:
1. Consulta o serviço;
2. Verifica se o documento não foi emitido anteriormente;
3. Envia o documento
4. Caso o envio seja assincrono busca o resultado do processamento
- Caso o processamento ainda não tenha sido efetuado,
aguarda o tempo médio + 50% e tenta o máximo setado no atributo
'maximo_tentativas_consulta_recibo'
5. Retorna o resultado.
Caro você queira armazenar todas as consultas em seu ERP segue o
exemplo:
for edoc in self.serialize():
nfe = NFe()
processo = None
for p in nfe.processar_documento(edoc):
# seu código aqui
:param edoc:
:return: Esta função retorna um yield, portanto ela retorna um iterator
| Processar documento executa o envio do documento fiscal de forma
completa ao serviço relacionado, esta é um método padrão que
segue o seguinte workflow: | def processar_documento(self, edoc):
""" Processar documento executa o envio do documento fiscal de forma
completa ao serviço relacionado, esta é um método padrão que
segue o seguinte workflow:
1. Consulta o serviço;
2. Verifica se o documento não foi emitido anteriormente;
3. Envia o documento
4. Caso o envio seja assincrono busca o resultado do processamento
- Caso o processamento ainda não tenha sido efetuado,
aguarda o tempo médio + 50% e tenta o máximo setado no atributo
'maximo_tentativas_consulta_recibo'
5. Retorna o resultado.
Caro você queira armazenar todas as consultas em seu ERP segue o
exemplo:
for edoc in self.serialize():
nfe = NFe()
processo = None
for p in nfe.processar_documento(edoc):
# seu código aqui
:param edoc:
:return: Esta função retorna um yield, portanto ela retorna um iterator
"""
if self._consulta_servico_ao_enviar:
proc_servico = self.status_servico()
yield proc_servico
#
# Se o serviço não estiver em operação
#
if not self._verifica_servico_em_operacao(proc_servico):
#
# Interrompe todo o processo
#
return
#
# Verificar se os documentos já não foram emitados antes
#
if self._consulta_documento_antes_de_enviar:
documento, chave = self.get_documento_id(edoc)
if not chave:
#
# Interrompe todo o processo se o documento nao tem chave
#
return
proc_consulta = self.consulta_documento(chave)
yield proc_consulta
#
# Se o documento já constar na SEFAZ (autorizada ou denegada)
#
if self._verifica_documento_ja_enviado(proc_consulta):
#
# Interrompe todo o processo
#
return
#
# Documento nao foi enviado, entao vamos envia-lo
#
proc_envio = self.envia_documento(edoc)
yield proc_envio
#
# Deu errado?
#
if not proc_envio.resposta:
return
if not self._verifica_resposta_envio_sucesso(proc_envio):
#
# Interrompe o processo
#
return
#
# Aguarda o tempo do processamento antes da consulta
#
self._aguarda_tempo_medio(proc_envio)
#
# Consulta o recibo do lote, para ver o que aconteceu
#
proc_recibo = self.consulta_recibo(proc_envio=proc_envio)
if not proc_recibo.resposta:
return
#
# Tenta receber o resultado do processamento do lote, caso ainda
# esteja em processamento
#
tentativa = 0
while (self._edoc_situacao_em_processamento(proc_recibo) and
tentativa < self._maximo_tentativas_consulta_recibo):
self._aguarda_tempo_medio(proc_envio)
tentativa += 1
#
# Consulta o recibo do lote, para ver o que aconteceu
#
proc_recibo = self.consulta_recibo(proc_envio=proc_envio)
yield proc_recibo | [
"def",
"processar_documento",
"(",
"self",
",",
"edoc",
")",
":",
"if",
"self",
".",
"_consulta_servico_ao_enviar",
":",
"proc_servico",
"=",
"self",
".",
"status_servico",
"(",
")",
"yield",
"proc_servico",
"#",
"# Se o serviço não estiver em operação",
"#",
"if",
"not",
"self",
".",
"_verifica_servico_em_operacao",
"(",
"proc_servico",
")",
":",
"#",
"# Interrompe todo o processo",
"#",
"return",
"#",
"# Verificar se os documentos já não foram emitados antes",
"#",
"if",
"self",
".",
"_consulta_documento_antes_de_enviar",
":",
"documento",
",",
"chave",
"=",
"self",
".",
"get_documento_id",
"(",
"edoc",
")",
"if",
"not",
"chave",
":",
"#",
"# Interrompe todo o processo se o documento nao tem chave",
"#",
"return",
"proc_consulta",
"=",
"self",
".",
"consulta_documento",
"(",
"chave",
")",
"yield",
"proc_consulta",
"#",
"# Se o documento já constar na SEFAZ (autorizada ou denegada)",
"#",
"if",
"self",
".",
"_verifica_documento_ja_enviado",
"(",
"proc_consulta",
")",
":",
"#",
"# Interrompe todo o processo",
"#",
"return",
"#",
"# Documento nao foi enviado, entao vamos envia-lo",
"#",
"proc_envio",
"=",
"self",
".",
"envia_documento",
"(",
"edoc",
")",
"yield",
"proc_envio",
"#",
"# Deu errado?",
"#",
"if",
"not",
"proc_envio",
".",
"resposta",
":",
"return",
"if",
"not",
"self",
".",
"_verifica_resposta_envio_sucesso",
"(",
"proc_envio",
")",
":",
"#",
"# Interrompe o processo",
"#",
"return",
"#",
"# Aguarda o tempo do processamento antes da consulta",
"#",
"self",
".",
"_aguarda_tempo_medio",
"(",
"proc_envio",
")",
"#",
"# Consulta o recibo do lote, para ver o que aconteceu",
"#",
"proc_recibo",
"=",
"self",
".",
"consulta_recibo",
"(",
"proc_envio",
"=",
"proc_envio",
")",
"if",
"not",
"proc_recibo",
".",
"resposta",
":",
"return",
"#",
"# Tenta receber o resultado do processamento do lote, caso ainda",
"# esteja em processamento",
"#",
"tentativa",
"=",
"0",
"while",
"(",
"self",
".",
"_edoc_situacao_em_processamento",
"(",
"proc_recibo",
")",
"and",
"tentativa",
"<",
"self",
".",
"_maximo_tentativas_consulta_recibo",
")",
":",
"self",
".",
"_aguarda_tempo_medio",
"(",
"proc_envio",
")",
"tentativa",
"+=",
"1",
"#",
"# Consulta o recibo do lote, para ver o que aconteceu",
"#",
"proc_recibo",
"=",
"self",
".",
"consulta_recibo",
"(",
"proc_envio",
"=",
"proc_envio",
")",
"yield",
"proc_recibo"
] | [
80,
4
] | [
183,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
weighted_sample | (bn, e) | return event, w | Exemplo de um evento de bn que é consistente com a evidência e;
Retornar o evento e seu peso, a probabilidade de que o evento
Concorda com as provas. | Exemplo de um evento de bn que é consistente com a evidência e;
Retornar o evento e seu peso, a probabilidade de que o evento
Concorda com as provas. | def weighted_sample(bn, e):
"""Exemplo de um evento de bn que é consistente com a evidência e;
Retornar o evento e seu peso, a probabilidade de que o evento
Concorda com as provas."""
w = 1
event = dict(e)
for node in bn.nodes:
Xi = node.variable
if Xi in e:
w *= node.p(e[Xi], event)
else:
event[Xi] = node.sample(event)
return event, w | [
"def",
"weighted_sample",
"(",
"bn",
",",
"e",
")",
":",
"w",
"=",
"1",
"event",
"=",
"dict",
"(",
"e",
")",
"for",
"node",
"in",
"bn",
".",
"nodes",
":",
"Xi",
"=",
"node",
".",
"variable",
"if",
"Xi",
"in",
"e",
":",
"w",
"*=",
"node",
".",
"p",
"(",
"e",
"[",
"Xi",
"]",
",",
"event",
")",
"else",
":",
"event",
"[",
"Xi",
"]",
"=",
"node",
".",
"sample",
"(",
"event",
")",
"return",
"event",
",",
"w"
] | [
463,
0
] | [
475,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
BoletoHTML._drawReciboSacado | (self, boletoDados) | Imprime o Recibo do Sacado para modelo de página inteira
:param boletoDados: Objeto com os dados do boleto a ser preenchido.
Deve ser subclasse de :class:`pyboleto.data.BoletoData`
:type boletoDados: :class:`pyboleto.data.BoletoData`
| Imprime o Recibo do Sacado para modelo de página inteira | def _drawReciboSacado(self, boletoDados):
"""Imprime o Recibo do Sacado para modelo de página inteira
:param boletoDados: Objeto com os dados do boleto a ser preenchido.
Deve ser subclasse de :class:`pyboleto.data.BoletoData`
:type boletoDados: :class:`pyboleto.data.BoletoData`
"""
tpl = string.Template(self._load_template('recibo_sacado.html'))
tpl_data = {}
# Cabeçalho
tpl_data['logo_img'] = ''
if boletoDados.logo_image:
img = codecs.open(self._load_image(boletoDados.logo_image))
aux = img.read()
aux = base64.b64encode(aux)
img_base64 = 'data:image/jpeg;base64,{0}'.format(aux)
tpl_data['logo_img'] = img_base64
tpl_data['codigo_dv_banco'] = boletoDados.codigo_dv_banco
# Corpo
tpl_data['cedente'] = boletoDados.cedente
tpl_data['agencia_conta_cedente'] = boletoDados.agencia_conta_cedente
tpl_data['cedente_documento'] = boletoDados.cedente_documento
data_vencimento = boletoDados.data_vencimento
tpl_data['data_vencimento'] = data_vencimento.strftime('%d/%m/%Y')
tpl_data['sacado'] = boletoDados.sacado[0]
tpl_data['nosso_numero_format'] = boletoDados.format_nosso_numero()
tpl_data['numero_documento'] = boletoDados.numero_documento
data_documento = boletoDados.data_documento
tpl_data['data_documento'] = data_documento.strftime('%d/%m/%Y')
tpl_data['cedente_endereco'] = boletoDados.cedente_endereco
valor_doc = self._formataValorParaExibir(boletoDados.valor_documento)
tpl_data['valor_documento'] = valor_doc
# Demonstrativo
tpl_data['demonstrativo'] = ''
for dm in boletoDados.demonstrativo:
tpl_data['demonstrativo'] += '<p>{0}</p>'.format(dm)
self.html += tpl.substitute(tpl_data) | [
"def",
"_drawReciboSacado",
"(",
"self",
",",
"boletoDados",
")",
":",
"tpl",
"=",
"string",
".",
"Template",
"(",
"self",
".",
"_load_template",
"(",
"'recibo_sacado.html'",
")",
")",
"tpl_data",
"=",
"{",
"}",
"# Cabeçalho",
"tpl_data",
"[",
"'logo_img'",
"]",
"=",
"''",
"if",
"boletoDados",
".",
"logo_image",
":",
"img",
"=",
"codecs",
".",
"open",
"(",
"self",
".",
"_load_image",
"(",
"boletoDados",
".",
"logo_image",
")",
")",
"aux",
"=",
"img",
".",
"read",
"(",
")",
"aux",
"=",
"base64",
".",
"b64encode",
"(",
"aux",
")",
"img_base64",
"=",
"'data:image/jpeg;base64,{0}'",
".",
"format",
"(",
"aux",
")",
"tpl_data",
"[",
"'logo_img'",
"]",
"=",
"img_base64",
"tpl_data",
"[",
"'codigo_dv_banco'",
"]",
"=",
"boletoDados",
".",
"codigo_dv_banco",
"# Corpo",
"tpl_data",
"[",
"'cedente'",
"]",
"=",
"boletoDados",
".",
"cedente",
"tpl_data",
"[",
"'agencia_conta_cedente'",
"]",
"=",
"boletoDados",
".",
"agencia_conta_cedente",
"tpl_data",
"[",
"'cedente_documento'",
"]",
"=",
"boletoDados",
".",
"cedente_documento",
"data_vencimento",
"=",
"boletoDados",
".",
"data_vencimento",
"tpl_data",
"[",
"'data_vencimento'",
"]",
"=",
"data_vencimento",
".",
"strftime",
"(",
"'%d/%m/%Y'",
")",
"tpl_data",
"[",
"'sacado'",
"]",
"=",
"boletoDados",
".",
"sacado",
"[",
"0",
"]",
"tpl_data",
"[",
"'nosso_numero_format'",
"]",
"=",
"boletoDados",
".",
"format_nosso_numero",
"(",
")",
"tpl_data",
"[",
"'numero_documento'",
"]",
"=",
"boletoDados",
".",
"numero_documento",
"data_documento",
"=",
"boletoDados",
".",
"data_documento",
"tpl_data",
"[",
"'data_documento'",
"]",
"=",
"data_documento",
".",
"strftime",
"(",
"'%d/%m/%Y'",
")",
"tpl_data",
"[",
"'cedente_endereco'",
"]",
"=",
"boletoDados",
".",
"cedente_endereco",
"valor_doc",
"=",
"self",
".",
"_formataValorParaExibir",
"(",
"boletoDados",
".",
"valor_documento",
")",
"tpl_data",
"[",
"'valor_documento'",
"]",
"=",
"valor_doc",
"# Demonstrativo",
"tpl_data",
"[",
"'demonstrativo'",
"]",
"=",
"''",
"for",
"dm",
"in",
"boletoDados",
".",
"demonstrativo",
":",
"tpl_data",
"[",
"'demonstrativo'",
"]",
"+=",
"'<p>{0}</p>'",
".",
"format",
"(",
"dm",
")",
"self",
".",
"html",
"+=",
"tpl",
".",
"substitute",
"(",
"tpl_data",
")"
] | [
85,
4
] | [
129,
45
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
separa_frases | (sentenca) | return re.split(r'[,:;]+', sentenca) | A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca | A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca | def separa_frases(sentenca):
'''A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca'''
return re.split(r'[,:;]+', sentenca) | [
"def",
"separa_frases",
"(",
"sentenca",
")",
":",
"return",
"re",
".",
"split",
"(",
"r'[,:;]+'",
",",
"sentenca",
")"
] | [
35,
0
] | [
37,
40
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Interface.set_ip | (self, ip, mask) | Pega ip passado por instância e adiciona na variável self.ip. | Pega ip passado por instância e adiciona na variável self.ip. | def set_ip(self, ip, mask):
""" Pega ip passado por instância e adiciona na variável self.ip."""
self.ip = ip
self.mask = Interface.convert_cidr(mask) | [
"def",
"set_ip",
"(",
"self",
",",
"ip",
",",
"mask",
")",
":",
"self",
".",
"ip",
"=",
"ip",
"self",
".",
"mask",
"=",
"Interface",
".",
"convert_cidr",
"(",
"mask",
")"
] | [
20,
4
] | [
24,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
check_fleet_edges | (ai_settings, aliens) | Responde apropriadamente se algum alienígena alcançou uma borda | Responde apropriadamente se algum alienígena alcançou uma borda | def check_fleet_edges(ai_settings, aliens):
"""Responde apropriadamente se algum alienígena alcançou uma borda"""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break | [
"def",
"check_fleet_edges",
"(",
"ai_settings",
",",
"aliens",
")",
":",
"for",
"alien",
"in",
"aliens",
".",
"sprites",
"(",
")",
":",
"if",
"alien",
".",
"check_edges",
"(",
")",
":",
"change_fleet_direction",
"(",
"ai_settings",
",",
"aliens",
")",
"break"
] | [
233,
0
] | [
238,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
lex | (ctx, *, extension: str) | Carrega uma extensão. | Carrega uma extensão. | async def lex(ctx, *, extension: str):
"""Carrega uma extensão."""
try:
client.load_extension(f"ext.{extension}")
except commands.ExtensionNotFound as ex:
await ctx.reply(f"Não existe uma extensão chamada `{ex.name}`")
return
except commands.ExtensionAlreadyLoaded as ex:
await ctx.reply(f"A extensão `{ex.name}` já está carregada.")
return
except commands.NoEntryPointError as ex:
await ctx.reply(f"A extensão `{ex.name}` não possui a função `setup(...)`")
return
await ctx.reply("Extensão carregada :+1:")
| [
"async",
"def",
"lex",
"(",
"ctx",
",",
"*",
",",
"extension",
":",
"str",
")",
":",
"try",
":",
"client",
".",
"load_extension",
"(",
"f\"ext.{extension}\"",
")",
"except",
"commands",
".",
"ExtensionNotFound",
"as",
"ex",
":",
"await",
"ctx",
".",
"reply",
"(",
"f\"Não existe uma extensão chamada `{ex.name}`\")\r",
"",
"return",
"except",
"commands",
".",
"ExtensionAlreadyLoaded",
"as",
"ex",
":",
"await",
"ctx",
".",
"reply",
"(",
"f\"A extensão `{ex.name}` já está carregada.\")\r",
"",
"return",
"except",
"commands",
".",
"NoEntryPointError",
"as",
"ex",
":",
"await",
"ctx",
".",
"reply",
"(",
"f\"A extensão `{ex.name}` não possui a função `setup(...)`\")\r",
"",
"return",
"await",
"ctx",
".",
"reply",
"(",
"\"Extensão carregada :+1:\")",
"\r"
] | [
415,
0
] | [
429,
47
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
sum_out | (var, factors, bn) | return result | Eliminar var de todos os fatores somando sobre seus valores. | Eliminar var de todos os fatores somando sobre seus valores. | def sum_out(var, factors, bn):
"Eliminar var de todos os fatores somando sobre seus valores."
result, var_factors = [], []
for f in factors:
(var_factors if var in f.variables else result).append(f)
result.append(pointwise_product(var_factors, bn).sum_out(var, bn))
return result | [
"def",
"sum_out",
"(",
"var",
",",
"factors",
",",
"bn",
")",
":",
"result",
",",
"var_factors",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"f",
"in",
"factors",
":",
"(",
"var_factors",
"if",
"var",
"in",
"f",
".",
"variables",
"else",
"result",
")",
".",
"append",
"(",
"f",
")",
"result",
".",
"append",
"(",
"pointwise_product",
"(",
"var_factors",
",",
"bn",
")",
".",
"sum_out",
"(",
"var",
",",
"bn",
")",
")",
"return",
"result"
] | [
343,
0
] | [
349,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Contrato.salva_estado | (self) | return Estado(Contrato(data=self.__data,
cliente=self.__cliente,
tipo=self.__tipo)) | Cria um estado com espelho do contrato atual Obs. Um novo objeto,
pois o mesmo será salvo no historico.
Returns:
Class Estado: Um objeto class Estado (class Contrato)
| Cria um estado com espelho do contrato atual Obs. Um novo objeto,
pois o mesmo será salvo no historico. | def salva_estado(self):
"""Cria um estado com espelho do contrato atual Obs. Um novo objeto,
pois o mesmo será salvo no historico.
Returns:
Class Estado: Um objeto class Estado (class Contrato)
"""
return Estado(Contrato(data=self.__data,
cliente=self.__cliente,
tipo=self.__tipo)) | [
"def",
"salva_estado",
"(",
"self",
")",
":",
"return",
"Estado",
"(",
"Contrato",
"(",
"data",
"=",
"self",
".",
"__data",
",",
"cliente",
"=",
"self",
".",
"__cliente",
",",
"tipo",
"=",
"self",
".",
"__tipo",
")",
")"
] | [
54,
4
] | [
63,
49
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update_bullets | (ai_settings,screen, stats, sb, ship, aliens, bullets) | Atualiza a posicao dos projeteis e se livra dos porjeteis
antigos. | Atualiza a posicao dos projeteis e se livra dos porjeteis
antigos. | def update_bullets(ai_settings,screen, stats, sb, ship, aliens, bullets):
"""Atualiza a posicao dos projeteis e se livra dos porjeteis
antigos."""
bullets.update()
# Livra-se dos projeteis que desapareceram
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",
")",
":",
"bullets",
".",
"update",
"(",
")",
"# Livra-se dos projeteis que desapareceram",
"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",
")"
] | [
102,
0
] | [
114,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
buscaBinariaIterativa | (alvo, array) | return -1 | Retorna o índice do array em que o elemento alvo está contido.
Considerando a coleção recebida como parâmetro, identifica e retor-
na o índice em que o elemento especificado está contido. Caso esse
elemento não esteja presente na coleção, retorna -1. Utiliza uma
abordagem iterativa.
Parameters
----------
alvo : ?
Elemento cujo índice está sendo buscado
array : list
A lista cujo índice do elemento deve ser identificado
Return
------
index : int
O índice em que o elemento alvo está armazenado
| Retorna o índice do array em que o elemento alvo está contido. | def buscaBinariaIterativa(alvo, array):
""" Retorna o índice do array em que o elemento alvo está contido.
Considerando a coleção recebida como parâmetro, identifica e retor-
na o índice em que o elemento especificado está contido. Caso esse
elemento não esteja presente na coleção, retorna -1. Utiliza uma
abordagem iterativa.
Parameters
----------
alvo : ?
Elemento cujo índice está sendo buscado
array : list
A lista cujo índice do elemento deve ser identificado
Return
------
index : int
O índice em que o elemento alvo está armazenado
"""
min = 0
max = len(array) - 1
while (min <= max):
mid = (min + max) // 2
if (array[mid] == alvo):
return mid
else:
if (array[mid] < alvo):
min = mid + 1
else:
max = mid - 1
return -1 | [
"def",
"buscaBinariaIterativa",
"(",
"alvo",
",",
"array",
")",
":",
"min",
"=",
"0",
"max",
"=",
"len",
"(",
"array",
")",
"-",
"1",
"while",
"(",
"min",
"<=",
"max",
")",
":",
"mid",
"=",
"(",
"min",
"+",
"max",
")",
"//",
"2",
"if",
"(",
"array",
"[",
"mid",
"]",
"==",
"alvo",
")",
":",
"return",
"mid",
"else",
":",
"if",
"(",
"array",
"[",
"mid",
"]",
"<",
"alvo",
")",
":",
"min",
"=",
"mid",
"+",
"1",
"else",
":",
"max",
"=",
"mid",
"-",
"1",
"return",
"-",
"1"
] | [
17,
0
] | [
48,
13
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
freq_palavras | (palavras) | return dicionario | Primeiro eu transformo a string em uma lista para manipular melhor os dados e conseguir percorrer eles
por um laço de repetição de maneira simplificada | Primeiro eu transformo a string em uma lista para manipular melhor os dados e conseguir percorrer eles
por um laço de repetição de maneira simplificada | def freq_palavras(palavras):
""" Primeiro eu transformo a string em uma lista para manipular melhor os dados e conseguir percorrer eles
por um laço de repetição de maneira simplificada """
lista_palavras = palavras.split()
encontradas = []
dicionario = {}
for palavra in lista_palavras:
if palavra not in encontradas:
encontradas.append(palavra)
""" Com o uso de uma lista auxiliar eu crio uma nova versão da lista original, com a diferença de que
esta não contém palavras repetidas """
dicionario.update({palavra:lista_palavras.count(palavra)})
""" Fazendo uso da lista auxiliar, começo a popular um dicionário que usa a lista com palavras não repetidas
como referencia, e a lista original como fonte de dado para contagem utilizando a função "count()" que recebe
como parametro um valor dentro de uma lista e retorna a quantidade de ocorrencias desse valor na mesma """
return dicionario | [
"def",
"freq_palavras",
"(",
"palavras",
")",
":",
"lista_palavras",
"=",
"palavras",
".",
"split",
"(",
")",
"encontradas",
"=",
"[",
"]",
"dicionario",
"=",
"{",
"}",
"for",
"palavra",
"in",
"lista_palavras",
":",
"if",
"palavra",
"not",
"in",
"encontradas",
":",
"encontradas",
".",
"append",
"(",
"palavra",
")",
"\"\"\" Com o uso de uma lista auxiliar eu crio uma nova versão da lista original, com a diferença de que\n esta não contém palavras repetidas \"\"\"",
"dicionario",
".",
"update",
"(",
"{",
"palavra",
":",
"lista_palavras",
".",
"count",
"(",
"palavra",
")",
"}",
")",
"\"\"\" Fazendo uso da lista auxiliar, começo a popular um dicionário que usa a lista com palavras não repetidas\n como referencia, e a lista original como fonte de dado para contagem utilizando a função \"count()\" que recebe\n como parametro um valor dentro de uma lista e retorna a quantidade de ocorrencias desse valor na mesma \"\"\"",
"return",
"dicionario"
] | [
7,
0
] | [
22,
21
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
DrivvoSensor.total_payment | (self) | return total | Soma total de valores pagos em todos os abastecimentos. | Soma total de valores pagos em todos os abastecimentos. | def total_payment(self):
"""Soma total de valores pagos em todos os abastecimentos."""
total = 0
for supply in self._supplies:
total += supply.get("valor_total")
return total | [
"def",
"total_payment",
"(",
"self",
")",
":",
"total",
"=",
"0",
"for",
"supply",
"in",
"self",
".",
"_supplies",
":",
"total",
"+=",
"supply",
".",
"get",
"(",
"\"valor_total\"",
")",
"return",
"total"
] | [
120,
4
] | [
125,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Car.update_odometer | (self, mileage) | Define o valor de leitura do hodômetro com valor especificado. | Define o valor de leitura do hodômetro com valor especificado. | def update_odometer(self, mileage):
"""Define o valor de leitura do hodômetro com valor especificado."""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!") | [
"def",
"update_odometer",
"(",
"self",
",",
"mileage",
")",
":",
"if",
"mileage",
">=",
"self",
".",
"odometer_reading",
":",
"self",
".",
"odometer_reading",
"=",
"mileage",
"else",
":",
"print",
"(",
"\"You can't roll back an odometer!\"",
")"
] | [
24,
4
] | [
29,
53
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Car.read_odometer | (self) | Exibe uma frase que mostra a milhagem do carro | Exibe uma frase que mostra a milhagem do carro | def read_odometer(self):
"""Exibe uma frase que mostra a milhagem do carro """
print("This car has " + str(self.odometer_reading) + " miles on it.") | [
"def",
"read_odometer",
"(",
"self",
")",
":",
"print",
"(",
"\"This car has \"",
"+",
"str",
"(",
"self",
".",
"odometer_reading",
")",
"+",
"\" miles on it.\"",
")"
] | [
20,
4
] | [
22,
77
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
get_string | (number) | return numero_por_extenso | Dada uma string de um número de tamanho 3 XXX (centena, dezena e unidade. Com '0' a esquerda caso preciso)
retorna a string do número escrito por extenso | Dada uma string de um número de tamanho 3 XXX (centena, dezena e unidade. Com '0' a esquerda caso preciso)
retorna a string do número escrito por extenso | def get_string(number):
"""Dada uma string de um número de tamanho 3 XXX (centena, dezena e unidade. Com '0' a esquerda caso preciso)
retorna a string do número escrito por extenso"""
if type(number) != str or len(number) != 3:
raise ValueError(
"O argumento number deve ser uma string de comprimento 3 representando o numéro.")
numero_por_extenso = ''
for idx in range(0, 3):
next_string = translate_matrix[2 - idx][int(number[idx])]
if next_string != '':
# Caso especial da dezena iniciada por 1 (10,11,12,13...)
if idx == 1 and int(number[idx]) == 1:
next_string = translate_matrix[3][int(number[idx+1])]
numero_por_extenso += next_string
break
# Só pra escrita ficar mais natural, da maneira como falamos
if idx != 2 and number[idx+1:] != '0':
next_string += ' e '
numero_por_extenso += next_string
return numero_por_extenso | [
"def",
"get_string",
"(",
"number",
")",
":",
"if",
"type",
"(",
"number",
")",
"!=",
"str",
"or",
"len",
"(",
"number",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"O argumento number deve ser uma string de comprimento 3 representando o numéro.\")",
"",
"numero_por_extenso",
"=",
"''",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"3",
")",
":",
"next_string",
"=",
"translate_matrix",
"[",
"2",
"-",
"idx",
"]",
"[",
"int",
"(",
"number",
"[",
"idx",
"]",
")",
"]",
"if",
"next_string",
"!=",
"''",
":",
"# Caso especial da dezena iniciada por 1 (10,11,12,13...)",
"if",
"idx",
"==",
"1",
"and",
"int",
"(",
"number",
"[",
"idx",
"]",
")",
"==",
"1",
":",
"next_string",
"=",
"translate_matrix",
"[",
"3",
"]",
"[",
"int",
"(",
"number",
"[",
"idx",
"+",
"1",
"]",
")",
"]",
"numero_por_extenso",
"+=",
"next_string",
"break",
"# Só pra escrita ficar mais natural, da maneira como falamos",
"if",
"idx",
"!=",
"2",
"and",
"number",
"[",
"idx",
"+",
"1",
":",
"]",
"!=",
"'0'",
":",
"next_string",
"+=",
"' e '",
"numero_por_extenso",
"+=",
"next_string",
"return",
"numero_por_extenso"
] | [
17,
0
] | [
37,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
number_of_friends | (user) | return len(user["Friends"]) | Quantos amigos o usuário tem? | Quantos amigos o usuário tem? | def number_of_friends(user):
"""Quantos amigos o usuário tem?"""
return len(user["Friends"]) # Tamanho da Lista de Amigos | [
"def",
"number_of_friends",
"(",
"user",
")",
":",
"return",
"len",
"(",
"user",
"[",
"\"Friends\"",
"]",
")",
"# Tamanho da Lista de Amigos"
] | [
37,
0
] | [
39,
60
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Factor.normalize | (self) | return ProbDist(self.variables[0], {k: v for ((k,), v) in self.cpt.items()}) | Retorne minhas probabilidades; Deve ser inferior a uma variável. | Retorne minhas probabilidades; Deve ser inferior a uma variável. | def normalize(self):
"Retorne minhas probabilidades; Deve ser inferior a uma variável."
assert len(self.variables) == 1
return ProbDist(self.variables[0], {k: v for ((k,), v) in self.cpt.items()}) | [
"def",
"normalize",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"variables",
")",
"==",
"1",
"return",
"ProbDist",
"(",
"self",
".",
"variables",
"[",
"0",
"]",
",",
"{",
"k",
":",
"v",
"for",
"(",
"(",
"k",
",",
")",
",",
"v",
")",
"in",
"self",
".",
"cpt",
".",
"items",
"(",
")",
"}",
")"
] | [
380,
4
] | [
383,
84
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
resta | (a: float, b: float) | return a - b | Resta dos números.
:param a: Primer número.
:a type: float
:param b: Segundo número.
:b type: float
:return: La resta de los dos números.
:rtype: float
| Resta dos números. | def resta(a: float, b: float) -> float:
"""Resta dos números.
:param a: Primer número.
:a type: float
:param b: Segundo número.
:b type: float
:return: La resta de los dos números.
:rtype: float
"""
return a - b | [
"def",
"resta",
"(",
"a",
":",
"float",
",",
"b",
":",
"float",
")",
"->",
"float",
":",
"return",
"a",
"-",
"b"
] | [
19,
0
] | [
29,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
UndirectedGraph.has_node | (self, v) | return (v in self.__edges) | Verifica se um vértice existe no grafo | Verifica se um vértice existe no grafo | def has_node(self, v):
''' Verifica se um vértice existe no grafo'''
return (v in self.__edges) | [
"def",
"has_node",
"(",
"self",
",",
"v",
")",
":",
"return",
"(",
"v",
"in",
"self",
".",
"__edges",
")"
] | [
95,
4
] | [
97,
34
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
SendDividas.__init__ | (self, *args, email, compt) | a partir do terceiro argumento, só há mensagens attachedas | a partir do terceiro argumento, só há mensagens attachedas | def __init__(self, *args, email, compt):
__razao_social, __cnpj = args
now_email = email
self.compt = compt
print(now_email)
# print(f'VALOR: {VALOR}')
print(f'_cliente: {__razao_social}')
# input(self.set_compt_only(-11, 1, past_only=False))
# FUNCIONA PRA CONTAR PRO MES Q VEM VALIDADO COM ANO
self.client_path = self.files_pathit(
"Dívidas_Simples_" + __razao_social, compt)
dividas_pdf_files = self.files_get_anexos_v4(
self.client_path, file_type='pdf', upload=False)
qtd_arquivos = len(dividas_pdf_files)
# mail_header = f"com vencimento previsto para o dia: {self.venc_boletos().replace('-', '/')}"
mail_header = f"com vencimento previsto para o dia: 30/10"
mail_header = mail_header.replace('30', '31')
mail_header = f"Parcelamentos, {'boleto' if qtd_arquivos == 1 else 'boletos'} {mail_header}"
print('titulo: ', mail_header)
message = self.mail_dividas_msg(
__razao_social, __cnpj, len(dividas_pdf_files))
# print(message)
das_message = self.write_message(message)
# # '[email protected]'
self.main_send_email(now_email, mail_header,
das_message, dividas_pdf_files)
# ###########################
# Vou registrar o each_dict no b
# ###########################
"""a partir do terceiro argumento, só há mensagens attachedas""" | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"email",
",",
"compt",
")",
":",
"__razao_social",
",",
"__cnpj",
"=",
"args",
"now_email",
"=",
"email",
"self",
".",
"compt",
"=",
"compt",
"print",
"(",
"now_email",
")",
"# print(f'VALOR: {VALOR}')",
"print",
"(",
"f'_cliente: {__razao_social}'",
")",
"# input(self.set_compt_only(-11, 1, past_only=False))",
"# FUNCIONA PRA CONTAR PRO MES Q VEM VALIDADO COM ANO",
"self",
".",
"client_path",
"=",
"self",
".",
"files_pathit",
"(",
"\"Dívidas_Simples_\" ",
" ",
"_razao_social,",
" ",
"ompt)",
"",
"dividas_pdf_files",
"=",
"self",
".",
"files_get_anexos_v4",
"(",
"self",
".",
"client_path",
",",
"file_type",
"=",
"'pdf'",
",",
"upload",
"=",
"False",
")",
"qtd_arquivos",
"=",
"len",
"(",
"dividas_pdf_files",
")",
"# mail_header = f\"com vencimento previsto para o dia: {self.venc_boletos().replace('-', '/')}\"",
"mail_header",
"=",
"f\"com vencimento previsto para o dia: 30/10\"",
"mail_header",
"=",
"mail_header",
".",
"replace",
"(",
"'30'",
",",
"'31'",
")",
"mail_header",
"=",
"f\"Parcelamentos, {'boleto' if qtd_arquivos == 1 else 'boletos'} {mail_header}\"",
"print",
"(",
"'titulo: '",
",",
"mail_header",
")",
"message",
"=",
"self",
".",
"mail_dividas_msg",
"(",
"__razao_social",
",",
"__cnpj",
",",
"len",
"(",
"dividas_pdf_files",
")",
")",
"# print(message)",
"das_message",
"=",
"self",
".",
"write_message",
"(",
"message",
")",
"# # '[email protected]'",
"self",
".",
"main_send_email",
"(",
"now_email",
",",
"mail_header",
",",
"das_message",
",",
"dividas_pdf_files",
")",
"# ###########################",
"# Vou registrar o each_dict no b",
"# ###########################"
] | [
5,
4
] | [
41,
74
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Pesquisador.getArea | (self) | Acessa XML e extrai lista com áreas de conhecimento do perfil do pesquisador.
Returns:
type: Lista de AREAS ou None
| Acessa XML e extrai lista com áreas de conhecimento do perfil do pesquisador. | def getArea(self):
"""Acessa XML e extrai lista com áreas de conhecimento do perfil do pesquisador.
Returns:
type: Lista de AREAS ou None
"""
#----Temos XML válido?
if self.__FLAG:
#----Areas registradas nos dados-gerais do pesquisador
AREAS = [ el.get("NOME-DA-AREA-DO-CONHECIMENTO") for el in self.root.xpath("DADOS-GERAIS/AREAS-DE-ATUACAO/*")]
#----tudo maiúsculo. mesma forma da tabela do qualis
AREAS = [val.upper() for val in AREAS]
#----elimina duplicatas de um jeito legal
AREAS = list(OrderedDict.fromkeys(AREAS))
return AREAS
else:
return None | [
"def",
"getArea",
"(",
"self",
")",
":",
"#----Temos XML válido?",
"if",
"self",
".",
"__FLAG",
":",
"#----Areas registradas nos dados-gerais do pesquisador",
"AREAS",
"=",
"[",
"el",
".",
"get",
"(",
"\"NOME-DA-AREA-DO-CONHECIMENTO\"",
")",
"for",
"el",
"in",
"self",
".",
"root",
".",
"xpath",
"(",
"\"DADOS-GERAIS/AREAS-DE-ATUACAO/*\"",
")",
"]",
"#----tudo maiúsculo. mesma forma da tabela do qualis",
"AREAS",
"=",
"[",
"val",
".",
"upper",
"(",
")",
"for",
"val",
"in",
"AREAS",
"]",
"#----elimina duplicatas de um jeito legal",
"AREAS",
"=",
"list",
"(",
"OrderedDict",
".",
"fromkeys",
"(",
"AREAS",
")",
")",
"return",
"AREAS",
"else",
":",
"return",
"None"
] | [
476,
4
] | [
494,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
MinhaUFOP.gerar_boleto | (self, valor: float, matricula: str, perfil: str = "G", **kwargs) | Gera um novo boleto se não há boletos pendentes, do contrário levanta um erro.
Args:
valor (float): Valor do boleto a ser gerado. Entre 3.0 e 300.0
matricula (str): Matrícula do usuário (20.1.1111)
perfil (str): Tipo de perfil do usuário. O padrão é G para Graduação.
Kwargs:
cpf (str): CPF do usuário logado (123.456.789-10). O padrão é o CPF utilizado na função login().
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Returns:
Um dict com informações do boleto gerado.
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
| Gera um novo boleto se não há boletos pendentes, do contrário levanta um erro. | def gerar_boleto(self, valor: float, matricula: str, perfil: str = "G", **kwargs) -> dict:
"""Gera um novo boleto se não há boletos pendentes, do contrário levanta um erro.
Args:
valor (float): Valor do boleto a ser gerado. Entre 3.0 e 300.0
matricula (str): Matrícula do usuário (20.1.1111)
perfil (str): Tipo de perfil do usuário. O padrão é G para Graduação.
Kwargs:
cpf (str): CPF do usuário logado (123.456.789-10). O padrão é o CPF utilizado na função login().
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Returns:
Um dict com informações do boleto gerado.
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
"""
url = kwargs.get('url', "https://zeppelin10.ufop.br/api/v1/ru/boleto/")
headers = kwargs.get('headers', {'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json'})
cpf = kwargs.get('cpf', self.cpf)
valor = "{:.2f}".format(valor)
payload = f'{{"idUsuario":"{cpf}","identificacao":"{matricula}","perfil":"{perfil}","valor":"{valor}"}}'
response = requests.request("POST", url, headers=headers, data=payload)
if response.ok:
return response.json()
else:
raise MinhaUFOPHTTPError(response) | [
"def",
"gerar_boleto",
"(",
"self",
",",
"valor",
":",
"float",
",",
"matricula",
":",
"str",
",",
"perfil",
":",
"str",
"=",
"\"G\"",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
",",
"\"https://zeppelin10.ufop.br/api/v1/ru/boleto/\"",
")",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"'Authorization'",
":",
"f'Bearer {self.token}'",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"cpf",
"=",
"kwargs",
".",
"get",
"(",
"'cpf'",
",",
"self",
".",
"cpf",
")",
"valor",
"=",
"\"{:.2f}\"",
".",
"format",
"(",
"valor",
")",
"payload",
"=",
"f'{{\"idUsuario\":\"{cpf}\",\"identificacao\":\"{matricula}\",\"perfil\":\"{perfil}\",\"valor\":\"{valor}\"}}'",
"response",
"=",
"requests",
".",
"request",
"(",
"\"POST\"",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"payload",
")",
"if",
"response",
".",
"ok",
":",
"return",
"response",
".",
"json",
"(",
")",
"else",
":",
"raise",
"MinhaUFOPHTTPError",
"(",
"response",
")"
] | [
245,
4
] | [
276,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Command.add_arguments | (self, parser) | Configura os parâmetros e opçẽos | Configura os parâmetros e opçẽos | def add_arguments(self, parser):
"Configura os parâmetros e opçẽos"
parser.add_argument('id_campanha', nargs=1, type=int) | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'id_campanha'",
",",
"nargs",
"=",
"1",
",",
"type",
"=",
"int",
")"
] | [
10,
4
] | [
12,
61
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestLambdas.test_lambda_allall | (self) | Teste usando dois operadores lambda: all e all | Teste usando dois operadores lambda: all e all | def test_lambda_allall(self):
"""Teste usando dois operadores lambda: all e all"""
expected = "customFieldValues/all(x: x/items/all(y: y/customFieldItem eq 'MGSSUSTR6-06R'))"
result = AllAll(
self.properties["customFieldValues"].items.customFieldItem
== "MGSSUSTR6-06R"
)
self.assertEqual(result, expected) | [
"def",
"test_lambda_allall",
"(",
"self",
")",
":",
"expected",
"=",
"\"customFieldValues/all(x: x/items/all(y: y/customFieldItem eq 'MGSSUSTR6-06R'))\"",
"result",
"=",
"AllAll",
"(",
"self",
".",
"properties",
"[",
"\"customFieldValues\"",
"]",
".",
"items",
".",
"customFieldItem",
"==",
"\"MGSSUSTR6-06R\"",
")",
"self",
".",
"assertEqual",
"(",
"result",
",",
"expected",
")"
] | [
81,
4
] | [
88,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
new_entry | (request, topic_id) | return render(request, 'learning_logs/new_entry.html', context) | Acrescenta uma nova entrada para um assunto em particular. | Acrescenta uma nova entrada para um assunto em particular. | def new_entry(request, topic_id):
"""Acrescenta uma nova entrada para um assunto em particular."""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
# Nenhum dado submetido; cria um formulário em branco
check_topic_owner(request, topic)
form = EntryForm()
else:
# Dados de POST submetidos; processa os dados
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_entry.save()
return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id]))
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context) | [
"def",
"new_entry",
"(",
"request",
",",
"topic_id",
")",
":",
"topic",
"=",
"Topic",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"topic_id",
")",
"if",
"request",
".",
"method",
"!=",
"'POST'",
":",
"# Nenhum dado submetido; cria um formulário em branco",
"check_topic_owner",
"(",
"request",
",",
"topic",
")",
"form",
"=",
"EntryForm",
"(",
")",
"else",
":",
"# Dados de POST submetidos; processa os dados",
"form",
"=",
"EntryForm",
"(",
"data",
"=",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"new_entry",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"new_entry",
".",
"topic",
"=",
"topic",
"new_entry",
".",
"save",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'learning_logs:topic'",
",",
"args",
"=",
"[",
"topic_id",
"]",
")",
")",
"context",
"=",
"{",
"'topic'",
":",
"topic",
",",
"'form'",
":",
"form",
"}",
"return",
"render",
"(",
"request",
",",
"'learning_logs/new_entry.html'",
",",
"context",
")"
] | [
53,
0
] | [
70,
67
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
get_current_process | () | return process_list.item(process_list.focus())['values'][1] | Captura e retorna id do processo ativo (em destaque na interface). | Captura e retorna id do processo ativo (em destaque na interface). | def get_current_process():
""" Captura e retorna id do processo ativo (em destaque na interface). """
return process_list.item(process_list.focus())['values'][1] | [
"def",
"get_current_process",
"(",
")",
":",
"return",
"process_list",
".",
"item",
"(",
"process_list",
".",
"focus",
"(",
")",
")",
"[",
"'values'",
"]",
"[",
"1",
"]"
] | [
138,
0
] | [
141,
63
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
dump_jsonl | (filename, lines) | Escreve resultado em um arquivo caminho determinado.
Args:
lines: Lista de linhas contento sequência de caracteres.
filename: Caminho para o arquivo.
Retornos:
Não há retorno
Exceções:
Não lança exceções.
| Escreve resultado em um arquivo caminho determinado. | def dump_jsonl(filename, lines):
"""Escreve resultado em um arquivo caminho determinado.
Args:
lines: Lista de linhas contento sequência de caracteres.
filename: Caminho para o arquivo.
Retornos:
Não há retorno
Exceções:
Não lança exceções.
"""
with open(filename, "a") as fp:
for line in lines:
fp.write(line)
fp.write("\n") | [
"def",
"dump_jsonl",
"(",
"filename",
",",
"lines",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"a\"",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"lines",
":",
"fp",
".",
"write",
"(",
"line",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")"
] | [
124,
0
] | [
139,
26
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
SimplesNacionalUtilities.change_ecac_client | (self, CNPJ) | :return: vai até ao site de declaração do ECAC. | :return: vai até ao site de declaração do ECAC. | def change_ecac_client(self, CNPJ):
""":return: vai até ao site de declaração do ECAC."""
driver = self.driver
# Merge me after with others like me...
for i in range(randint(1, 2)):
driver.get("https://cav.receita.fazenda.gov.br/ecac/")
driver.implicitly_wait(10)
sleep(randint(3, 5))
def elem_with_text(elem, searched):
_tag = driver.find_element(By.XPATH,
f"//{elem}[contains(text(),'{searched.rstrip()}')]")
return _tag
self.tags_wait('html', 'span')
sleep(5)
# nextcl = elem_with_text("span", "Alterar perfil de acesso")
# nextcl.click()
btn_perfil = WebDriverWait(self.driver, 20).until(
expected_conditions.presence_of_element_located((By.ID, 'btnPerfil')))
self.click_ac_elementors(btn_perfil)
# altera perfil e manda o cnpj
self.tags_wait('label')
cnpj = elem_with_text("label", "Procurador de pessoa jurídica - CNPJ")
cnpj.click()
sleep(.5)
self.send_keys_anywhere(CNPJ)
sleep(1)
self.send_keys_anywhere(Keys.TAB)
self.send_keys_anywhere(Keys.ENTER)
sleep(1)
# driver.find_element(By.CLASS_NAME, 'access-button').click()
# sleep(10)
antigo = driver.current_url
"""I GOT IT"""
# switch_to.frame...
sleep(5)
driver.get(
'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/')
sleep(2.5)
driver.get(antigo)
driver.get(
'https://cav.receita.fazenda.gov.br/ecac/Aplicacao.aspx?id=10009&origem=menu')
driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))
sleep(2)
while True:
try:
# don't need anymore
# break
driver.find_element(By.XPATH,
'//span[@class="glyphicon glyphicon-off"]').click()
driver.refresh()
break
except ElementClickInterceptedException:
print('---> PRESSIONE ESC PARA CONTINUAR <--- glyphicon-off intercepted')
press_key_b4('esc')
except NoSuchElementException:
print('---> PRESSIONE ESC PARA CONTINUAR NoSuchElement glyphicon-off')
press_key_b4('esc')
driver.get(
'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/')
driver.implicitly_wait(5)
break
sleep(3)
driver.switch_to.default_content()
"""I GOT IT"""
# chegou em todo mundo...
driver.get(
'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/')
driver.implicitly_wait(5) | [
"def",
"change_ecac_client",
"(",
"self",
",",
"CNPJ",
")",
":",
"driver",
"=",
"self",
".",
"driver",
"# Merge me after with others like me...",
"for",
"i",
"in",
"range",
"(",
"randint",
"(",
"1",
",",
"2",
")",
")",
":",
"driver",
".",
"get",
"(",
"\"https://cav.receita.fazenda.gov.br/ecac/\"",
")",
"driver",
".",
"implicitly_wait",
"(",
"10",
")",
"sleep",
"(",
"randint",
"(",
"3",
",",
"5",
")",
")",
"def",
"elem_with_text",
"(",
"elem",
",",
"searched",
")",
":",
"_tag",
"=",
"driver",
".",
"find_element",
"(",
"By",
".",
"XPATH",
",",
"f\"//{elem}[contains(text(),'{searched.rstrip()}')]\"",
")",
"return",
"_tag",
"self",
".",
"tags_wait",
"(",
"'html'",
",",
"'span'",
")",
"sleep",
"(",
"5",
")",
"# nextcl = elem_with_text(\"span\", \"Alterar perfil de acesso\")",
"# nextcl.click()",
"btn_perfil",
"=",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"20",
")",
".",
"until",
"(",
"expected_conditions",
".",
"presence_of_element_located",
"(",
"(",
"By",
".",
"ID",
",",
"'btnPerfil'",
")",
")",
")",
"self",
".",
"click_ac_elementors",
"(",
"btn_perfil",
")",
"# altera perfil e manda o cnpj",
"self",
".",
"tags_wait",
"(",
"'label'",
")",
"cnpj",
"=",
"elem_with_text",
"(",
"\"label\"",
",",
"\"Procurador de pessoa jurídica - CNPJ\")",
"",
"cnpj",
".",
"click",
"(",
")",
"sleep",
"(",
".5",
")",
"self",
".",
"send_keys_anywhere",
"(",
"CNPJ",
")",
"sleep",
"(",
"1",
")",
"self",
".",
"send_keys_anywhere",
"(",
"Keys",
".",
"TAB",
")",
"self",
".",
"send_keys_anywhere",
"(",
"Keys",
".",
"ENTER",
")",
"sleep",
"(",
"1",
")",
"# driver.find_element(By.CLASS_NAME, 'access-button').click()",
"# sleep(10)",
"antigo",
"=",
"driver",
".",
"current_url",
"\"\"\"I GOT IT\"\"\"",
"# switch_to.frame...",
"sleep",
"(",
"5",
")",
"driver",
".",
"get",
"(",
"'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/'",
")",
"sleep",
"(",
"2.5",
")",
"driver",
".",
"get",
"(",
"antigo",
")",
"driver",
".",
"get",
"(",
"'https://cav.receita.fazenda.gov.br/ecac/Aplicacao.aspx?id=10009&origem=menu'",
")",
"driver",
".",
"switch_to",
".",
"frame",
"(",
"driver",
".",
"find_element",
"(",
"By",
".",
"TAG_NAME",
",",
"\"iframe\"",
")",
")",
"sleep",
"(",
"2",
")",
"while",
"True",
":",
"try",
":",
"# don't need anymore",
"# break",
"driver",
".",
"find_element",
"(",
"By",
".",
"XPATH",
",",
"'//span[@class=\"glyphicon glyphicon-off\"]'",
")",
".",
"click",
"(",
")",
"driver",
".",
"refresh",
"(",
")",
"break",
"except",
"ElementClickInterceptedException",
":",
"print",
"(",
"'---> PRESSIONE ESC PARA CONTINUAR <--- glyphicon-off intercepted'",
")",
"press_key_b4",
"(",
"'esc'",
")",
"except",
"NoSuchElementException",
":",
"print",
"(",
"'---> PRESSIONE ESC PARA CONTINUAR NoSuchElement glyphicon-off'",
")",
"press_key_b4",
"(",
"'esc'",
")",
"driver",
".",
"get",
"(",
"'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/'",
")",
"driver",
".",
"implicitly_wait",
"(",
"5",
")",
"break",
"sleep",
"(",
"3",
")",
"driver",
".",
"switch_to",
".",
"default_content",
"(",
")",
"\"\"\"I GOT IT\"\"\"",
"# chegou em todo mundo...",
"driver",
".",
"get",
"(",
"'https://sinac.cav.receita.fazenda.gov.br/simplesnacional/aplicacoes/atspo/pgdasd2018.app/'",
")",
"driver",
".",
"implicitly_wait",
"(",
"5",
")"
] | [
244,
4
] | [
317,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
event_values | (event, variables) | Retorna uma tupla dos valores das variáveis no evento. | Retorna uma tupla dos valores das variáveis no evento. | def event_values(event, variables):
"""Retorna uma tupla dos valores das variáveis no evento."""
if isinstance(event, tuple) and len(event) == len(variables):
return event
else:
return tuple([event[var] for var in variables]) | [
"def",
"event_values",
"(",
"event",
",",
"variables",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"tuple",
")",
"and",
"len",
"(",
"event",
")",
"==",
"len",
"(",
"variables",
")",
":",
"return",
"event",
"else",
":",
"return",
"tuple",
"(",
"[",
"event",
"[",
"var",
"]",
"for",
"var",
"in",
"variables",
"]",
")"
] | [
123,
0
] | [
128,
55
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
MinhaUFOP.login | (self,
usuario: str,
senha: str,
encode: bool = True,
**kwargs) | Gera o token necessáio para acessar a API simulando um login.
Args:
usuario (str):Seu cpf com pontos e hífens (ex.: 123.456.789-10)
senha (str):Sua senha da MinhaUFOP, também pode ser um hash MD5
da senha
encode (bool):True se você estiver usando a senha pura, False se
você estiver utilizando um hash MD5 da senha
Kwargs:
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
| Gera o token necessáio para acessar a API simulando um login. | def login(self,
usuario: str,
senha: str,
encode: bool = True,
**kwargs) -> dict:
"""Gera o token necessáio para acessar a API simulando um login.
Args:
usuario (str):Seu cpf com pontos e hífens (ex.: 123.456.789-10)
senha (str):Sua senha da MinhaUFOP, também pode ser um hash MD5
da senha
encode (bool):True se você estiver usando a senha pura, False se
você estiver utilizando um hash MD5 da senha
Kwargs:
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
"""
self.cpf = usuario
if encode:
senha = hashlib.md5(senha.encode()).hexdigest()
url = kwargs.get('url', "https://zeppelin10.ufop.br/minhaUfop/v1/auth/login")
identificacao = kwargs.get('identificacao', '')
perfil = kwargs.get('perfil', '')
chave = kwargs.get('chave', "e8c8f5ef-4248-4e81-9cb9-4ab910080485")
payload = f'{{"identificador":"{usuario}","senha":"{senha}","identificacao":"{identificacao}","perfil":"{perfil}","crypt":true,"chave":"{chave}"}}'
headers = kwargs.get('headers', {'Content-Type': 'application/json'})
response = requests.request("POST", url, headers=headers, data=payload)
perfil_num = kwargs.get('perfil_num')
if response.ok:
res_json = response.json()
if res_json.get("token"):
self.token = res_json.get("token")
return res_json
elif res_json.get("perfil") and perfil_num:
res = self.login(usuario, senha, encode=encode, identificacao=res_json['perfil'][perfil_num]['identificacao'], perfil=res_json['perfil'][perfil_num]['perfil'])
return res
elif res_json.get("perfil") and not perfil_num:
return res_json
else:
raise MinhaUFOPHTTPError(response) | [
"def",
"login",
"(",
"self",
",",
"usuario",
":",
"str",
",",
"senha",
":",
"str",
",",
"encode",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"self",
".",
"cpf",
"=",
"usuario",
"if",
"encode",
":",
"senha",
"=",
"hashlib",
".",
"md5",
"(",
"senha",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
",",
"\"https://zeppelin10.ufop.br/minhaUfop/v1/auth/login\"",
")",
"identificacao",
"=",
"kwargs",
".",
"get",
"(",
"'identificacao'",
",",
"''",
")",
"perfil",
"=",
"kwargs",
".",
"get",
"(",
"'perfil'",
",",
"''",
")",
"chave",
"=",
"kwargs",
".",
"get",
"(",
"'chave'",
",",
"\"e8c8f5ef-4248-4e81-9cb9-4ab910080485\"",
")",
"payload",
"=",
"f'{{\"identificador\":\"{usuario}\",\"senha\":\"{senha}\",\"identificacao\":\"{identificacao}\",\"perfil\":\"{perfil}\",\"crypt\":true,\"chave\":\"{chave}\"}}'",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"response",
"=",
"requests",
".",
"request",
"(",
"\"POST\"",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"payload",
")",
"perfil_num",
"=",
"kwargs",
".",
"get",
"(",
"'perfil_num'",
")",
"if",
"response",
".",
"ok",
":",
"res_json",
"=",
"response",
".",
"json",
"(",
")",
"if",
"res_json",
".",
"get",
"(",
"\"token\"",
")",
":",
"self",
".",
"token",
"=",
"res_json",
".",
"get",
"(",
"\"token\"",
")",
"return",
"res_json",
"elif",
"res_json",
".",
"get",
"(",
"\"perfil\"",
")",
"and",
"perfil_num",
":",
"res",
"=",
"self",
".",
"login",
"(",
"usuario",
",",
"senha",
",",
"encode",
"=",
"encode",
",",
"identificacao",
"=",
"res_json",
"[",
"'perfil'",
"]",
"[",
"perfil_num",
"]",
"[",
"'identificacao'",
"]",
",",
"perfil",
"=",
"res_json",
"[",
"'perfil'",
"]",
"[",
"perfil_num",
"]",
"[",
"'perfil'",
"]",
")",
"return",
"res",
"elif",
"res_json",
".",
"get",
"(",
"\"perfil\"",
")",
"and",
"not",
"perfil_num",
":",
"return",
"res_json",
"else",
":",
"raise",
"MinhaUFOPHTTPError",
"(",
"response",
")"
] | [
11,
4
] | [
61,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Orcamento.valor | (self) | return total - self.__desconto_extra | Quando a propriedade for acessada, ela soma cada item retornando o valor
do orçamento e aplica o desconto extra.
Returns:
float: Valor total do orçamento menos desconto extra.
| Quando a propriedade for acessada, ela soma cada item retornando o valor
do orçamento e aplica o desconto extra. | def valor(self) -> float:
"""Quando a propriedade for acessada, ela soma cada item retornando o valor
do orçamento e aplica o desconto extra.
Returns:
float: Valor total do orçamento menos desconto extra.
"""
total: float = 0.0
for item in self.__itens:
total += item.valor
return total - self.__desconto_extra | [
"def",
"valor",
"(",
"self",
")",
"->",
"float",
":",
"total",
":",
"float",
"=",
"0.0",
"for",
"item",
"in",
"self",
".",
"__itens",
":",
"total",
"+=",
"item",
".",
"valor",
"return",
"total",
"-",
"self",
".",
"__desconto_extra"
] | [
54,
4
] | [
64,
44
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Certidao.mask | (self, doc: str = '') | return "{}.{}.{}.{}.{}.{}.{}.{}-{}".format(
doc[:6], doc[6:8], doc[8:10], doc[10:14],
doc[14], doc[15:20], doc[20:23], doc[23:30], doc[-2:]) | Mascara para a Certidão de Nascimento/Casamento/Óbito. | Mascara para a Certidão de Nascimento/Casamento/Óbito. | def mask(self, doc: str = '') -> str:
"""Mascara para a Certidão de Nascimento/Casamento/Óbito."""
return "{}.{}.{}.{}.{}.{}.{}.{}-{}".format(
doc[:6], doc[6:8], doc[8:10], doc[10:14],
doc[14], doc[15:20], doc[20:23], doc[23:30], doc[-2:]) | [
"def",
"mask",
"(",
"self",
",",
"doc",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"return",
"\"{}.{}.{}.{}.{}.{}.{}.{}-{}\"",
".",
"format",
"(",
"doc",
"[",
":",
"6",
"]",
",",
"doc",
"[",
"6",
":",
"8",
"]",
",",
"doc",
"[",
"8",
":",
"10",
"]",
",",
"doc",
"[",
"10",
":",
"14",
"]",
",",
"doc",
"[",
"14",
"]",
",",
"doc",
"[",
"15",
":",
"20",
"]",
",",
"doc",
"[",
"20",
":",
"23",
"]",
",",
"doc",
"[",
"23",
":",
"30",
"]",
",",
"doc",
"[",
"-",
"2",
":",
"]",
")"
] | [
54,
4
] | [
58,
66
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
random_list | (size, max_value) | return values | Retorna uma lista de valores aleatórios.
Cria e retorna uma lista de valores gerados aleatoriamente. A lista
possui o tamanho passado como parâmetro. Sendo MAX o valor do parâ-
metro valor_maximo, os valores gerados estarão contidos em [0, MAX].
Parameters
----------
size : int
O tamanho da lista a ser criada
max_value : int
O maior valor a ser possivelmente gerado
Return
------
values : list
A lista de tamanho especificado contendo os valores aleatórios
| Retorna uma lista de valores aleatórios. | def random_list(size, max_value):
""" Retorna uma lista de valores aleatórios.
Cria e retorna uma lista de valores gerados aleatoriamente. A lista
possui o tamanho passado como parâmetro. Sendo MAX o valor do parâ-
metro valor_maximo, os valores gerados estarão contidos em [0, MAX].
Parameters
----------
size : int
O tamanho da lista a ser criada
max_value : int
O maior valor a ser possivelmente gerado
Return
------
values : list
A lista de tamanho especificado contendo os valores aleatórios
"""
values = []
for i in range(size):
values.append(random.randint(0, max_value))
return values | [
"def",
"random_list",
"(",
"size",
",",
"max_value",
")",
":",
"values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"values",
".",
"append",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"max_value",
")",
")",
"return",
"values"
] | [
116,
0
] | [
138,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
create_routers | () | return router_objects | Le os dados no arquivo YAML e instancia os objetos de cada roteador. | Le os dados no arquivo YAML e instancia os objetos de cada roteador. | def create_routers():
""" Le os dados no arquivo YAML e instancia os objetos de cada roteador."""
router_objects = []
for router in yaml.routers:
for name, conf in router.items():
router_objects.append(Router( nome=name,
gns_port=conf['gns_port'],
ios=conf['ios'],
networks=conf['network'],
scope=conf['scope'],
script=conf['script_file']))
return router_objects | [
"def",
"create_routers",
"(",
")",
":",
"router_objects",
"=",
"[",
"]",
"for",
"router",
"in",
"yaml",
".",
"routers",
":",
"for",
"name",
",",
"conf",
"in",
"router",
".",
"items",
"(",
")",
":",
"router_objects",
".",
"append",
"(",
"Router",
"(",
"nome",
"=",
"name",
",",
"gns_port",
"=",
"conf",
"[",
"'gns_port'",
"]",
",",
"ios",
"=",
"conf",
"[",
"'ios'",
"]",
",",
"networks",
"=",
"conf",
"[",
"'network'",
"]",
",",
"scope",
"=",
"conf",
"[",
"'scope'",
"]",
",",
"script",
"=",
"conf",
"[",
"'script_file'",
"]",
")",
")",
"return",
"router_objects"
] | [
13,
0
] | [
26,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
SelectionSort.__simpleSelectionSort | (self, array, leftIndex, rightIndex) | Implementação do método SelectionSort de forma iterativa
Parametros:
array: Lista a ser ordenada
leftIndex(Opcional): Índice limítrofe a esquerda do array para ordenação parcial
rightIndex(Opcional): Índice limítrofe a direita do array para ordenação parcial
| Implementação do método SelectionSort de forma iterativa
Parametros:
array: Lista a ser ordenada
leftIndex(Opcional): Índice limítrofe a esquerda do array para ordenação parcial
rightIndex(Opcional): Índice limítrofe a direita do array para ordenação parcial
| def __simpleSelectionSort(self, array, leftIndex, rightIndex):
"""Implementação do método SelectionSort de forma iterativa
Parametros:
array: Lista a ser ordenada
leftIndex(Opcional): Índice limítrofe a esquerda do array para ordenação parcial
rightIndex(Opcional): Índice limítrofe a direita do array para ordenação parcial
"""
while(leftIndex < rightIndex):
minIndex = leftIndex
for i in range(leftIndex + 1, rightIndex + 1):
if(array[minIndex] > array[i]):
minIndex = i
array[minIndex], array[leftIndex] = array[leftIndex], array[minIndex]
leftIndex = leftIndex + 1 | [
"def",
"__simpleSelectionSort",
"(",
"self",
",",
"array",
",",
"leftIndex",
",",
"rightIndex",
")",
":",
"while",
"(",
"leftIndex",
"<",
"rightIndex",
")",
":",
"minIndex",
"=",
"leftIndex",
"for",
"i",
"in",
"range",
"(",
"leftIndex",
"+",
"1",
",",
"rightIndex",
"+",
"1",
")",
":",
"if",
"(",
"array",
"[",
"minIndex",
"]",
">",
"array",
"[",
"i",
"]",
")",
":",
"minIndex",
"=",
"i",
"array",
"[",
"minIndex",
"]",
",",
"array",
"[",
"leftIndex",
"]",
"=",
"array",
"[",
"leftIndex",
"]",
",",
"array",
"[",
"minIndex",
"]",
"leftIndex",
"=",
"leftIndex",
"+",
"1"
] | [
35,
1
] | [
49,
28
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DireitosGrupoEquipamento.create | (self, authenticated_user) | Insere um novo direito de um grupo de usuário em um grupo de equipamento.
@return: Nothing.
@raise UGrupo.DoesNotExist: Grupo de usuário não cadastrado.
@raise EGrupoNotFoundError: Grupo de equipamento não cadastrado.
@raise DireitoGrupoEquipamentoDuplicatedError: Direito Grupo Equipamento já cadastrado.
@raise GrupoError: Falha ao inserir o direito.
| Insere um novo direito de um grupo de usuário em um grupo de equipamento. | def create(self, authenticated_user):
"""Insere um novo direito de um grupo de usuário em um grupo de equipamento.
@return: Nothing.
@raise UGrupo.DoesNotExist: Grupo de usuário não cadastrado.
@raise EGrupoNotFoundError: Grupo de equipamento não cadastrado.
@raise DireitoGrupoEquipamentoDuplicatedError: Direito Grupo Equipamento já cadastrado.
@raise GrupoError: Falha ao inserir o direito.
"""
self.egrupo = EGrupo.get_by_pk(self.egrupo.id)
try:
self.ugrupo = UGrupo.objects.get(pk=self.ugrupo.id)
if DireitosGrupoEquipamento.objects.filter(egrupo__id=self.egrupo.id, ugrupo__id=self.ugrupo.id).count() > 0:
raise DireitoGrupoEquipamentoDuplicatedError(
None, u'Direito Grupo Equipamento para o grupo de usuário %d e grupo de equipamento %s já cadastrado.' % (self.ugrupo_id, self.egrupo_id))
self.save()
except UGrupo.DoesNotExist, e:
raise e
except DireitoGrupoEquipamentoDuplicatedError, e:
raise e
except Exception, e:
self.log.error(
u'Falha ao inserir o direito do grupo de usuário no grupo de equipamento.')
raise GrupoError(
e, u'Falha ao inserir o direito do grupo de usuário no grupo de equipamento.') | [
"def",
"create",
"(",
"self",
",",
"authenticated_user",
")",
":",
"self",
".",
"egrupo",
"=",
"EGrupo",
".",
"get_by_pk",
"(",
"self",
".",
"egrupo",
".",
"id",
")",
"try",
":",
"self",
".",
"ugrupo",
"=",
"UGrupo",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"ugrupo",
".",
"id",
")",
"if",
"DireitosGrupoEquipamento",
".",
"objects",
".",
"filter",
"(",
"egrupo__id",
"=",
"self",
".",
"egrupo",
".",
"id",
",",
"ugrupo__id",
"=",
"self",
".",
"ugrupo",
".",
"id",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"raise",
"DireitoGrupoEquipamentoDuplicatedError",
"(",
"None",
",",
"u'Direito Grupo Equipamento para o grupo de usuário %d e grupo de equipamento %s já cadastrado.' %",
"(",
"e",
"lf.u",
"g",
"rupo_id, ",
"s",
"lf.e",
"g",
"rupo_id))",
"",
"",
"self",
".",
"save",
"(",
")",
"except",
"UGrupo",
".",
"DoesNotExist",
",",
"e",
":",
"raise",
"e",
"except",
"DireitoGrupoEquipamentoDuplicatedError",
",",
"e",
":",
"raise",
"e",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Falha ao inserir o direito do grupo de usuário no grupo de equipamento.')",
"",
"raise",
"GrupoError",
"(",
"e",
",",
"u'Falha ao inserir o direito do grupo de usuário no grupo de equipamento.')",
""
] | [
465,
4
] | [
493,
95
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
BaseDoc.generate_list | (self, n: int = 1, mask: bool = False, repeat: bool = False) | return doc_list | Gerar uma lista do mesmo documento. | Gerar uma lista do mesmo documento. | def generate_list(self, n: int = 1, mask: bool = False, repeat: bool = False) -> list:
"""Gerar uma lista do mesmo documento."""
doc_list = []
if n <= 0:
return doc_list
for i in range(n):
doc_list.append(self.generate(mask))
while not repeat:
doc_set = set(doc_list)
unique_values = len(doc_set)
if unique_values < n:
doc_list = list(doc_set) + self.generate_list((n - unique_values), mask, repeat)
else:
repeat = True
return doc_list | [
"def",
"generate_list",
"(",
"self",
",",
"n",
":",
"int",
"=",
"1",
",",
"mask",
":",
"bool",
"=",
"False",
",",
"repeat",
":",
"bool",
"=",
"False",
")",
"->",
"list",
":",
"doc_list",
"=",
"[",
"]",
"if",
"n",
"<=",
"0",
":",
"return",
"doc_list",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"doc_list",
".",
"append",
"(",
"self",
".",
"generate",
"(",
"mask",
")",
")",
"while",
"not",
"repeat",
":",
"doc_set",
"=",
"set",
"(",
"doc_list",
")",
"unique_values",
"=",
"len",
"(",
"doc_set",
")",
"if",
"unique_values",
"<",
"n",
":",
"doc_list",
"=",
"list",
"(",
"doc_set",
")",
"+",
"self",
".",
"generate_list",
"(",
"(",
"n",
"-",
"unique_values",
")",
",",
"mask",
",",
"repeat",
")",
"else",
":",
"repeat",
"=",
"True",
"return",
"doc_list"
] | [
19,
4
] | [
38,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
register_document | (folder: str, session, storage, pid_database_engine, poison_pill=PoisonPill()) | return get_article_result_dict(xml_sps) | Registra registra pacotes SPS em uma instância do Kernel e seus
ativos digitais em um object storage. | Registra registra pacotes SPS em uma instância do Kernel e seus
ativos digitais em um object storage. | def register_document(folder: str, session, storage, pid_database_engine, poison_pill=PoisonPill()) -> None:
"""Registra registra pacotes SPS em uma instância do Kernel e seus
ativos digitais em um object storage."""
if poison_pill.poisoned:
return
logger.debug("Starting the import step for '%s' package.", folder)
package_files = files.list_files(folder)
xmls = files.xml_files_list(folder)
if xmls is None or len(xmls) == 0:
raise exceptions.XMLError(
"There is no XML file into package '%s'. Please verify and try later."
% folder
) from None
xml_path = os.path.join(folder, xmls[0])
constructor.article_xml_constructor(xml_path, folder, pid_database_engine, False)
try:
obj_xml = xml.loadToXML(xml_path)
except lxml.etree.ParseError as exc:
raise exceptions.XMLError(
"Could not parse the '%s' file, please validate"
" this file before then try to import again." % xml_path,
) from None
xml_sps = SPS_Package(obj_xml)
pid_v3 = xml_sps.scielo_pid_v3
try:
session.documents.fetch(id=pid_v3)
except DoesNotExist:
pass
else:
logger.debug(
"Document '%s' already exist in kernel. Returning article result information",
pid_v3,
)
return get_article_result_dict(xml_sps)
prefix = xml_sps.media_prefix or ""
url_xml = storage.register(xml_path, prefix)
static_assets, static_additionals = get_document_assets_path(
obj_xml, package_files, folder
)
registered_assets = put_static_assets_into_storage(static_assets, prefix, storage)
for additional_path in static_additionals.values():
storage.register(os.path.join(additional_path), prefix)
renditions = get_document_renditions(folder, prefix, storage)
document = Document(
manifest=manifest.get_document_manifest(
xml_sps, url_xml, registered_assets, renditions
)
)
try:
add_document(session, document)
if renditions:
add_renditions(session, document)
except AlreadyExists as exc:
logger.error(exc)
else:
logger.debug("Document with id '%s' was imported.", document.id())
return get_article_result_dict(xml_sps) | [
"def",
"register_document",
"(",
"folder",
":",
"str",
",",
"session",
",",
"storage",
",",
"pid_database_engine",
",",
"poison_pill",
"=",
"PoisonPill",
"(",
")",
")",
"->",
"None",
":",
"if",
"poison_pill",
".",
"poisoned",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Starting the import step for '%s' package.\"",
",",
"folder",
")",
"package_files",
"=",
"files",
".",
"list_files",
"(",
"folder",
")",
"xmls",
"=",
"files",
".",
"xml_files_list",
"(",
"folder",
")",
"if",
"xmls",
"is",
"None",
"or",
"len",
"(",
"xmls",
")",
"==",
"0",
":",
"raise",
"exceptions",
".",
"XMLError",
"(",
"\"There is no XML file into package '%s'. Please verify and try later.\"",
"%",
"folder",
")",
"from",
"None",
"xml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"xmls",
"[",
"0",
"]",
")",
"constructor",
".",
"article_xml_constructor",
"(",
"xml_path",
",",
"folder",
",",
"pid_database_engine",
",",
"False",
")",
"try",
":",
"obj_xml",
"=",
"xml",
".",
"loadToXML",
"(",
"xml_path",
")",
"except",
"lxml",
".",
"etree",
".",
"ParseError",
"as",
"exc",
":",
"raise",
"exceptions",
".",
"XMLError",
"(",
"\"Could not parse the '%s' file, please validate\"",
"\" this file before then try to import again.\"",
"%",
"xml_path",
",",
")",
"from",
"None",
"xml_sps",
"=",
"SPS_Package",
"(",
"obj_xml",
")",
"pid_v3",
"=",
"xml_sps",
".",
"scielo_pid_v3",
"try",
":",
"session",
".",
"documents",
".",
"fetch",
"(",
"id",
"=",
"pid_v3",
")",
"except",
"DoesNotExist",
":",
"pass",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Document '%s' already exist in kernel. Returning article result information\"",
",",
"pid_v3",
",",
")",
"return",
"get_article_result_dict",
"(",
"xml_sps",
")",
"prefix",
"=",
"xml_sps",
".",
"media_prefix",
"or",
"\"\"",
"url_xml",
"=",
"storage",
".",
"register",
"(",
"xml_path",
",",
"prefix",
")",
"static_assets",
",",
"static_additionals",
"=",
"get_document_assets_path",
"(",
"obj_xml",
",",
"package_files",
",",
"folder",
")",
"registered_assets",
"=",
"put_static_assets_into_storage",
"(",
"static_assets",
",",
"prefix",
",",
"storage",
")",
"for",
"additional_path",
"in",
"static_additionals",
".",
"values",
"(",
")",
":",
"storage",
".",
"register",
"(",
"os",
".",
"path",
".",
"join",
"(",
"additional_path",
")",
",",
"prefix",
")",
"renditions",
"=",
"get_document_renditions",
"(",
"folder",
",",
"prefix",
",",
"storage",
")",
"document",
"=",
"Document",
"(",
"manifest",
"=",
"manifest",
".",
"get_document_manifest",
"(",
"xml_sps",
",",
"url_xml",
",",
"registered_assets",
",",
"renditions",
")",
")",
"try",
":",
"add_document",
"(",
"session",
",",
"document",
")",
"if",
"renditions",
":",
"add_renditions",
"(",
"session",
",",
"document",
")",
"except",
"AlreadyExists",
"as",
"exc",
":",
"logger",
".",
"error",
"(",
"exc",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Document with id '%s' was imported.\"",
",",
"document",
".",
"id",
"(",
")",
")",
"return",
"get_article_result_dict",
"(",
"xml_sps",
")"
] | [
180,
0
] | [
250,
43
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
inicia_log | (logFile, logName = "dmsLibs", stdOut = True, logLevel = logging.DEBUG) | inicia o log do sistema | inicia o log do sistema | def inicia_log(logFile, logName = "dmsLibs", stdOut = True, logLevel = logging.DEBUG):
''' inicia o log do sistema '''
global _log
if stdOut:
_log = iniciaLoggerStdout()
else:
_log = iniciaLogger(logFile, logLevel, logName) | [
"def",
"inicia_log",
"(",
"logFile",
",",
"logName",
"=",
"\"dmsLibs\"",
",",
"stdOut",
"=",
"True",
",",
"logLevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"global",
"_log",
"if",
"stdOut",
":",
"_log",
"=",
"iniciaLoggerStdout",
"(",
")",
"else",
":",
"_log",
"=",
"iniciaLogger",
"(",
"logFile",
",",
"logLevel",
",",
"logName",
")"
] | [
93,
0
] | [
99,
55
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Log.debug | (self, msg, *args) | Imprime uma mensagem de debug no log | Imprime uma mensagem de debug no log | def debug(self, msg, *args):
"""Imprime uma mensagem de debug no log"""
self.__emit(self.logger.debug, msg, args) | [
"def",
"debug",
"(",
"self",
",",
"msg",
",",
"*",
"args",
")",
":",
"self",
".",
"__emit",
"(",
"self",
".",
"logger",
".",
"debug",
",",
"msg",
",",
"args",
")"
] | [
232,
4
] | [
234,
49
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Deque.add_end | (self, element) | Adiciona um elemento no final da fila | Adiciona um elemento no final da fila | def add_end(self, element):
""" Adiciona um elemento no final da fila """
self.deque.append(element)
self._size += 1 | [
"def",
"add_end",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"deque",
".",
"append",
"(",
"element",
")",
"self",
".",
"_size",
"+=",
"1"
] | [
18,
4
] | [
21,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Grafo.adicionaArco | (self, inicio, fim) | Adiciona uma aresta do grafo não direcionado | Adiciona uma aresta do grafo não direcionado | def adicionaArco(self, inicio, fim):
"""Adiciona uma aresta do grafo não direcionado"""
if self.isDirected == False:
self.matrizAdj[inicio][fim] += 1
self.matrizAdj[fim][inicio] += 1
self.listaVertices[fim].distancia = self.listaVertices[inicio].distancia + 1
elif self.isDirected == True:
self.matrizAdj[inicio][fim] += 1
self.numArestas += 1 | [
"def",
"adicionaArco",
"(",
"self",
",",
"inicio",
",",
"fim",
")",
":",
"if",
"self",
".",
"isDirected",
"==",
"False",
":",
"self",
".",
"matrizAdj",
"[",
"inicio",
"]",
"[",
"fim",
"]",
"+=",
"1",
"self",
".",
"matrizAdj",
"[",
"fim",
"]",
"[",
"inicio",
"]",
"+=",
"1",
"self",
".",
"listaVertices",
"[",
"fim",
"]",
".",
"distancia",
"=",
"self",
".",
"listaVertices",
"[",
"inicio",
"]",
".",
"distancia",
"+",
"1",
"elif",
"self",
".",
"isDirected",
"==",
"True",
":",
"self",
".",
"matrizAdj",
"[",
"inicio",
"]",
"[",
"fim",
"]",
"+=",
"1",
"self",
".",
"numArestas",
"+=",
"1"
] | [
30,
4
] | [
39,
28
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update_name | (idt, name, twitch) | return | Função que atualizar o nome e o link com base no id | Função que atualizar o nome e o link com base no id | def update_name(idt, name, twitch):
""" Função que atualizar o nome e o link com base no id"""
# Atualizar nome
upd = (
livecoders.update()
.values(nome=name, twitch=twitch)
.where(livecoders.c.id == idt)
)
engine.execute(upd)
return | [
"def",
"update_name",
"(",
"idt",
",",
"name",
",",
"twitch",
")",
":",
"# Atualizar nome\r",
"upd",
"=",
"(",
"livecoders",
".",
"update",
"(",
")",
".",
"values",
"(",
"nome",
"=",
"name",
",",
"twitch",
"=",
"twitch",
")",
".",
"where",
"(",
"livecoders",
".",
"c",
".",
"id",
"==",
"idt",
")",
")",
"engine",
".",
"execute",
"(",
"upd",
")",
"return"
] | [
92,
0
] | [
103,
10
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
ClassificadorWrapper.kCrossValidation | (self, X, y, numCv:int, doGridSearch:bool) | return round(acc * 100, 2), round(prec * 100, 2), round(recall * 100, 2), round(f1score * 100, 2), round(f1_macro * 100, 2) | Função para realizar o cross validation no data set
Parâmetros:
X:dataframe['tweets']
y:target
numCv: # de folds
doGridSearch: boolean (True para fazer um gridSearch antes do KCrossValidation)
return: acuracidade média dos folds e precisão média dos folds
| Função para realizar o cross validation no data set
Parâmetros:
X:dataframe['tweets']
y:target
numCv: # de folds
doGridSearch: boolean (True para fazer um gridSearch antes do KCrossValidation)
return: acuracidade média dos folds e precisão média dos folds
| def kCrossValidation(self, X, y, numCv:int, doGridSearch:bool):
'''Função para realizar o cross validation no data set
Parâmetros:
X:dataframe['tweets']
y:target
numCv: # de folds
doGridSearch: boolean (True para fazer um gridSearch antes do KCrossValidation)
return: acuracidade média dos folds e precisão média dos folds
'''
model = self.classificador
if doGridSearch:
model = self.getBestModel(X, y)
kf = StratifiedKFold(n_splits= numCv, shuffle= True, random_state= 123)
kf.get_n_splits(X, y) # returns the number of splitting iterations in the cross-validator
tn = 0
fp = 0
fn = 0
tp = 0
f1_macro = 0
for train_index, test_index in kf.split(X, y):
X_test = X.iloc[test_index]
y_test = y.iloc[test_index]
X_train = X.iloc[train_index]
y_train = y.iloc[train_index]
#clonando modelo de input para garantir que cada fold receberá o modelo original sem influência de outros folds
#### Fine tuning process ####
### Extrair features da base de treino ####
modelFold = clone(model)
cf = modelFold.fit(X_train, y_train)
### Extrair features da base de teste ###
tn1, fp1, fn1, tp1 = confusion_matrix(y_test,cf.predict(X_test)).ravel()
tn = tn + tn1
fp = fp + fp1
fn = fn + fn1
tp = tp + tp1
modelFold = None
f1_macro = f1_macro + f1_score(y_test,cf. predict(X_test), average= 'macro')
acc = (tp + tn) / (tn + fp + fn + tp)
f1_macro = f1_macro / 10.0
if(tp == 0 or (tp + fp) ==0): #evitar "nan" nos resultados pela inexistência de tp e fp
prec = 0
recall = 0
f1score = 0
else:
prec = tp / (tp + fp)
recall = tp / (tp + fn)
f1score = 2 * ((prec * recall) / (prec + recall))
print("Mean Accuracy: {0}%".format(round(acc * 100, 2)))
print("Mean Precision: {0}%".format(round(prec * 100, 2)))
print("Mean Recall: {0}%".format(round(recall * 100, 2)))
print("Mean F1-Score: {0}%".format(round(f1score * 100, 2)))
print("Mean Macro-F1-Score: {0}%".format(round(f1_macro * 100, 2)))
return round(acc * 100, 2), round(prec * 100, 2), round(recall * 100, 2), round(f1score * 100, 2), round(f1_macro * 100, 2) | [
"def",
"kCrossValidation",
"(",
"self",
",",
"X",
",",
"y",
",",
"numCv",
":",
"int",
",",
"doGridSearch",
":",
"bool",
")",
":",
"model",
"=",
"self",
".",
"classificador",
"if",
"doGridSearch",
":",
"model",
"=",
"self",
".",
"getBestModel",
"(",
"X",
",",
"y",
")",
"kf",
"=",
"StratifiedKFold",
"(",
"n_splits",
"=",
"numCv",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"123",
")",
"kf",
".",
"get_n_splits",
"(",
"X",
",",
"y",
")",
"# returns the number of splitting iterations in the cross-validator",
"tn",
"=",
"0",
"fp",
"=",
"0",
"fn",
"=",
"0",
"tp",
"=",
"0",
"f1_macro",
"=",
"0",
"for",
"train_index",
",",
"test_index",
"in",
"kf",
".",
"split",
"(",
"X",
",",
"y",
")",
":",
"X_test",
"=",
"X",
".",
"iloc",
"[",
"test_index",
"]",
"y_test",
"=",
"y",
".",
"iloc",
"[",
"test_index",
"]",
"X_train",
"=",
"X",
".",
"iloc",
"[",
"train_index",
"]",
"y_train",
"=",
"y",
".",
"iloc",
"[",
"train_index",
"]",
"#clonando modelo de input para garantir que cada fold receberá o modelo original sem influência de outros folds",
"#### Fine tuning process ####",
"### Extrair features da base de treino ####",
"modelFold",
"=",
"clone",
"(",
"model",
")",
"cf",
"=",
"modelFold",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"### Extrair features da base de teste ###",
"tn1",
",",
"fp1",
",",
"fn1",
",",
"tp1",
"=",
"confusion_matrix",
"(",
"y_test",
",",
"cf",
".",
"predict",
"(",
"X_test",
")",
")",
".",
"ravel",
"(",
")",
"tn",
"=",
"tn",
"+",
"tn1",
"fp",
"=",
"fp",
"+",
"fp1",
"fn",
"=",
"fn",
"+",
"fn1",
"tp",
"=",
"tp",
"+",
"tp1",
"modelFold",
"=",
"None",
"f1_macro",
"=",
"f1_macro",
"+",
"f1_score",
"(",
"y_test",
",",
"cf",
".",
"predict",
"(",
"X_test",
")",
",",
"average",
"=",
"'macro'",
")",
"acc",
"=",
"(",
"tp",
"+",
"tn",
")",
"/",
"(",
"tn",
"+",
"fp",
"+",
"fn",
"+",
"tp",
")",
"f1_macro",
"=",
"f1_macro",
"/",
"10.0",
"if",
"(",
"tp",
"==",
"0",
"or",
"(",
"tp",
"+",
"fp",
")",
"==",
"0",
")",
":",
"#evitar \"nan\" nos resultados pela inexistência de tp e fp",
"prec",
"=",
"0",
"recall",
"=",
"0",
"f1score",
"=",
"0",
"else",
":",
"prec",
"=",
"tp",
"/",
"(",
"tp",
"+",
"fp",
")",
"recall",
"=",
"tp",
"/",
"(",
"tp",
"+",
"fn",
")",
"f1score",
"=",
"2",
"*",
"(",
"(",
"prec",
"*",
"recall",
")",
"/",
"(",
"prec",
"+",
"recall",
")",
")",
"print",
"(",
"\"Mean Accuracy: {0}%\"",
".",
"format",
"(",
"round",
"(",
"acc",
"*",
"100",
",",
"2",
")",
")",
")",
"print",
"(",
"\"Mean Precision: {0}%\"",
".",
"format",
"(",
"round",
"(",
"prec",
"*",
"100",
",",
"2",
")",
")",
")",
"print",
"(",
"\"Mean Recall: {0}%\"",
".",
"format",
"(",
"round",
"(",
"recall",
"*",
"100",
",",
"2",
")",
")",
")",
"print",
"(",
"\"Mean F1-Score: {0}%\"",
".",
"format",
"(",
"round",
"(",
"f1score",
"*",
"100",
",",
"2",
")",
")",
")",
"print",
"(",
"\"Mean Macro-F1-Score: {0}%\"",
".",
"format",
"(",
"round",
"(",
"f1_macro",
"*",
"100",
",",
"2",
")",
")",
")",
"return",
"round",
"(",
"acc",
"*",
"100",
",",
"2",
")",
",",
"round",
"(",
"prec",
"*",
"100",
",",
"2",
")",
",",
"round",
"(",
"recall",
"*",
"100",
",",
"2",
")",
",",
"round",
"(",
"f1score",
"*",
"100",
",",
"2",
")",
",",
"round",
"(",
"f1_macro",
"*",
"100",
",",
"2",
")"
] | [
39,
4
] | [
98,
131
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Settings.__init__ | (self) | Inicializa as configurações estáticas do jogo | Inicializa as configurações estáticas do jogo | def __init__(self):
"""Inicializa as configurações estáticas do jogo"""
# Configurações da tela
self.screen_width = 1200
self.screen_height = 700
colors_screen = {'write': (254, 254, 254), 'black': (0, 0, 0), 'Gray': (230, 230, 230)}
color_screen = colors_screen['black']
self.bg_color = color_screen
# Configuração dos projeteis
self.bullet_width = 5
self.bullet_height = 15
colors_bullet = {'color_write': (253, 254, 254), 'color_black': (0, 0, 0), 'color_red': (254, 0, 0),
'color_blue': (0, 0, 254), 'color_green': (0, 254, 0)
}
color = colors_bullet['color_write']
self.bullet_color = color
self.bullets_allowed = 3
# Configurações da espaçonave
self.ship_limit = 3
# Configurações dos aliens
self.fleet_drop_speed = 10
# A taxa com que a velocidade do jogo aumenta
self.speedup_scale = 1.2
# A taxa com que os pontos para cada alien aumentam
self.score_scale = 1.5
self.initialize_dynamic_settings() | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Configurações da tela",
"self",
".",
"screen_width",
"=",
"1200",
"self",
".",
"screen_height",
"=",
"700",
"colors_screen",
"=",
"{",
"'write'",
":",
"(",
"254",
",",
"254",
",",
"254",
")",
",",
"'black'",
":",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"'Gray'",
":",
"(",
"230",
",",
"230",
",",
"230",
")",
"}",
"color_screen",
"=",
"colors_screen",
"[",
"'black'",
"]",
"self",
".",
"bg_color",
"=",
"color_screen",
"# Configuração dos projeteis",
"self",
".",
"bullet_width",
"=",
"5",
"self",
".",
"bullet_height",
"=",
"15",
"colors_bullet",
"=",
"{",
"'color_write'",
":",
"(",
"253",
",",
"254",
",",
"254",
")",
",",
"'color_black'",
":",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"'color_red'",
":",
"(",
"254",
",",
"0",
",",
"0",
")",
",",
"'color_blue'",
":",
"(",
"0",
",",
"0",
",",
"254",
")",
",",
"'color_green'",
":",
"(",
"0",
",",
"254",
",",
"0",
")",
"}",
"color",
"=",
"colors_bullet",
"[",
"'color_write'",
"]",
"self",
".",
"bullet_color",
"=",
"color",
"self",
".",
"bullets_allowed",
"=",
"3",
"# Configurações da espaçonave",
"self",
".",
"ship_limit",
"=",
"3",
"# Configurações dos aliens",
"self",
".",
"fleet_drop_speed",
"=",
"10",
"# A taxa com que a velocidade do jogo aumenta",
"self",
".",
"speedup_scale",
"=",
"1.2",
"# A taxa com que os pontos para cada alien aumentam",
"self",
".",
"score_scale",
"=",
"1.5",
"self",
".",
"initialize_dynamic_settings",
"(",
")"
] | [
3,
4
] | [
33,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Grafo.bfs | (self, start: int) | return visitados | Executa a busca em largura a partir do vértice start
Args:
start (int): vértice start
Returns:
list: lista com a ordem de vértices visitados
| Executa a busca em largura a partir do vértice start
Args:
start (int): vértice start
Returns:
list: lista com a ordem de vértices visitados
| def bfs(self, start: int) -> list:
"""Executa a busca em largura a partir do vértice start
Args:
start (int): vértice start
Returns:
list: lista com a ordem de vértices visitados
"""
fila = deque()
fila.append(start)
visitados = []
visitados.append(start)
while fila:
u = fila.popleft()
for v in self.adj[u]:
if v not in visitados:
fila.append(v)
visitados.append(v)
return visitados | [
"def",
"bfs",
"(",
"self",
",",
"start",
":",
"int",
")",
"->",
"list",
":",
"fila",
"=",
"deque",
"(",
")",
"fila",
".",
"append",
"(",
"start",
")",
"visitados",
"=",
"[",
"]",
"visitados",
".",
"append",
"(",
"start",
")",
"while",
"fila",
":",
"u",
"=",
"fila",
".",
"popleft",
"(",
")",
"for",
"v",
"in",
"self",
".",
"adj",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"visitados",
":",
"fila",
".",
"append",
"(",
"v",
")",
"visitados",
".",
"append",
"(",
"v",
")",
"return",
"visitados"
] | [
42,
4
] | [
64,
24
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
display_message | () | Exibe uma mensagem simples. | Exibe uma mensagem simples. | def display_message():
"""Exibe uma mensagem simples."""
print('\nHello! I am studing function in Python!\n') | [
"def",
"display_message",
"(",
")",
":",
"print",
"(",
"'\\nHello! I am studing function in Python!\\n'",
")"
] | [
4,
0
] | [
6,
56
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Subsets and Splits