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
list | start_point
list | end_point
list | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
get_number_aliens_x
|
(ai_settings, alien_width)
|
return number_aliens_x
|
Determina o numero de alienigenas que cabem em uma linha.
|
Determina o numero de alienigenas que cabem em uma linha.
|
def get_number_aliens_x(ai_settings, alien_width):
"""Determina o numero de alienigenas que cabem em uma linha."""
available_space_x = ai_settings.screen_width - 2 * alien_width
number_aliens_x = int(available_space_x / (2 * alien_width))
return number_aliens_x
|
[
"def",
"get_number_aliens_x",
"(",
"ai_settings",
",",
"alien_width",
")",
":",
"available_space_x",
"=",
"ai_settings",
".",
"screen_width",
"-",
"2",
"*",
"alien_width",
"number_aliens_x",
"=",
"int",
"(",
"available_space_x",
"/",
"(",
"2",
"*",
"alien_width",
")",
")",
"return",
"number_aliens_x"
] |
[
151,
0
] |
[
155,
26
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
AmbienteResource.handle_post
|
(self, request, user, *args, **kwargs)
|
Trata requisições POST para inserir novo Ambiente.
URL: ambiente/ or ambiente/ipconfig/
|
Trata requisições POST para inserir novo Ambiente.
|
def handle_post(self, request, user, *args, **kwargs):
"""Trata requisições POST para inserir novo Ambiente.
URL: ambiente/ or ambiente/ipconfig/
"""
try:
if not has_perm(user,
AdminPermission.ENVIRONMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION):
return self.not_authorized()
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.')
environment_map = networkapi_map.get('ambiente')
if environment_map is None:
return self.response_error(3, u'Não existe valor para a tag ambiente do XML de requisição.')
link = environment_map.get('link')
if not is_valid_string_maxsize(link, 200, False):
self.log.error(u'Parameter link is invalid. Value: %s', link)
raise InvalidValueError(None, 'link', link)
l3_group_id = environment_map.get('id_grupo_l3')
if not is_valid_int_greater_zero_param(l3_group_id):
self.log.error(
u'The l3_group_id parameter is not a valid value: %s.', l3_group_id)
raise InvalidValueError(None, 'l3_group_id', l3_group_id)
else:
l3_group_id = int(l3_group_id)
logic_environment_id = environment_map.get('id_ambiente_logico')
if not is_valid_int_greater_zero_param(logic_environment_id):
self.log.error(
u'The logic_environment_id parameter is not a valid value: %s.', logic_environment_id)
raise InvalidValueError(
None, 'logic_environment_id', logic_environment_id)
else:
logic_environment_id = int(logic_environment_id)
dc_division_id = environment_map.get('id_divisao')
if not is_valid_int_greater_zero_param(dc_division_id):
self.log.error(
u'The dc_division_id parameter is not a valid value: %s.', dc_division_id)
raise InvalidValueError(None, 'dc_division_id', dc_division_id)
else:
dc_division_id = int(dc_division_id)
filter_id = environment_map.get('id_filter')
if filter_id is not None:
if not is_valid_int_greater_zero_param(filter_id):
self.log.error(
u'Parameter filter_id is invalid. Value: %s.', filter_id)
raise InvalidValueError(None, 'filter_id', filter_id)
acl_path = environment_map.get('acl_path')
if not is_valid_string_maxsize(acl_path, 250, False):
self.log.error(
u'Parameter acl_path is invalid. Value: %s', acl_path)
raise InvalidValueError(None, 'acl_path', acl_path)
ipv4_template = environment_map.get('ipv4_template')
if not is_valid_string_maxsize(ipv4_template, 250, False):
self.log.error(
u'Parameter ipv4_template is invalid. Value: %s', ipv4_template)
raise InvalidValueError(None, 'ipv4_template', ipv4_template)
ipv6_template = environment_map.get('ipv6_template')
if not is_valid_string_maxsize(ipv6_template, 250, False):
self.log.error(
u'Parameter ipv6_template is invalid. Value: %s', ipv6_template)
raise InvalidValueError(None, 'ipv6_template', ipv6_template)
max_num_vlan_1 = environment_map.get('max_num_vlan_1')
min_num_vlan_1 = environment_map.get('min_num_vlan_1')
max_num_vlan_2 = environment_map.get('max_num_vlan_2')
min_num_vlan_2 = environment_map.get('min_num_vlan_2')
# validate max_num_vlan_1 and min_num_vlan_1
if (max_num_vlan_1 is not None and min_num_vlan_1 is None) or (min_num_vlan_1 is not None and max_num_vlan_1 is None):
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
if max_num_vlan_1 is not None and min_num_vlan_1 is not None:
max_num_vlan_1 = int(max_num_vlan_1)
min_num_vlan_1 = int(min_num_vlan_1)
if max_num_vlan_1 < 1 or min_num_vlan_1 < 1:
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
if max_num_vlan_1 <= min_num_vlan_1:
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
else:
max_num_vlan_1 = max_num_vlan_2
min_num_vlan_1 = min_num_vlan_2
# validate max_num_vlan_1 and min_num_vlan_1
# validate max_num_vlan_2 and min_num_vlan_2
if (max_num_vlan_2 is not None and min_num_vlan_2 is None) or (min_num_vlan_2 is not None and max_num_vlan_2 is None):
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
if max_num_vlan_2 is not None and min_num_vlan_2 is not None:
max_num_vlan_2 = int(max_num_vlan_2)
min_num_vlan_2 = int(min_num_vlan_2)
max_num_vlan_1 = int(max_num_vlan_1)
min_num_vlan_1 = int(min_num_vlan_1)
if max_num_vlan_2 < 1 or min_num_vlan_2 < 1:
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
if max_num_vlan_2 <= min_num_vlan_2:
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
else:
max_num_vlan_2 = max_num_vlan_1
min_num_vlan_2 = min_num_vlan_1
# validate max_num_vlan_2 and min_num_vlan_2
vrf = environment_map.get('vrf')
if not is_valid_string_maxsize(vrf, 100, False):
self.log.error(u'Parameter vrf is invalid. Value: %s', vrf)
raise InvalidValueError(None, 'link', vrf)
environment = Ambiente()
environment.grupo_l3 = GrupoL3()
environment.ambiente_logico = AmbienteLogico()
environment.divisao_dc = DivisaoDc()
environment.grupo_l3.id = l3_group_id
environment.ambiente_logico.id = logic_environment_id
environment.divisao_dc.id = dc_division_id
environment.acl_path = fix_acl_path(acl_path)
environment.ipv4_template = ipv4_template
environment.ipv6_template = ipv6_template
environment.max_num_vlan_1 = max_num_vlan_1
environment.min_num_vlan_1 = min_num_vlan_1
environment.max_num_vlan_2 = max_num_vlan_2
environment.min_num_vlan_2 = min_num_vlan_2
environment.vrf = vrf
if filter_id is not None:
environment.filter = Filter()
environment.filter.id = filter_id
environment.link = link
environment.create(user)
# IP Config
ip_config = kwargs.get('ip_config')
# If ip config is set
if ip_config:
# Add this to environment
id_ip_config = environment_map.get('id_ip_config')
# Valid ip config
if not is_valid_int_greater_zero_param(id_ip_config):
raise InvalidValueError(None, 'id_ip_config', id_ip_config)
# Ip config must exists
ip_conf = IPConfig().get_by_pk(id_ip_config)
# Makes the relationship
config = ConfigEnvironment()
config.environment = environment
config.ip_config = ip_conf
config.save()
environment_map = dict()
environment_map['id'] = environment.id
return self.response(dumps_networkapi({'ambiente': environment_map}))
except GrupoError:
return self.response_error(1)
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 FilterNotFoundError, e:
return self.response_error(339)
except IPConfigNotFoundError, e:
return self.response_error(301)
except GrupoL3.DoesNotExist:
return self.response_error(160, l3_group_id)
except AmbienteLogicoNotFoundError:
return self.response_error(162, logic_environment_id)
except AmbienteDuplicatedError:
return self.response_error(219)
except DivisaoDcNotFoundError:
return self.response_error(164, dc_division_id)
except ConfigEnvironmentDuplicateError, e:
return self.response_error(self.CODE_MESSAGE_CONFIG_ENVIRONMENT_ALREADY_EXISTS)
except AmbienteError:
return self.response_error(1)
|
[
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"ENVIRONMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"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.')",
"",
"environment_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'ambiente'",
")",
"if",
"environment_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag ambiente do XML de requisição.')",
"",
"link",
"=",
"environment_map",
".",
"get",
"(",
"'link'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"link",
",",
"200",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter link is invalid. Value: %s'",
",",
"link",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'link'",
",",
"link",
")",
"l3_group_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_grupo_l3'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"l3_group_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The l3_group_id parameter is not a valid value: %s.'",
",",
"l3_group_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'l3_group_id'",
",",
"l3_group_id",
")",
"else",
":",
"l3_group_id",
"=",
"int",
"(",
"l3_group_id",
")",
"logic_environment_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_ambiente_logico'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"logic_environment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The logic_environment_id parameter is not a valid value: %s.'",
",",
"logic_environment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'logic_environment_id'",
",",
"logic_environment_id",
")",
"else",
":",
"logic_environment_id",
"=",
"int",
"(",
"logic_environment_id",
")",
"dc_division_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_divisao'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"dc_division_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The dc_division_id parameter is not a valid value: %s.'",
",",
"dc_division_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'dc_division_id'",
",",
"dc_division_id",
")",
"else",
":",
"dc_division_id",
"=",
"int",
"(",
"dc_division_id",
")",
"filter_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_filter'",
")",
"if",
"filter_id",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"filter_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter filter_id is invalid. Value: %s.'",
",",
"filter_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'filter_id'",
",",
"filter_id",
")",
"acl_path",
"=",
"environment_map",
".",
"get",
"(",
"'acl_path'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"acl_path",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter acl_path is invalid. Value: %s'",
",",
"acl_path",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'acl_path'",
",",
"acl_path",
")",
"ipv4_template",
"=",
"environment_map",
".",
"get",
"(",
"'ipv4_template'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"ipv4_template",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter ipv4_template is invalid. Value: %s'",
",",
"ipv4_template",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ipv4_template'",
",",
"ipv4_template",
")",
"ipv6_template",
"=",
"environment_map",
".",
"get",
"(",
"'ipv6_template'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"ipv6_template",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter ipv6_template is invalid. Value: %s'",
",",
"ipv6_template",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ipv6_template'",
",",
"ipv6_template",
")",
"max_num_vlan_1",
"=",
"environment_map",
".",
"get",
"(",
"'max_num_vlan_1'",
")",
"min_num_vlan_1",
"=",
"environment_map",
".",
"get",
"(",
"'min_num_vlan_1'",
")",
"max_num_vlan_2",
"=",
"environment_map",
".",
"get",
"(",
"'max_num_vlan_2'",
")",
"min_num_vlan_2",
"=",
"environment_map",
".",
"get",
"(",
"'min_num_vlan_2'",
")",
"# validate max_num_vlan_1 and min_num_vlan_1",
"if",
"(",
"max_num_vlan_1",
"is",
"not",
"None",
"and",
"min_num_vlan_1",
"is",
"None",
")",
"or",
"(",
"min_num_vlan_1",
"is",
"not",
"None",
"and",
"max_num_vlan_1",
"is",
"None",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"is",
"not",
"None",
"and",
"min_num_vlan_1",
"is",
"not",
"None",
":",
"max_num_vlan_1",
"=",
"int",
"(",
"max_num_vlan_1",
")",
"min_num_vlan_1",
"=",
"int",
"(",
"min_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"<",
"1",
"or",
"min_num_vlan_1",
"<",
"1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"<=",
"min_num_vlan_1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"else",
":",
"max_num_vlan_1",
"=",
"max_num_vlan_2",
"min_num_vlan_1",
"=",
"min_num_vlan_2",
"# validate max_num_vlan_1 and min_num_vlan_1",
"# validate max_num_vlan_2 and min_num_vlan_2",
"if",
"(",
"max_num_vlan_2",
"is",
"not",
"None",
"and",
"min_num_vlan_2",
"is",
"None",
")",
"or",
"(",
"min_num_vlan_2",
"is",
"not",
"None",
"and",
"max_num_vlan_2",
"is",
"None",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"is",
"not",
"None",
"and",
"min_num_vlan_2",
"is",
"not",
"None",
":",
"max_num_vlan_2",
"=",
"int",
"(",
"max_num_vlan_2",
")",
"min_num_vlan_2",
"=",
"int",
"(",
"min_num_vlan_2",
")",
"max_num_vlan_1",
"=",
"int",
"(",
"max_num_vlan_1",
")",
"min_num_vlan_1",
"=",
"int",
"(",
"min_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"<",
"1",
"or",
"min_num_vlan_2",
"<",
"1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"<=",
"min_num_vlan_2",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"else",
":",
"max_num_vlan_2",
"=",
"max_num_vlan_1",
"min_num_vlan_2",
"=",
"min_num_vlan_1",
"# validate max_num_vlan_2 and min_num_vlan_2",
"vrf",
"=",
"environment_map",
".",
"get",
"(",
"'vrf'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"vrf",
",",
"100",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter vrf is invalid. Value: %s'",
",",
"vrf",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'link'",
",",
"vrf",
")",
"environment",
"=",
"Ambiente",
"(",
")",
"environment",
".",
"grupo_l3",
"=",
"GrupoL3",
"(",
")",
"environment",
".",
"ambiente_logico",
"=",
"AmbienteLogico",
"(",
")",
"environment",
".",
"divisao_dc",
"=",
"DivisaoDc",
"(",
")",
"environment",
".",
"grupo_l3",
".",
"id",
"=",
"l3_group_id",
"environment",
".",
"ambiente_logico",
".",
"id",
"=",
"logic_environment_id",
"environment",
".",
"divisao_dc",
".",
"id",
"=",
"dc_division_id",
"environment",
".",
"acl_path",
"=",
"fix_acl_path",
"(",
"acl_path",
")",
"environment",
".",
"ipv4_template",
"=",
"ipv4_template",
"environment",
".",
"ipv6_template",
"=",
"ipv6_template",
"environment",
".",
"max_num_vlan_1",
"=",
"max_num_vlan_1",
"environment",
".",
"min_num_vlan_1",
"=",
"min_num_vlan_1",
"environment",
".",
"max_num_vlan_2",
"=",
"max_num_vlan_2",
"environment",
".",
"min_num_vlan_2",
"=",
"min_num_vlan_2",
"environment",
".",
"vrf",
"=",
"vrf",
"if",
"filter_id",
"is",
"not",
"None",
":",
"environment",
".",
"filter",
"=",
"Filter",
"(",
")",
"environment",
".",
"filter",
".",
"id",
"=",
"filter_id",
"environment",
".",
"link",
"=",
"link",
"environment",
".",
"create",
"(",
"user",
")",
"# IP Config",
"ip_config",
"=",
"kwargs",
".",
"get",
"(",
"'ip_config'",
")",
"# If ip config is set",
"if",
"ip_config",
":",
"# Add this to environment",
"id_ip_config",
"=",
"environment_map",
".",
"get",
"(",
"'id_ip_config'",
")",
"# Valid ip config",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_ip_config",
")",
":",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_ip_config'",
",",
"id_ip_config",
")",
"# Ip config must exists",
"ip_conf",
"=",
"IPConfig",
"(",
")",
".",
"get_by_pk",
"(",
"id_ip_config",
")",
"# Makes the relationship",
"config",
"=",
"ConfigEnvironment",
"(",
")",
"config",
".",
"environment",
"=",
"environment",
"config",
".",
"ip_config",
"=",
"ip_conf",
"config",
".",
"save",
"(",
")",
"environment_map",
"=",
"dict",
"(",
")",
"environment_map",
"[",
"'id'",
"]",
"=",
"environment",
".",
"id",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'ambiente'",
":",
"environment_map",
"}",
")",
")",
"except",
"GrupoError",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")",
"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",
"FilterNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"339",
")",
"except",
"IPConfigNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"301",
")",
"except",
"GrupoL3",
".",
"DoesNotExist",
":",
"return",
"self",
".",
"response_error",
"(",
"160",
",",
"l3_group_id",
")",
"except",
"AmbienteLogicoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"162",
",",
"logic_environment_id",
")",
"except",
"AmbienteDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"219",
")",
"except",
"DivisaoDcNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"164",
",",
"dc_division_id",
")",
"except",
"ConfigEnvironmentDuplicateError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"self",
".",
"CODE_MESSAGE_CONFIG_ENVIRONMENT_ALREADY_EXISTS",
")",
"except",
"AmbienteError",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] |
[
145,
4
] |
[
374,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
MainAPagar.formAPagar
|
(self)
|
Chamanda de funções localizadas no arquivo financeiro.py na pasta Funcoes
|
Chamanda de funções localizadas no arquivo financeiro.py na pasta Funcoes
|
def formAPagar(self):
self.LimpaFrame(self.fr_Apagar)
super(MainAPagar, self).setFormAPagar(self.fr_Apagar)
self.fr_FormPagar.show()
# Checado ID
self.idCheckAPagar()
""" Chamanda de funções localizadas no arquivo financeiro.py na pasta Funcoes """
# Autocomplete
self.setAutocompleteFinanceiro()
# Data Vencimento e Pagamento com data Atual
self.setDataVencPgto()
# Setando Icones Salvar, Voltar e Imprimir
self.setIconFormFinanceiro()
# Pupulando combobox Repetir
self.cboxRepedir(self.cb_repetir)
# Botao Add Categoria
self.bt_AddCategoriaProduto.clicked.connect(
self.AddCategoriaFinanceiro)
# Botao Cancela add Categoria
self.bt_CancelAddCatergoria.clicked.connect(
partial(self.CalcelAddFinanceiro, self.bt_CancelAddCatergoria,
self.bt_AddCategoriaProduto, self.tx_addCategoria,
self.cb_categoria))
# Validador Campos Float
self.ValidaInputFloat(self.tx_valor)
self.ValidaInputFloat(self.tx_valorPago)
# valida Campo Int
self.ValidaInputInt(self.tx_Id)
""" Fim Chamanda financeiro.py """
""" Chamanda de funções localizadas no arquivo FormaPagamento.py na pasta Funcoes """
# Populando combobox Forma de Pagamento
self.CboxFPagamento(self.cb_formaPagamento)
""" Fim Chamanda FormaPagamento.py """
""" Chamanda de funções localizadas no arquivo categoriaAPagar.py na pasta Funcoes """
# Populando combobox Forma de Pagamento
self.cboxCatAPagar(self.cb_categoria)
""" Fim Chamanda categoriaAPagar.py """
""" Chamanda de funções localizadas no arquivo fornecedor.py na pasta Funcoes """
# Campo Busca por nome e Autocompletar Fornecedor
self.tx_NomeFantasia.textEdited.connect(self.autocompleFornecedor)
self.tx_NomeFantasia.returnPressed.connect(
partial(self.BuscaFornecedorNome, self.tx_descricao))
# Return Press Busca Id Fornecedor
self.tx_Id.returnPressed.connect(
partial(self.BuscaFornecedorId, self.tx_descricao))
""" Fim Chamadas """
# Adicionando Nova Categoria
self.tx_addCategoria.returnPressed.connect(self.CadCategoriraPagar)
# Foco campos ID Cliente
self.tx_Id.setFocus()
# Botao Pagar
self.bt_receber.clicked.connect(self.PagarParcela)
# Imprimir Recibo
self.bt_PrintRecibo.clicked.connect(self.imprimirReciboPag)
# Botao Salvar
self.bt_Salvar.clicked.connect(self.validaCadPagar)
# Botao Voltar
self.bt_Voltar.clicked.connect(self.JanelaAPagar)
|
[
"def",
"formAPagar",
"(",
"self",
")",
":",
"self",
".",
"LimpaFrame",
"(",
"self",
".",
"fr_Apagar",
")",
"super",
"(",
"MainAPagar",
",",
"self",
")",
".",
"setFormAPagar",
"(",
"self",
".",
"fr_Apagar",
")",
"self",
".",
"fr_FormPagar",
".",
"show",
"(",
")",
"# Checado ID",
"self",
".",
"idCheckAPagar",
"(",
")",
"# Autocomplete",
"self",
".",
"setAutocompleteFinanceiro",
"(",
")",
"# Data Vencimento e Pagamento com data Atual",
"self",
".",
"setDataVencPgto",
"(",
")",
"# Setando Icones Salvar, Voltar e Imprimir",
"self",
".",
"setIconFormFinanceiro",
"(",
")",
"# Pupulando combobox Repetir",
"self",
".",
"cboxRepedir",
"(",
"self",
".",
"cb_repetir",
")",
"# Botao Add Categoria",
"self",
".",
"bt_AddCategoriaProduto",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"AddCategoriaFinanceiro",
")",
"# Botao Cancela add Categoria",
"self",
".",
"bt_CancelAddCatergoria",
".",
"clicked",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"CalcelAddFinanceiro",
",",
"self",
".",
"bt_CancelAddCatergoria",
",",
"self",
".",
"bt_AddCategoriaProduto",
",",
"self",
".",
"tx_addCategoria",
",",
"self",
".",
"cb_categoria",
")",
")",
"# Validador Campos Float",
"self",
".",
"ValidaInputFloat",
"(",
"self",
".",
"tx_valor",
")",
"self",
".",
"ValidaInputFloat",
"(",
"self",
".",
"tx_valorPago",
")",
"# valida Campo Int",
"self",
".",
"ValidaInputInt",
"(",
"self",
".",
"tx_Id",
")",
"\"\"\" Fim Chamanda financeiro.py \"\"\"",
"\"\"\" Chamanda de funções localizadas no arquivo FormaPagamento.py na pasta Funcoes \"\"\"",
"# Populando combobox Forma de Pagamento",
"self",
".",
"CboxFPagamento",
"(",
"self",
".",
"cb_formaPagamento",
")",
"\"\"\" Fim Chamanda FormaPagamento.py \"\"\"",
"\"\"\" Chamanda de funções localizadas no arquivo categoriaAPagar.py na pasta Funcoes \"\"\"",
"# Populando combobox Forma de Pagamento",
"self",
".",
"cboxCatAPagar",
"(",
"self",
".",
"cb_categoria",
")",
"\"\"\" Fim Chamanda categoriaAPagar.py \"\"\"",
"\"\"\" Chamanda de funções localizadas no arquivo fornecedor.py na pasta Funcoes \"\"\"",
"# Campo Busca por nome e Autocompletar Fornecedor",
"self",
".",
"tx_NomeFantasia",
".",
"textEdited",
".",
"connect",
"(",
"self",
".",
"autocompleFornecedor",
")",
"self",
".",
"tx_NomeFantasia",
".",
"returnPressed",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"BuscaFornecedorNome",
",",
"self",
".",
"tx_descricao",
")",
")",
"# Return Press Busca Id Fornecedor",
"self",
".",
"tx_Id",
".",
"returnPressed",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"BuscaFornecedorId",
",",
"self",
".",
"tx_descricao",
")",
")",
"\"\"\" Fim Chamadas \"\"\"",
"# Adicionando Nova Categoria",
"self",
".",
"tx_addCategoria",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"CadCategoriraPagar",
")",
"# Foco campos ID Cliente",
"self",
".",
"tx_Id",
".",
"setFocus",
"(",
")",
"# Botao Pagar",
"self",
".",
"bt_receber",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"PagarParcela",
")",
"# Imprimir Recibo",
"self",
".",
"bt_PrintRecibo",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"imprimirReciboPag",
")",
"# Botao Salvar",
"self",
".",
"bt_Salvar",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"validaCadPagar",
")",
"# Botao Voltar",
"self",
".",
"bt_Voltar",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"JanelaAPagar",
")"
] |
[
106,
4
] |
[
183,
57
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
DiarioGC.escrever
|
(self)
|
funcao para escrever um novo pensamento
|
funcao para escrever um novo pensamento
|
def escrever(self):
"""funcao para escrever um novo pensamento"""
self.janela6 = QWidget()
layout = QVBoxLayout()
hl = QFormLayout()
titulo = QLineEdit()
titulo.setAlignment(Qt.AlignCenter)
titulo.setToolTip('*: OBRIGATORIO!')
hl.addRow('Digite um &Nome para o Arquivo: *', titulo)
layout.addLayout(hl)
texto = QTextEdit()
texto.setFont(QFont('cambria', 10))
texto.setAcceptRichText(True)
texto.setAcceptDrops(True)
layout.addWidget(texto)
def guardar():
if isEmpty(titulo.text()):
QMessageBox.warning(self.ferramentas, 'Falha', f'Por favor atribua um nome ao documento antes de guarda-lo!')
warning('ficheiro não nomeado!')
else:
try:
if not path.exists(f'DIARIOGC-{self.nome.text()}/pensamentos'):
mkdir(f'DIARIOGC-{self.nome.text()}/pensamentos')
with open(f'DIARIOGC-{self.nome.text()}/pensamentos/{titulo.text()}.gc-txt', 'w+') as fileCodificado:
doc1, doc2 = encrypt(texto.toPlainText())
fileCodificado.write(str(doc1) + '\n' + str(doc2))
QMessageBox.information(self.ferramentas, 'Concluido', 'Codificação Bem Sucedida..')
self.tab.removeTab(1)
self.diario0()
except Exception as e:
QMessageBox.warning(self.ferramentas, "Falha", f"Lamento, ocorreu um erro inesperado..\n\t{e}")
warning(f'{e}')
hl = QHBoxLayout()
guardarBotao = QPushButton('Guardar')
guardarBotao.setToolTip('CODIFICADO')
guardarBotao.clicked.connect(guardar)
guardarBotao.setDefault(True)
hl.addWidget(guardarBotao)
cancelar = lambda p: self.tab.removeTab(1)
cancelarBotao = QPushButton('Cancelar')
cancelarBotao.clicked.connect(cancelar)
cancelarBotao.setDefault(True)
hl.addWidget(cancelarBotao)
layout.addLayout(hl)
self.janela6.setLayout(layout)
self.tab.addTab(self.janela6, 'Novo-Arquivo')
self.tab.setCurrentWidget(self.janela6)
|
[
"def",
"escrever",
"(",
"self",
")",
":",
"self",
".",
"janela6",
"=",
"QWidget",
"(",
")",
"layout",
"=",
"QVBoxLayout",
"(",
")",
"hl",
"=",
"QFormLayout",
"(",
")",
"titulo",
"=",
"QLineEdit",
"(",
")",
"titulo",
".",
"setAlignment",
"(",
"Qt",
".",
"AlignCenter",
")",
"titulo",
".",
"setToolTip",
"(",
"'*: OBRIGATORIO!'",
")",
"hl",
".",
"addRow",
"(",
"'Digite um &Nome para o Arquivo: *'",
",",
"titulo",
")",
"layout",
".",
"addLayout",
"(",
"hl",
")",
"texto",
"=",
"QTextEdit",
"(",
")",
"texto",
".",
"setFont",
"(",
"QFont",
"(",
"'cambria'",
",",
"10",
")",
")",
"texto",
".",
"setAcceptRichText",
"(",
"True",
")",
"texto",
".",
"setAcceptDrops",
"(",
"True",
")",
"layout",
".",
"addWidget",
"(",
"texto",
")",
"def",
"guardar",
"(",
")",
":",
"if",
"isEmpty",
"(",
"titulo",
".",
"text",
"(",
")",
")",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
".",
"ferramentas",
",",
"'Falha'",
",",
"f'Por favor atribua um nome ao documento antes de guarda-lo!'",
")",
"warning",
"(",
"'ficheiro não nomeado!')",
"",
"else",
":",
"try",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"f'DIARIOGC-{self.nome.text()}/pensamentos'",
")",
":",
"mkdir",
"(",
"f'DIARIOGC-{self.nome.text()}/pensamentos'",
")",
"with",
"open",
"(",
"f'DIARIOGC-{self.nome.text()}/pensamentos/{titulo.text()}.gc-txt'",
",",
"'w+'",
")",
"as",
"fileCodificado",
":",
"doc1",
",",
"doc2",
"=",
"encrypt",
"(",
"texto",
".",
"toPlainText",
"(",
")",
")",
"fileCodificado",
".",
"write",
"(",
"str",
"(",
"doc1",
")",
"+",
"'\\n'",
"+",
"str",
"(",
"doc2",
")",
")",
"QMessageBox",
".",
"information",
"(",
"self",
".",
"ferramentas",
",",
"'Concluido'",
",",
"'Codificação Bem Sucedida..')",
"",
"self",
".",
"tab",
".",
"removeTab",
"(",
"1",
")",
"self",
".",
"diario0",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
".",
"ferramentas",
",",
"\"Falha\"",
",",
"f\"Lamento, ocorreu um erro inesperado..\\n\\t{e}\"",
")",
"warning",
"(",
"f'{e}'",
")",
"hl",
"=",
"QHBoxLayout",
"(",
")",
"guardarBotao",
"=",
"QPushButton",
"(",
"'Guardar'",
")",
"guardarBotao",
".",
"setToolTip",
"(",
"'CODIFICADO'",
")",
"guardarBotao",
".",
"clicked",
".",
"connect",
"(",
"guardar",
")",
"guardarBotao",
".",
"setDefault",
"(",
"True",
")",
"hl",
".",
"addWidget",
"(",
"guardarBotao",
")",
"cancelar",
"=",
"lambda",
"p",
":",
"self",
".",
"tab",
".",
"removeTab",
"(",
"1",
")",
"cancelarBotao",
"=",
"QPushButton",
"(",
"'Cancelar'",
")",
"cancelarBotao",
".",
"clicked",
".",
"connect",
"(",
"cancelar",
")",
"cancelarBotao",
".",
"setDefault",
"(",
"True",
")",
"hl",
".",
"addWidget",
"(",
"cancelarBotao",
")",
"layout",
".",
"addLayout",
"(",
"hl",
")",
"self",
".",
"janela6",
".",
"setLayout",
"(",
"layout",
")",
"self",
".",
"tab",
".",
"addTab",
"(",
"self",
".",
"janela6",
",",
"'Novo-Arquivo'",
")",
"self",
".",
"tab",
".",
"setCurrentWidget",
"(",
"self",
".",
"janela6",
")"
] |
[
325,
4
] |
[
378,
47
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
StockData.stockdata
|
(self, timeframe, date, past_days)
|
Valores normalizados pelo dia
|
Valores normalizados pelo dia
|
def stockdata(self, timeframe, date, past_days):
""" Valores normalizados pelo dia"""
self.past_days = past_days
if not mt5.initialize():
print("initialize() failed")
mt5.shutdown()
try:
date - timedelta(days=past_days)
except:
past_days = past_days.uint
ticks = mt5.copy_rates_range(self.stock, timeframe, date - timedelta(days=past_days), date)
mt5.shutdown()
tick_frame = pd.DataFrame(ticks)
tick_frame.time = pd.to_datetime(tick_frame.time, unit='s')
tick_frame = self.RSI(tick_frame, 2)
tick_frame = self.stochastic(tick_frame, 10)
tick_frame = tick_frame.set_index(tick_frame.time)
tick_frame.drop(['time', 'spread', 'tick_volume'], axis='columns', inplace=True)
self.y_cols = [-1 - list(reversed(tick_frame.columns)).index('high'),
-1 - list(reversed(tick_frame.columns)).index('low')]
self.ticks_frame = tick_frame
ticks = []
periods = self.ticks_frame.index.to_period('d').drop_duplicates().sort_values().values
for s, i in enumerate(periods):
tick = self.ticks_frame.loc[self.ticks_frame.index.to_period('d') == i, :]
tmp = tick.loc[:, ['high', 'low']]
tmp.reset_index(inplace=True, drop=True)
dif = ((tmp.high - tmp.low) * 0.1).astype(int)
tmp['high_d'] = tmp.high - dif
tmp['low_d'] = tmp.low + dif
scaler_x = MinMaxScaler(feature_range=(0, 1))
scaler_y = MinMaxScaler(feature_range=(0, 1))
if s == len(periods) - 2:
self.n_features = int(tick.shape[1])
self.n_obs = int(tick.shape[1] * self.n_in)
_scaler_y = scaler_y
_scaler_x = scaler_x
elif s >= len(periods) - 1:
ind = tick.index.values
tick = _scaler_x.fit_transform(tick.values)
self.scaler_x = _scaler_x
self.scaler_y.fit(tmp.loc[:, ['high_d', 'low_d']].values)
tick = self._series_to_supervised(tick)
pickle.dump(self.scaler_x,
open(r'C:\Users\mueld\Documents\Python_Projects\Stock_1\scaler_X.sav',
'wb'))
pickle.dump(self.scaler_y,
open(r'C:\Users\mueld\Documents\Python_Projects\Stock_1\scaler_Y.sav',
'wb'))
if not tick.empty:
self.ticks_today.append(tick)
self.y_today.append(tmp.iloc[-len(tick):,
[tmp.columns.tolist().index('high_d'),
tmp.columns.tolist().index('low_d')]].values[-len(tick):, :])
self.graf_x.append(ind[-len(tick):])
else:
a = 1
continue
tick = scaler_x.fit_transform(tick.values.astype('float32'))
tick = self._series_to_supervised(tick)
if not tick.empty:
tick.reset_index(inplace=True, drop=True)
ticks.append(tick.values)
_tmp = scaler_y.fit_transform(tmp.iloc[-len(tick):,
[tmp.columns.tolist().index('high_d'),
tmp.columns.tolist().index('low_d')]].values)
self.train_y.append(_tmp)
ticks = np.concatenate(ticks)
# ticks = np.random.permutation(ticks)
self.total_lines = len(ticks)
self.train_y = np.concatenate(self.train_y)
self.train_x = ticks[:, :self.n_obs].reshape(-1, self.n_features, self.n_in)
self.ENVIRONMENT_SHAPE = (self.train_x.shape[1], self.train_x.shape[2])
ticks = np.concatenate(self.ticks_today)
self.y_today = np.concatenate(self.y_today)
self.x_today = ticks[:, self.n_features:].reshape(-1, self.n_features, self.n_in)
self.graf_x = np.concatenate(self.graf_x)
if len(self.train_x) != len(self.train_y):
a = 1
|
[
"def",
"stockdata",
"(",
"self",
",",
"timeframe",
",",
"date",
",",
"past_days",
")",
":",
"self",
".",
"past_days",
"=",
"past_days",
"if",
"not",
"mt5",
".",
"initialize",
"(",
")",
":",
"print",
"(",
"\"initialize() failed\"",
")",
"mt5",
".",
"shutdown",
"(",
")",
"try",
":",
"date",
"-",
"timedelta",
"(",
"days",
"=",
"past_days",
")",
"except",
":",
"past_days",
"=",
"past_days",
".",
"uint",
"ticks",
"=",
"mt5",
".",
"copy_rates_range",
"(",
"self",
".",
"stock",
",",
"timeframe",
",",
"date",
"-",
"timedelta",
"(",
"days",
"=",
"past_days",
")",
",",
"date",
")",
"mt5",
".",
"shutdown",
"(",
")",
"tick_frame",
"=",
"pd",
".",
"DataFrame",
"(",
"ticks",
")",
"tick_frame",
".",
"time",
"=",
"pd",
".",
"to_datetime",
"(",
"tick_frame",
".",
"time",
",",
"unit",
"=",
"'s'",
")",
"tick_frame",
"=",
"self",
".",
"RSI",
"(",
"tick_frame",
",",
"2",
")",
"tick_frame",
"=",
"self",
".",
"stochastic",
"(",
"tick_frame",
",",
"10",
")",
"tick_frame",
"=",
"tick_frame",
".",
"set_index",
"(",
"tick_frame",
".",
"time",
")",
"tick_frame",
".",
"drop",
"(",
"[",
"'time'",
",",
"'spread'",
",",
"'tick_volume'",
"]",
",",
"axis",
"=",
"'columns'",
",",
"inplace",
"=",
"True",
")",
"self",
".",
"y_cols",
"=",
"[",
"-",
"1",
"-",
"list",
"(",
"reversed",
"(",
"tick_frame",
".",
"columns",
")",
")",
".",
"index",
"(",
"'high'",
")",
",",
"-",
"1",
"-",
"list",
"(",
"reversed",
"(",
"tick_frame",
".",
"columns",
")",
")",
".",
"index",
"(",
"'low'",
")",
"]",
"self",
".",
"ticks_frame",
"=",
"tick_frame",
"ticks",
"=",
"[",
"]",
"periods",
"=",
"self",
".",
"ticks_frame",
".",
"index",
".",
"to_period",
"(",
"'d'",
")",
".",
"drop_duplicates",
"(",
")",
".",
"sort_values",
"(",
")",
".",
"values",
"for",
"s",
",",
"i",
"in",
"enumerate",
"(",
"periods",
")",
":",
"tick",
"=",
"self",
".",
"ticks_frame",
".",
"loc",
"[",
"self",
".",
"ticks_frame",
".",
"index",
".",
"to_period",
"(",
"'d'",
")",
"==",
"i",
",",
":",
"]",
"tmp",
"=",
"tick",
".",
"loc",
"[",
":",
",",
"[",
"'high'",
",",
"'low'",
"]",
"]",
"tmp",
".",
"reset_index",
"(",
"inplace",
"=",
"True",
",",
"drop",
"=",
"True",
")",
"dif",
"=",
"(",
"(",
"tmp",
".",
"high",
"-",
"tmp",
".",
"low",
")",
"*",
"0.1",
")",
".",
"astype",
"(",
"int",
")",
"tmp",
"[",
"'high_d'",
"]",
"=",
"tmp",
".",
"high",
"-",
"dif",
"tmp",
"[",
"'low_d'",
"]",
"=",
"tmp",
".",
"low",
"+",
"dif",
"scaler_x",
"=",
"MinMaxScaler",
"(",
"feature_range",
"=",
"(",
"0",
",",
"1",
")",
")",
"scaler_y",
"=",
"MinMaxScaler",
"(",
"feature_range",
"=",
"(",
"0",
",",
"1",
")",
")",
"if",
"s",
"==",
"len",
"(",
"periods",
")",
"-",
"2",
":",
"self",
".",
"n_features",
"=",
"int",
"(",
"tick",
".",
"shape",
"[",
"1",
"]",
")",
"self",
".",
"n_obs",
"=",
"int",
"(",
"tick",
".",
"shape",
"[",
"1",
"]",
"*",
"self",
".",
"n_in",
")",
"_scaler_y",
"=",
"scaler_y",
"_scaler_x",
"=",
"scaler_x",
"elif",
"s",
">=",
"len",
"(",
"periods",
")",
"-",
"1",
":",
"ind",
"=",
"tick",
".",
"index",
".",
"values",
"tick",
"=",
"_scaler_x",
".",
"fit_transform",
"(",
"tick",
".",
"values",
")",
"self",
".",
"scaler_x",
"=",
"_scaler_x",
"self",
".",
"scaler_y",
".",
"fit",
"(",
"tmp",
".",
"loc",
"[",
":",
",",
"[",
"'high_d'",
",",
"'low_d'",
"]",
"]",
".",
"values",
")",
"tick",
"=",
"self",
".",
"_series_to_supervised",
"(",
"tick",
")",
"pickle",
".",
"dump",
"(",
"self",
".",
"scaler_x",
",",
"open",
"(",
"r'C:\\Users\\mueld\\Documents\\Python_Projects\\Stock_1\\scaler_X.sav'",
",",
"'wb'",
")",
")",
"pickle",
".",
"dump",
"(",
"self",
".",
"scaler_y",
",",
"open",
"(",
"r'C:\\Users\\mueld\\Documents\\Python_Projects\\Stock_1\\scaler_Y.sav'",
",",
"'wb'",
")",
")",
"if",
"not",
"tick",
".",
"empty",
":",
"self",
".",
"ticks_today",
".",
"append",
"(",
"tick",
")",
"self",
".",
"y_today",
".",
"append",
"(",
"tmp",
".",
"iloc",
"[",
"-",
"len",
"(",
"tick",
")",
":",
",",
"[",
"tmp",
".",
"columns",
".",
"tolist",
"(",
")",
".",
"index",
"(",
"'high_d'",
")",
",",
"tmp",
".",
"columns",
".",
"tolist",
"(",
")",
".",
"index",
"(",
"'low_d'",
")",
"]",
"]",
".",
"values",
"[",
"-",
"len",
"(",
"tick",
")",
":",
",",
":",
"]",
")",
"self",
".",
"graf_x",
".",
"append",
"(",
"ind",
"[",
"-",
"len",
"(",
"tick",
")",
":",
"]",
")",
"else",
":",
"a",
"=",
"1",
"continue",
"tick",
"=",
"scaler_x",
".",
"fit_transform",
"(",
"tick",
".",
"values",
".",
"astype",
"(",
"'float32'",
")",
")",
"tick",
"=",
"self",
".",
"_series_to_supervised",
"(",
"tick",
")",
"if",
"not",
"tick",
".",
"empty",
":",
"tick",
".",
"reset_index",
"(",
"inplace",
"=",
"True",
",",
"drop",
"=",
"True",
")",
"ticks",
".",
"append",
"(",
"tick",
".",
"values",
")",
"_tmp",
"=",
"scaler_y",
".",
"fit_transform",
"(",
"tmp",
".",
"iloc",
"[",
"-",
"len",
"(",
"tick",
")",
":",
",",
"[",
"tmp",
".",
"columns",
".",
"tolist",
"(",
")",
".",
"index",
"(",
"'high_d'",
")",
",",
"tmp",
".",
"columns",
".",
"tolist",
"(",
")",
".",
"index",
"(",
"'low_d'",
")",
"]",
"]",
".",
"values",
")",
"self",
".",
"train_y",
".",
"append",
"(",
"_tmp",
")",
"ticks",
"=",
"np",
".",
"concatenate",
"(",
"ticks",
")",
"# ticks = np.random.permutation(ticks)",
"self",
".",
"total_lines",
"=",
"len",
"(",
"ticks",
")",
"self",
".",
"train_y",
"=",
"np",
".",
"concatenate",
"(",
"self",
".",
"train_y",
")",
"self",
".",
"train_x",
"=",
"ticks",
"[",
":",
",",
":",
"self",
".",
"n_obs",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"self",
".",
"n_features",
",",
"self",
".",
"n_in",
")",
"self",
".",
"ENVIRONMENT_SHAPE",
"=",
"(",
"self",
".",
"train_x",
".",
"shape",
"[",
"1",
"]",
",",
"self",
".",
"train_x",
".",
"shape",
"[",
"2",
"]",
")",
"ticks",
"=",
"np",
".",
"concatenate",
"(",
"self",
".",
"ticks_today",
")",
"self",
".",
"y_today",
"=",
"np",
".",
"concatenate",
"(",
"self",
".",
"y_today",
")",
"self",
".",
"x_today",
"=",
"ticks",
"[",
":",
",",
"self",
".",
"n_features",
":",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"self",
".",
"n_features",
",",
"self",
".",
"n_in",
")",
"self",
".",
"graf_x",
"=",
"np",
".",
"concatenate",
"(",
"self",
".",
"graf_x",
")",
"if",
"len",
"(",
"self",
".",
"train_x",
")",
"!=",
"len",
"(",
"self",
".",
"train_y",
")",
":",
"a",
"=",
"1"
] |
[
35,
4
] |
[
117,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
ViewTestCase.test_api_can_create_duplicate_agenda
|
(self)
|
Testando a criacao da duplicada via post
|
Testando a criacao da duplicada via post
|
def test_api_can_create_duplicate_agenda(self):
"""Testando a criacao da duplicada via post"""
sala = Sala(name="Av Paulista II")
sala.save()
date_init = '2019-01-05 14:00'
date_end = '2019-01-05 16:00'
agenda_data = {
'titulo':
'Reuniao ABC',
'sala' : sala.id,
'date_init' : date_init,
'date_end' : date_end
}
self.client.post(
reverse('agenda'),
agenda_data,
format="json")
date_end = '2019-01-05 18:00'
agenda_data['date_end'] = date_end
response = self.client.post(
reverse('agenda'),
agenda_data,
format="json")
# #espero erro 400
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
[
"def",
"test_api_can_create_duplicate_agenda",
"(",
"self",
")",
":",
"sala",
"=",
"Sala",
"(",
"name",
"=",
"\"Av Paulista II\"",
")",
"sala",
".",
"save",
"(",
")",
"date_init",
"=",
"'2019-01-05 14:00'",
"date_end",
"=",
"'2019-01-05 16:00'",
"agenda_data",
"=",
"{",
"'titulo'",
":",
"'Reuniao ABC'",
",",
"'sala'",
":",
"sala",
".",
"id",
",",
"'date_init'",
":",
"date_init",
",",
"'date_end'",
":",
"date_end",
"}",
"self",
".",
"client",
".",
"post",
"(",
"reverse",
"(",
"'agenda'",
")",
",",
"agenda_data",
",",
"format",
"=",
"\"json\"",
")",
"date_end",
"=",
"'2019-01-05 18:00'",
"agenda_data",
"[",
"'date_end'",
"]",
"=",
"date_end",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"reverse",
"(",
"'agenda'",
")",
",",
"agenda_data",
",",
"format",
"=",
"\"json\"",
")",
"# #espero erro 400",
"self",
".",
"assertEqual",
"(",
"response",
".",
"status_code",
",",
"status",
".",
"HTTP_400_BAD_REQUEST",
")"
] |
[
97,
4
] |
[
125,
75
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Pesquisador.getFileFromNome
|
(self)
|
return self.__file
|
Se classe for iniciada por nome, busca nome de arquivo em base de dados externa.
Returns:
type: Nome do arquivo.
|
Se classe for iniciada por nome, busca nome de arquivo em base de dados externa.
|
def getFileFromNome(self):
"""Se classe for iniciada por nome, busca nome de arquivo em base de dados externa.
Returns:
type: Nome do arquivo.
"""
if self.__nome is not None:
#----Se o nome foi informado, coloca na forma canônica
nome = self.__nome
nome = nome.upper()
nome = unidecode(nome)
if self.__file is not None:
#----Informando Arquivo e Nome pode ser incompatível. Esqueça o nome.
#LOG.warning("Conflito NOME-FILE, prevalece FILE")
return
else:
df = pd.read_excel(pathHandler("../../data/external/DBnomes.xlsx"))
self.__file = df.loc[df['NOME']==nome, 'FILE'].values[0]
else:
if self.__file is not None:
return
else:
#LOG.error("Nenhum nome ou arquivo definidos")
# Não é possível continuar.
sys.exit(-1)
return self.__file
|
[
"def",
"getFileFromNome",
"(",
"self",
")",
":",
"if",
"self",
".",
"__nome",
"is",
"not",
"None",
":",
"#----Se o nome foi informado, coloca na forma canônica",
"nome",
"=",
"self",
".",
"__nome",
"nome",
"=",
"nome",
".",
"upper",
"(",
")",
"nome",
"=",
"unidecode",
"(",
"nome",
")",
"if",
"self",
".",
"__file",
"is",
"not",
"None",
":",
"#----Informando Arquivo e Nome pode ser incompatível. Esqueça o nome.",
"#LOG.warning(\"Conflito NOME-FILE, prevalece FILE\")",
"return",
"else",
":",
"df",
"=",
"pd",
".",
"read_excel",
"(",
"pathHandler",
"(",
"\"../../data/external/DBnomes.xlsx\"",
")",
")",
"self",
".",
"__file",
"=",
"df",
".",
"loc",
"[",
"df",
"[",
"'NOME'",
"]",
"==",
"nome",
",",
"'FILE'",
"]",
".",
"values",
"[",
"0",
"]",
"else",
":",
"if",
"self",
".",
"__file",
"is",
"not",
"None",
":",
"return",
"else",
":",
"#LOG.error(\"Nenhum nome ou arquivo definidos\")",
"# Não é possível continuar.",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"return",
"self",
".",
"__file"
] |
[
394,
4
] |
[
420,
26
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
maior_primo
|
(num)
|
Parâmetro: número inteiro maior ou igual a 2.
Retorna o maior número primo menor ou igual ao valor dado.
|
Parâmetro: número inteiro maior ou igual a 2.
Retorna o maior número primo menor ou igual ao valor dado.
|
def maior_primo(num):
'''Parâmetro: número inteiro maior ou igual a 2.
Retorna o maior número primo menor ou igual ao valor dado.'''
if num >= 2:
maior_primo = [i for i in range(2, num+1) if primalidade(i)]
return max(maior_primo)
else:
print('Esta função só aceita números inteiros maiores ou iguais a 2. Tente novamente.')
|
[
"def",
"maior_primo",
"(",
"num",
")",
":",
"if",
"num",
">=",
"2",
":",
"maior_primo",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"num",
"+",
"1",
")",
"if",
"primalidade",
"(",
"i",
")",
"]",
"return",
"max",
"(",
"maior_primo",
")",
"else",
":",
"print",
"(",
"'Esta função só aceita números inteiros maiores ou iguais a 2. Tente novamente.')",
""
] |
[
16,
0
] |
[
24,
95
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Sabores.__init__
|
(self)
|
Conterá uma lista de sabores disponiveis.
|
Conterá uma lista de sabores disponiveis.
|
def __init__(self):
"""Conterá uma lista de sabores disponiveis."""
self.lista_sabores = [
'morango', 'coco', 'napolitano', 'amendoas', 'graviola',
'maracujá', 'prestígio', 'mesclado', 'creme', 'flocos'
]
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"lista_sabores",
"=",
"[",
"'morango'",
",",
"'coco'",
",",
"'napolitano'",
",",
"'amendoas'",
",",
"'graviola'",
",",
"'maracujá',",
" ",
"prestígio', ",
"'",
"esclado', ",
"'",
"reme', ",
"'",
"locos'",
"]"
] |
[
55,
4
] |
[
60,
13
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
register_or_update
|
(_id: str, payload: dict, entity_url: str)
|
return response
|
Cadastra ou atualiza uma entidade no Kernel a partir de um payload
|
Cadastra ou atualiza uma entidade no Kernel a partir de um payload
|
def register_or_update(_id: str, payload: dict, entity_url: str):
"""Cadastra ou atualiza uma entidade no Kernel a partir de um payload"""
try:
response = hooks.kernel_connect(
endpoint="{}{}".format(entity_url, _id), method="GET"
)
except requests.exceptions.HTTPError as exc:
logging.info("hooks.kernel_connect HTTPError: %d", exc.response.status_code)
if exc.response.status_code == http.client.NOT_FOUND:
payload = {k: v for k, v in payload.items() if v}
response = hooks.kernel_connect(
endpoint="{}{}".format(entity_url, _id),
method="PUT",
data=payload
)
else:
raise exc
else:
_metadata = response.json()["metadata"]
payload = {
k: v
for k, v in payload.items()
if _metadata.get(k) or _metadata.get(k) == v or v
}
if DeepDiff(_metadata, payload, ignore_order=True):
response = hooks.kernel_connect(
endpoint="{}{}".format(entity_url, _id),
method="PATCH",
data=payload
)
return response
|
[
"def",
"register_or_update",
"(",
"_id",
":",
"str",
",",
"payload",
":",
"dict",
",",
"entity_url",
":",
"str",
")",
":",
"try",
":",
"response",
"=",
"hooks",
".",
"kernel_connect",
"(",
"endpoint",
"=",
"\"{}{}\"",
".",
"format",
"(",
"entity_url",
",",
"_id",
")",
",",
"method",
"=",
"\"GET\"",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"exc",
":",
"logging",
".",
"info",
"(",
"\"hooks.kernel_connect HTTPError: %d\"",
",",
"exc",
".",
"response",
".",
"status_code",
")",
"if",
"exc",
".",
"response",
".",
"status_code",
"==",
"http",
".",
"client",
".",
"NOT_FOUND",
":",
"payload",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"payload",
".",
"items",
"(",
")",
"if",
"v",
"}",
"response",
"=",
"hooks",
".",
"kernel_connect",
"(",
"endpoint",
"=",
"\"{}{}\"",
".",
"format",
"(",
"entity_url",
",",
"_id",
")",
",",
"method",
"=",
"\"PUT\"",
",",
"data",
"=",
"payload",
")",
"else",
":",
"raise",
"exc",
"else",
":",
"_metadata",
"=",
"response",
".",
"json",
"(",
")",
"[",
"\"metadata\"",
"]",
"payload",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"payload",
".",
"items",
"(",
")",
"if",
"_metadata",
".",
"get",
"(",
"k",
")",
"or",
"_metadata",
".",
"get",
"(",
"k",
")",
"==",
"v",
"or",
"v",
"}",
"if",
"DeepDiff",
"(",
"_metadata",
",",
"payload",
",",
"ignore_order",
"=",
"True",
")",
":",
"response",
"=",
"hooks",
".",
"kernel_connect",
"(",
"endpoint",
"=",
"\"{}{}\"",
".",
"format",
"(",
"entity_url",
",",
"_id",
")",
",",
"method",
"=",
"\"PATCH\"",
",",
"data",
"=",
"payload",
")",
"return",
"response"
] |
[
208,
0
] |
[
241,
19
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Knowledge.__setitem__
|
(self, location, value)
|
Define a localidade do quarto.
|
Define a localidade do quarto.
|
def __setitem__(self, location, value):
"""Define a localidade do quarto."""
x, y = location
self._rooms[y][x] = value
|
[
"def",
"__setitem__",
"(",
"self",
",",
"location",
",",
"value",
")",
":",
"x",
",",
"y",
"=",
"location",
"self",
".",
"_rooms",
"[",
"y",
"]",
"[",
"x",
"]",
"=",
"value"
] |
[
259,
2
] |
[
264,
29
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
InterfaceResource.handle_post
|
(self, request, user, *args, **kwargs)
|
Trata as requisições de POST para criar uma nova interface para o equipamento
URL: /interface/
|
Trata as requisições de POST para criar uma nova interface para o equipamento
|
def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para criar uma nova interface para o equipamento
URL: /interface/
"""
# Obtém dados do request e verifica acesso
try:
# Obtém os dados do xml do request
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 "interface"
interface_map = networkapi_map.get('interface')
if interface_map is None:
return self.response_error(3, u'Não existe valor para a tag interface do XML de requisição.')
# Valid id_equipamento value
id_equipamento = interface_map.get('id_equipamento')
if not is_valid_int_greater_zero_param(id_equipamento):
self.log.error(
u'Parameter id_equipamento is invalid. Value: %s', id_equipamento)
raise InvalidValueError(None, 'id_equipamento', id_equipamento)
else:
id_equipamento = int(id_equipamento)
# Check existence
Equipamento.get_by_pk(id_equipamento)
# Verify permission
if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None,
id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION):
return self.not_authorized()
# Valid name value
nome = interface_map.get('nome')
if not is_valid_string_minsize(nome, 1) or not is_valid_string_maxsize(nome, 20):
self.log.error(u'Parameter nome is invalid. Value: %s', nome)
raise InvalidValueError(None, 'nome', nome)
# Valid protegida value
protegida = interface_map.get('protegida')
if not is_valid_boolean_param(protegida):
self.log.error(
u'Parameter protegida is invalid. Value: %s', protegida)
raise InvalidValueError(None, 'protegida', protegida)
else:
protegida = convert_string_or_int_to_boolean(protegida)
# Valid descricao value
descricao = interface_map.get('descricao')
if descricao is not None:
if not is_valid_string_minsize(descricao, 3) or not is_valid_string_maxsize(descricao, 200):
self.log.error(
u'Parameter descricao is invalid. Value: %s', descricao)
raise InvalidValueError(None, 'descricao', descricao)
# Valid "id_ligacao_front" value
id_ligacao_front = interface_map.get('id_ligacao_front')
if id_ligacao_front is not None:
if not is_valid_int_greater_zero_param(id_ligacao_front):
self.log.error(
u'The id_ligacao_front parameter is not a valid value: %s.', id_ligacao_front)
raise InvalidValueError(
None, 'id_ligacao_front', id_ligacao_front)
else:
id_ligacao_front = int(id_ligacao_front)
ligacao_front = Interface(id=id_ligacao_front)
else:
ligacao_front = None
# Valid "id_ligacao_back" value
id_ligacao_back = interface_map.get('id_ligacao_back')
if id_ligacao_back is not None:
if not is_valid_int_greater_zero_param(id_ligacao_back):
self.log.error(
u'The id_ligacao_back parameter is not a valid value: %s.', id_ligacao_back)
raise InvalidValueError(
None, 'id_ligacao_back', id_ligacao_back)
else:
id_ligacao_back = int(id_ligacao_back)
ligacao_back = Interface(id=id_ligacao_back)
else:
ligacao_back = None
tipo_interface = interface_map.get('tipo')
if tipo_interface is None:
tipo_interface = 'Access'
tipo_interface = TipoInterface.get_by_name(tipo_interface)
vlan = interface_map.get('vlan')
# Cria a interface conforme dados recebidos no XML
interface = Interface(
interface=nome,
protegida=protegida,
descricao=descricao,
ligacao_front=ligacao_front,
ligacao_back=ligacao_back,
equipamento=Equipamento(id=id_equipamento),
tipo=tipo_interface,
vlan_nativa=vlan
)
interface.create(user)
networkapi_map = dict()
interface_map = dict()
interface_map['id'] = interface.id
networkapi_map['interface'] = interface_map
return self.response(dumps_networkapi(networkapi_map))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
except EquipamentoNotFoundError:
return self.response_error(117, id_equipamento)
except FrontLinkNotFoundError:
return self.response_error(212)
except BackLinkNotFoundError:
return self.response_error(213)
except InterfaceForEquipmentDuplicatedError:
return self.response_error(187, nome, id_equipamento)
except (InterfaceError, GrupoError, EquipamentoError):
return self.response_error(1)
|
[
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Obtém dados do request e verifica acesso",
"try",
":",
"# Obtém os dados do xml do request",
"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 \"interface\"",
"interface_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'interface'",
")",
"if",
"interface_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag interface do XML de requisição.')",
"",
"# Valid id_equipamento value",
"id_equipamento",
"=",
"interface_map",
".",
"get",
"(",
"'id_equipamento'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_equipamento",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter id_equipamento is invalid. Value: %s'",
",",
"id_equipamento",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_equipamento'",
",",
"id_equipamento",
")",
"else",
":",
"id_equipamento",
"=",
"int",
"(",
"id_equipamento",
")",
"# Check existence",
"Equipamento",
".",
"get_by_pk",
"(",
"id_equipamento",
")",
"# Verify permission",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"None",
",",
"id_equipamento",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"# Valid name value",
"nome",
"=",
"interface_map",
".",
"get",
"(",
"'nome'",
")",
"if",
"not",
"is_valid_string_minsize",
"(",
"nome",
",",
"1",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"nome",
",",
"20",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter nome is invalid. Value: %s'",
",",
"nome",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'nome'",
",",
"nome",
")",
"# Valid protegida value",
"protegida",
"=",
"interface_map",
".",
"get",
"(",
"'protegida'",
")",
"if",
"not",
"is_valid_boolean_param",
"(",
"protegida",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter protegida is invalid. Value: %s'",
",",
"protegida",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'protegida'",
",",
"protegida",
")",
"else",
":",
"protegida",
"=",
"convert_string_or_int_to_boolean",
"(",
"protegida",
")",
"# Valid descricao value",
"descricao",
"=",
"interface_map",
".",
"get",
"(",
"'descricao'",
")",
"if",
"descricao",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_string_minsize",
"(",
"descricao",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"descricao",
",",
"200",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter descricao is invalid. Value: %s'",
",",
"descricao",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'descricao'",
",",
"descricao",
")",
"# Valid \"id_ligacao_front\" value",
"id_ligacao_front",
"=",
"interface_map",
".",
"get",
"(",
"'id_ligacao_front'",
")",
"if",
"id_ligacao_front",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_ligacao_front",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The id_ligacao_front parameter is not a valid value: %s.'",
",",
"id_ligacao_front",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_ligacao_front'",
",",
"id_ligacao_front",
")",
"else",
":",
"id_ligacao_front",
"=",
"int",
"(",
"id_ligacao_front",
")",
"ligacao_front",
"=",
"Interface",
"(",
"id",
"=",
"id_ligacao_front",
")",
"else",
":",
"ligacao_front",
"=",
"None",
"# Valid \"id_ligacao_back\" value",
"id_ligacao_back",
"=",
"interface_map",
".",
"get",
"(",
"'id_ligacao_back'",
")",
"if",
"id_ligacao_back",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_ligacao_back",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The id_ligacao_back parameter is not a valid value: %s.'",
",",
"id_ligacao_back",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_ligacao_back'",
",",
"id_ligacao_back",
")",
"else",
":",
"id_ligacao_back",
"=",
"int",
"(",
"id_ligacao_back",
")",
"ligacao_back",
"=",
"Interface",
"(",
"id",
"=",
"id_ligacao_back",
")",
"else",
":",
"ligacao_back",
"=",
"None",
"tipo_interface",
"=",
"interface_map",
".",
"get",
"(",
"'tipo'",
")",
"if",
"tipo_interface",
"is",
"None",
":",
"tipo_interface",
"=",
"'Access'",
"tipo_interface",
"=",
"TipoInterface",
".",
"get_by_name",
"(",
"tipo_interface",
")",
"vlan",
"=",
"interface_map",
".",
"get",
"(",
"'vlan'",
")",
"# Cria a interface conforme dados recebidos no XML",
"interface",
"=",
"Interface",
"(",
"interface",
"=",
"nome",
",",
"protegida",
"=",
"protegida",
",",
"descricao",
"=",
"descricao",
",",
"ligacao_front",
"=",
"ligacao_front",
",",
"ligacao_back",
"=",
"ligacao_back",
",",
"equipamento",
"=",
"Equipamento",
"(",
"id",
"=",
"id_equipamento",
")",
",",
"tipo",
"=",
"tipo_interface",
",",
"vlan_nativa",
"=",
"vlan",
")",
"interface",
".",
"create",
"(",
"user",
")",
"networkapi_map",
"=",
"dict",
"(",
")",
"interface_map",
"=",
"dict",
"(",
")",
"interface_map",
"[",
"'id'",
"]",
"=",
"interface",
".",
"id",
"networkapi_map",
"[",
"'interface'",
"]",
"=",
"interface_map",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"networkapi_map",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisição.')",
"",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"id_equipamento",
")",
"except",
"FrontLinkNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"212",
")",
"except",
"BackLinkNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"213",
")",
"except",
"InterfaceForEquipmentDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"187",
",",
"nome",
",",
"id_equipamento",
")",
"except",
"(",
"InterfaceError",
",",
"GrupoError",
",",
"EquipamentoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] |
[
106,
4
] |
[
240,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Moderation.reaction_activate
|
(self, ctx, channel: Optional[discord.TextChannel],
msg: str,
emoji: discord.Emoji,
role: discord.Role)
|
Sisteminha básico de reaction roles, atualmente suporta apenas 1 reação por mensagem.
|
Sisteminha básico de reaction roles, atualmente suporta apenas 1 reação por mensagem.
|
async def reaction_activate(self, ctx, channel: Optional[discord.TextChannel],
msg: str,
emoji: discord.Emoji,
role: discord.Role):
"""Sisteminha básico de reaction roles, atualmente suporta apenas 1 reação por mensagem."""
message = await channel.send(msg)
try:
await message.add_reaction(emoji)
except discord.InvalidArgument:
await channel.send("Me desculpe, aparentemente há algo de errado com o seu emoji :sad:")
except discord.NotFound:
await channel.send("Emoji não encontrado")
except discord.HTTPException:
await channel.send("Algo deu errado:(")
else:
write_reaction_messages_to_file(channel.id, message.id, emoji.id, role.id)
await channel.send("Mensagem reagida com sucesso!")
|
[
"async",
"def",
"reaction_activate",
"(",
"self",
",",
"ctx",
",",
"channel",
":",
"Optional",
"[",
"discord",
".",
"TextChannel",
"]",
",",
"msg",
":",
"str",
",",
"emoji",
":",
"discord",
".",
"Emoji",
",",
"role",
":",
"discord",
".",
"Role",
")",
":",
"message",
"=",
"await",
"channel",
".",
"send",
"(",
"msg",
")",
"try",
":",
"await",
"message",
".",
"add_reaction",
"(",
"emoji",
")",
"except",
"discord",
".",
"InvalidArgument",
":",
"await",
"channel",
".",
"send",
"(",
"\"Me desculpe, aparentemente há algo de errado com o seu emoji :sad:\")",
"",
"except",
"discord",
".",
"NotFound",
":",
"await",
"channel",
".",
"send",
"(",
"\"Emoji não encontrado\")",
"",
"except",
"discord",
".",
"HTTPException",
":",
"await",
"channel",
".",
"send",
"(",
"\"Algo deu errado:(\"",
")",
"else",
":",
"write_reaction_messages_to_file",
"(",
"channel",
".",
"id",
",",
"message",
".",
"id",
",",
"emoji",
".",
"id",
",",
"role",
".",
"id",
")",
"await",
"channel",
".",
"send",
"(",
"\"Mensagem reagida com sucesso!\"",
")"
] |
[
156,
4
] |
[
172,
63
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
EletronicDocument.get_ide
|
(self, nfe, operacao)
|
return dict(
tipo_operacao=operacao,
model='nfce' if str(modelo) == '65' else 'nfe',
serie_documento=serie,
numero_controle=num_controle,
numero=numero_nfe,
data_emissao=data_emissao.astimezone(pytz.utc).replace(tzinfo=None),
data_entrada_saida=dt_entrada_saida,
ind_dest=str(indicador_destinatario),
ambiente=ambiente,
finalidade_emissao=finalidade_emissao,
state='imported',
name='Documento Eletrônico: n° ' + str(numero_nfe),
)
|
Importa a seção <ide> do xml
|
Importa a seção <ide> do xml
|
def get_ide(self, nfe, operacao):
''' Importa a seção <ide> do xml'''
ide = nfe.NFe.infNFe.ide
modelo = ide.mod
serie = ide.serie
num_controle = ide.cNF
numero_nfe = ide.nNF
data_emissao = parser.parse(str(ide.dhEmi))
dt_entrada_saida = get(ide, 'dhSaiEnt')
if dt_entrada_saida:
dt_entrada_saida = parser.parse(str(dt_entrada_saida))
dt_entrada_saida = dt_entrada_saida.astimezone(pytz.utc).replace(tzinfo=None)
indicador_destinatario = ide.idDest
ambiente = 'homologacao' if ide.tpAmb == 2\
else 'producao'
finalidade_emissao = str(ide.finNFe)
return dict(
tipo_operacao=operacao,
model='nfce' if str(modelo) == '65' else 'nfe',
serie_documento=serie,
numero_controle=num_controle,
numero=numero_nfe,
data_emissao=data_emissao.astimezone(pytz.utc).replace(tzinfo=None),
data_entrada_saida=dt_entrada_saida,
ind_dest=str(indicador_destinatario),
ambiente=ambiente,
finalidade_emissao=finalidade_emissao,
state='imported',
name='Documento Eletrônico: n° ' + str(numero_nfe),
)
|
[
"def",
"get_ide",
"(",
"self",
",",
"nfe",
",",
"operacao",
")",
":",
"ide",
"=",
"nfe",
".",
"NFe",
".",
"infNFe",
".",
"ide",
"modelo",
"=",
"ide",
".",
"mod",
"serie",
"=",
"ide",
".",
"serie",
"num_controle",
"=",
"ide",
".",
"cNF",
"numero_nfe",
"=",
"ide",
".",
"nNF",
"data_emissao",
"=",
"parser",
".",
"parse",
"(",
"str",
"(",
"ide",
".",
"dhEmi",
")",
")",
"dt_entrada_saida",
"=",
"get",
"(",
"ide",
",",
"'dhSaiEnt'",
")",
"if",
"dt_entrada_saida",
":",
"dt_entrada_saida",
"=",
"parser",
".",
"parse",
"(",
"str",
"(",
"dt_entrada_saida",
")",
")",
"dt_entrada_saida",
"=",
"dt_entrada_saida",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"indicador_destinatario",
"=",
"ide",
".",
"idDest",
"ambiente",
"=",
"'homologacao'",
"if",
"ide",
".",
"tpAmb",
"==",
"2",
"else",
"'producao'",
"finalidade_emissao",
"=",
"str",
"(",
"ide",
".",
"finNFe",
")",
"return",
"dict",
"(",
"tipo_operacao",
"=",
"operacao",
",",
"model",
"=",
"'nfce'",
"if",
"str",
"(",
"modelo",
")",
"==",
"'65'",
"else",
"'nfe'",
",",
"serie_documento",
"=",
"serie",
",",
"numero_controle",
"=",
"num_controle",
",",
"numero",
"=",
"numero_nfe",
",",
"data_emissao",
"=",
"data_emissao",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
",",
"data_entrada_saida",
"=",
"dt_entrada_saida",
",",
"ind_dest",
"=",
"str",
"(",
"indicador_destinatario",
")",
",",
"ambiente",
"=",
"ambiente",
",",
"finalidade_emissao",
"=",
"finalidade_emissao",
",",
"state",
"=",
"'imported'",
",",
"name",
"=",
"'Documento Eletrônico: n° ' +",
"s",
"r(n",
"u",
"mero_nfe),",
"",
"",
")"
] |
[
75,
4
] |
[
106,
9
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
le_textos
|
()
|
return textos
|
A funcao le todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento
|
A funcao le todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento
|
def le_textos():
'''A funcao le todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento'''
i = 1
textos = []
texto = input("Digite o texto " + str(i) +" (aperte enter para sair): ")
while texto:
textos.append(texto)
i += 1
texto = input("Digite o texto " + str(i) +" (aperte enter para sair): ")
return textos
|
[
"def",
"le_textos",
"(",
")",
":",
"i",
"=",
"1",
"textos",
"=",
"[",
"]",
"texto",
"=",
"input",
"(",
"\"Digite o texto \"",
"+",
"str",
"(",
"i",
")",
"+",
"\" (aperte enter para sair): \"",
")",
"while",
"texto",
":",
"textos",
".",
"append",
"(",
"texto",
")",
"i",
"+=",
"1",
"texto",
"=",
"input",
"(",
"\"Digite o texto \"",
"+",
"str",
"(",
"i",
")",
"+",
"\" (aperte enter para sair): \"",
")",
"return",
"textos"
] |
[
16,
0
] |
[
26,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
RestResource.handle_get
|
(self, request, user, *args, **kwargs)
|
return self.not_implemented()
|
Trata uma requisição com o método GET
|
Trata uma requisição com o método GET
|
def handle_get(self, request, user, *args, **kwargs):
"""Trata uma requisição com o método GET"""
return self.not_implemented()
|
[
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"not_implemented",
"(",
")"
] |
[
115,
4
] |
[
117,
37
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
hello
|
(person)
|
return 'Olá {}'.format(person)
|
Exemplo de rota dinâmica.
|
Exemplo de rota dinâmica.
|
def hello(person):
"""Exemplo de rota dinâmica."""
return 'Olá {}'.format(person)
|
[
"def",
"hello",
"(",
"person",
")",
":",
"return",
"'Olá {}'.",
"f",
"ormat(",
"p",
"erson)",
""
] |
[
16,
0
] |
[
18,
35
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
get_nome_socio
|
(id)
|
pega o nome de um livro pelo id.
|
pega o nome de um livro pelo id.
|
def get_nome_socio(id):
"""pega o nome de um livro pelo id."""
if request.method == 'GET':
try:
socio = db.query_bd('select * from socio where id = "%s"' % id)
if socio:
print(socio)
socio = socio[0]
print(socio)
content = {
'nome': socio['nome'],
'status': socio['status']
}
return json.dumps(content)
except Exception as e:
print(e)
return render_template('404.html')
|
[
"def",
"get_nome_socio",
"(",
"id",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"try",
":",
"socio",
"=",
"db",
".",
"query_bd",
"(",
"'select * from socio where id = \"%s\"'",
"%",
"id",
")",
"if",
"socio",
":",
"print",
"(",
"socio",
")",
"socio",
"=",
"socio",
"[",
"0",
"]",
"print",
"(",
"socio",
")",
"content",
"=",
"{",
"'nome'",
":",
"socio",
"[",
"'nome'",
"]",
",",
"'status'",
":",
"socio",
"[",
"'status'",
"]",
"}",
"return",
"json",
".",
"dumps",
"(",
"content",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"render_template",
"(",
"'404.html'",
")"
] |
[
98,
0
] |
[
115,
46
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
GuessTest.test_match_right
|
(self)
|
Cenário 1: Tentativa está totalmente correta
|
Cenário 1: Tentativa está totalmente correta
|
def test_match_right(self):
""" Cenário 1: Tentativa está totalmente correta """
self.assertEqual(guess.match('1234', '1234'), '++++')
|
[
"def",
"test_match_right",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"guess",
".",
"match",
"(",
"'1234'",
",",
"'1234'",
")",
",",
"'++++'",
")"
] |
[
6,
4
] |
[
8,
61
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
dumpDatabase
|
(database, outfile)
|
Efetua o dump de database em outfile
|
Efetua o dump de database em outfile
|
def dumpDatabase(database, outfile):
'Efetua o dump de database em outfile'
if DBConfig['user'] != '':
adminUser = '-u %s' % DBConfig['user']
else:
adminUser = '-u root'
if DBConfig['pass'] != '':
adminPass = '-p%s' % DBConfig['pass']
else:
adminPass = ''
mysqlDump = 'mysqldump %s %s' % (adminUser, adminPass)
basename = outfile.split('.')
basename.reverse()
if len(basename) > 0 and basename[0] == 'sql':
cmd = '%s --opt %s > %s' % (mysqlDump, database, outfile)
elif len(basename) > 1 and basename[1] == 'sql':
if basename[0] == 'gz':
cmd = '%s %s | gzip > %s' % (mysqlDump, database, outfile)
elif basename[0] == 'bz2':
cmd = '%s %s | bzip2 -c > %s' % (mysqlDump, database, outfile)
else:
print 'Tipo de arquivo não confere com os suportados (.sql, .sql.gz, .sql.bz2)'
sys.exit(1)
else:
print 'Tipo de arquivo não confere com os suportados (.sql, .sql.gz, .sql.bz2)'
sys.exit(1)
res = commands.getstatusoutput(cmd)
if res[0] == 0:
print 'Arquivo %s gerado com sucesso!' % outfile
else:
print 'Erro ao gerar arquivo %s: %s' % (outfile, res[1])
|
[
"def",
"dumpDatabase",
"(",
"database",
",",
"outfile",
")",
":",
"if",
"DBConfig",
"[",
"'user'",
"]",
"!=",
"''",
":",
"adminUser",
"=",
"'-u %s'",
"%",
"DBConfig",
"[",
"'user'",
"]",
"else",
":",
"adminUser",
"=",
"'-u root'",
"if",
"DBConfig",
"[",
"'pass'",
"]",
"!=",
"''",
":",
"adminPass",
"=",
"'-p%s'",
"%",
"DBConfig",
"[",
"'pass'",
"]",
"else",
":",
"adminPass",
"=",
"''",
"mysqlDump",
"=",
"'mysqldump %s %s'",
"%",
"(",
"adminUser",
",",
"adminPass",
")",
"basename",
"=",
"outfile",
".",
"split",
"(",
"'.'",
")",
"basename",
".",
"reverse",
"(",
")",
"if",
"len",
"(",
"basename",
")",
">",
"0",
"and",
"basename",
"[",
"0",
"]",
"==",
"'sql'",
":",
"cmd",
"=",
"'%s --opt %s > %s'",
"%",
"(",
"mysqlDump",
",",
"database",
",",
"outfile",
")",
"elif",
"len",
"(",
"basename",
")",
">",
"1",
"and",
"basename",
"[",
"1",
"]",
"==",
"'sql'",
":",
"if",
"basename",
"[",
"0",
"]",
"==",
"'gz'",
":",
"cmd",
"=",
"'%s %s | gzip > %s'",
"%",
"(",
"mysqlDump",
",",
"database",
",",
"outfile",
")",
"elif",
"basename",
"[",
"0",
"]",
"==",
"'bz2'",
":",
"cmd",
"=",
"'%s %s | bzip2 -c > %s'",
"%",
"(",
"mysqlDump",
",",
"database",
",",
"outfile",
")",
"else",
":",
"print",
"'Tipo de arquivo não confere com os suportados (.sql, .sql.gz, .sql.bz2)'",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"print",
"'Tipo de arquivo não confere com os suportados (.sql, .sql.gz, .sql.bz2)'",
"sys",
".",
"exit",
"(",
"1",
")",
"res",
"=",
"commands",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"res",
"[",
"0",
"]",
"==",
"0",
":",
"print",
"'Arquivo %s gerado com sucesso!'",
"%",
"outfile",
"else",
":",
"print",
"'Erro ao gerar arquivo %s: %s'",
"%",
"(",
"outfile",
",",
"res",
"[",
"1",
"]",
")"
] |
[
41,
0
] |
[
71,
64
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Deque.add_first
|
(self, element)
|
Adiciona um elemento no inicio da fila
|
Adiciona um elemento no inicio da fila
|
def add_first(self, element):
""" Adiciona um elemento no inicio da fila """
self.deque.insert(0, element)
self._size += 1
|
[
"def",
"add_first",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"deque",
".",
"insert",
"(",
"0",
",",
"element",
")",
"self",
".",
"_size",
"+=",
"1"
] |
[
12,
4
] |
[
15,
23
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
gerar
|
(quantidade=1,regiao=-1)
|
return valid_cpfs
|
Gera um CPF aleatório.
Retorna uma lista com os CPFs gerados (já checados).
``quantidade`` é um parametro ``int`` que remete a quantos CPFs serão gerados. ``1`` é o valor padrão e será gerado apenas 1 CPF.
``regiao`` é um parametro ``int`` que remete à região cujos CPFs serão gerados. ``-1`` é o valor padrão e será utilizado uma região aleatória.
Regiôes:
-----------
0: Rio Grande do Sul
1: Distrito Federal – Goiás – Mato Grosso – Mato Grosso do Sul – Tocantins
2: Pará – Amazonas – Acre – Amapá – Rondônia – Roraima
3: Ceará – Maranhão – Piauí
4: Pernambuco – Rio Grande do Norte – Paraíba – Alagoas
5: Bahia – Sergipe
6: Minas Gerais
7: Rio de Janeiro – Espírito Santo
8: São Paulo
9: Paraná – Santa Catarina
|
Gera um CPF aleatório.
Retorna uma lista com os CPFs gerados (já checados).
``quantidade`` é um parametro ``int`` que remete a quantos CPFs serão gerados. ``1`` é o valor padrão e será gerado apenas 1 CPF.
``regiao`` é um parametro ``int`` que remete à região cujos CPFs serão gerados. ``-1`` é o valor padrão e será utilizado uma região aleatória.
|
def gerar(quantidade=1,regiao=-1):
"""Gera um CPF aleatório.
Retorna uma lista com os CPFs gerados (já checados).
``quantidade`` é um parametro ``int`` que remete a quantos CPFs serão gerados. ``1`` é o valor padrão e será gerado apenas 1 CPF.
``regiao`` é um parametro ``int`` que remete à região cujos CPFs serão gerados. ``-1`` é o valor padrão e será utilizado uma região aleatória.
Regiôes:
-----------
0: Rio Grande do Sul
1: Distrito Federal – Goiás – Mato Grosso – Mato Grosso do Sul – Tocantins
2: Pará – Amazonas – Acre – Amapá – Rondônia – Roraima
3: Ceará – Maranhão – Piauí
4: Pernambuco – Rio Grande do Norte – Paraíba – Alagoas
5: Bahia – Sergipe
6: Minas Gerais
7: Rio de Janeiro – Espírito Santo
8: São Paulo
9: Paraná – Santa Catarina
"""
import random
valid_rcpf = []
valid_cpfs = []
while len(valid_rcpf) != quantidade:
raw_cpfs = []
for i in range(quantidade):
rcpf = ""
for x in range(11):
if x == 8:
if regiao == -1:
rcpf += str(random.randint(0, 9))
else:
rcpf += str(regiao)
else:
rcpf += str(random.randint(0, 9))
raw_cpfs.append(rcpf)
if checar(raw_cpfs[i],False):
valid_rcpf.append(raw_cpfs[i])
for i in range(len(valid_rcpf)):
valid_cpfs.append(valid_rcpf[i][:3]+"."+valid_rcpf[i][3:6]+"."+valid_rcpf[i][6:9]+"-"+valid_rcpf[i][9::])
return valid_cpfs
|
[
"def",
"gerar",
"(",
"quantidade",
"=",
"1",
",",
"regiao",
"=",
"-",
"1",
")",
":",
"import",
"random",
"valid_rcpf",
"=",
"[",
"]",
"valid_cpfs",
"=",
"[",
"]",
"while",
"len",
"(",
"valid_rcpf",
")",
"!=",
"quantidade",
":",
"raw_cpfs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"quantidade",
")",
":",
"rcpf",
"=",
"\"\"",
"for",
"x",
"in",
"range",
"(",
"11",
")",
":",
"if",
"x",
"==",
"8",
":",
"if",
"regiao",
"==",
"-",
"1",
":",
"rcpf",
"+=",
"str",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
")",
"else",
":",
"rcpf",
"+=",
"str",
"(",
"regiao",
")",
"else",
":",
"rcpf",
"+=",
"str",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
")",
"raw_cpfs",
".",
"append",
"(",
"rcpf",
")",
"if",
"checar",
"(",
"raw_cpfs",
"[",
"i",
"]",
",",
"False",
")",
":",
"valid_rcpf",
".",
"append",
"(",
"raw_cpfs",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"valid_rcpf",
")",
")",
":",
"valid_cpfs",
".",
"append",
"(",
"valid_rcpf",
"[",
"i",
"]",
"[",
":",
"3",
"]",
"+",
"\".\"",
"+",
"valid_rcpf",
"[",
"i",
"]",
"[",
"3",
":",
"6",
"]",
"+",
"\".\"",
"+",
"valid_rcpf",
"[",
"i",
"]",
"[",
"6",
":",
"9",
"]",
"+",
"\"-\"",
"+",
"valid_rcpf",
"[",
"i",
"]",
"[",
"9",
":",
":",
"]",
")",
"return",
"valid_cpfs"
] |
[
63,
0
] |
[
112,
21
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
p_se
|
(p)
|
se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
|
se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
|
def p_se(p):
"""se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
"""
pai = MyNode(name='se', type='SE')
p[0] = pai
filho1 = MyNode(name='SE', type='SE', parent=pai)
filho_se = MyNode(name=p[1], type='SE', parent=filho1)
p[1] = filho1
p[2].parent = pai
filho3 = MyNode(name='ENTAO', type='ENTAO', parent=pai)
filho_entao = MyNode(name=p[3], type='ENTAO', parent=filho3)
p[3] = filho3
p[4].parent = pai
if len(p) == 8:
filho5 = MyNode(name='SENAO', type='SENAO', parent=pai)
filho_senao = MyNode(name=p[5], type='SENAO', parent=filho5)
p[5] = filho5
p[6].parent = pai
filho7 = MyNode(name='FIM', type='FIM', parent=pai)
filho_fim = MyNode(name=p[7], type='FIM', parent=filho7)
p[7] = filho7
else:
filho5 = MyNode(name='fim', type='FIM', parent=pai)
filho_fim = MyNode(name=p[5], type='FIM', parent=filho5)
p[5] = filho5
|
[
"def",
"p_se",
"(",
"p",
")",
":",
"pai",
"=",
"MyNode",
"(",
"name",
"=",
"'se'",
",",
"type",
"=",
"'SE'",
")",
"p",
"[",
"0",
"]",
"=",
"pai",
"filho1",
"=",
"MyNode",
"(",
"name",
"=",
"'SE'",
",",
"type",
"=",
"'SE'",
",",
"parent",
"=",
"pai",
")",
"filho_se",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"type",
"=",
"'SE'",
",",
"parent",
"=",
"filho1",
")",
"p",
"[",
"1",
"]",
"=",
"filho1",
"p",
"[",
"2",
"]",
".",
"parent",
"=",
"pai",
"filho3",
"=",
"MyNode",
"(",
"name",
"=",
"'ENTAO'",
",",
"type",
"=",
"'ENTAO'",
",",
"parent",
"=",
"pai",
")",
"filho_entao",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"3",
"]",
",",
"type",
"=",
"'ENTAO'",
",",
"parent",
"=",
"filho3",
")",
"p",
"[",
"3",
"]",
"=",
"filho3",
"p",
"[",
"4",
"]",
".",
"parent",
"=",
"pai",
"if",
"len",
"(",
"p",
")",
"==",
"8",
":",
"filho5",
"=",
"MyNode",
"(",
"name",
"=",
"'SENAO'",
",",
"type",
"=",
"'SENAO'",
",",
"parent",
"=",
"pai",
")",
"filho_senao",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"5",
"]",
",",
"type",
"=",
"'SENAO'",
",",
"parent",
"=",
"filho5",
")",
"p",
"[",
"5",
"]",
"=",
"filho5",
"p",
"[",
"6",
"]",
".",
"parent",
"=",
"pai",
"filho7",
"=",
"MyNode",
"(",
"name",
"=",
"'FIM'",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"pai",
")",
"filho_fim",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"7",
"]",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"filho7",
")",
"p",
"[",
"7",
"]",
"=",
"filho7",
"else",
":",
"filho5",
"=",
"MyNode",
"(",
"name",
"=",
"'fim'",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"pai",
")",
"filho_fim",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"5",
"]",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"filho5",
")",
"p",
"[",
"5",
"]",
"=",
"filho5"
] |
[
359,
0
] |
[
392,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
get_journal_issn_in_issue
|
(issue)
|
return issue.data.get("issue").get("v35")[0]["_"]
|
Retorna o ISSN ID de um periódico na
perspectiva da issue
|
Retorna o ISSN ID de um periódico na
perspectiva da issue
|
def get_journal_issn_in_issue(issue) -> str:
"""Retorna o ISSN ID de um periódico na
perspectiva da issue"""
return issue.data.get("issue").get("v35")[0]["_"]
|
[
"def",
"get_journal_issn_in_issue",
"(",
"issue",
")",
"->",
"str",
":",
"return",
"issue",
".",
"data",
".",
"get",
"(",
"\"issue\"",
")",
".",
"get",
"(",
"\"v35\"",
")",
"[",
"0",
"]",
"[",
"\"_\"",
"]"
] |
[
200,
0
] |
[
203,
53
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Environment.add_thing
|
(self, thing, location=None)
|
Adicione uma coisa ao ambiente, definindo sua localização. Para
Conveniência, se a coisa é um programa do agente nós fazemos um agente novo
Para ele.
|
Adicione uma coisa ao ambiente, definindo sua localização. Para
Conveniência, se a coisa é um programa do agente nós fazemos um agente novo
Para ele.
|
def add_thing(self, thing, location=None):
"""Adicione uma coisa ao ambiente, definindo sua localização. Para
Conveniência, se a coisa é um programa do agente nós fazemos um agente novo
Para ele."""
if not isinstance(thing, Thing):
thing = Agent(thing)
assert thing not in self.things, "Don't add the same thing twice"
thing.location = location if location is not None else self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
|
[
"def",
"add_thing",
"(",
"self",
",",
"thing",
",",
"location",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"thing",
",",
"Thing",
")",
":",
"thing",
"=",
"Agent",
"(",
"thing",
")",
"assert",
"thing",
"not",
"in",
"self",
".",
"things",
",",
"\"Don't add the same thing twice\"",
"thing",
".",
"location",
"=",
"location",
"if",
"location",
"is",
"not",
"None",
"else",
"self",
".",
"default_location",
"(",
"thing",
")",
"self",
".",
"things",
".",
"append",
"(",
"thing",
")",
"if",
"isinstance",
"(",
"thing",
",",
"Agent",
")",
":",
"thing",
".",
"performance",
"=",
"0",
"self",
".",
"agents",
".",
"append",
"(",
"thing",
")"
] |
[
198,
4
] |
[
209,
37
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Carro.ler_hodometro
|
(self)
|
Exibe uma frase que mostra a milhagem do carro.
|
Exibe uma frase que mostra a milhagem do carro.
|
def ler_hodometro(self):
"""Exibe uma frase que mostra a milhagem do carro."""
print("Esse carro têm " + str(self.leitura_hodometro) +
" quilômetros rodados.")
|
[
"def",
"ler_hodometro",
"(",
"self",
")",
":",
"print",
"(",
"\"Esse carro têm \" ",
" ",
"tr(",
"s",
"elf.",
"l",
"eitura_hodometro)",
" ",
" ",
"\" quilômetros rodados.\")",
""
] |
[
16,
4
] |
[
19,
37
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
EquipamentoAcesso.search
|
(cls, ugroups=None, equipamento=None, protocolo=None)
|
Efetua a pesquisa das informações de acesso a equipamentos
@return: Um queryset contendo as informações de aceso a equipamentos cadastrados
@raise EquipamentoError: Falha ao pesquisar as informações de acesso a equipamentos.
|
Efetua a pesquisa das informações de acesso a equipamentos
|
def search(cls, ugroups=None, equipamento=None, protocolo=None):
"""Efetua a pesquisa das informações de acesso a equipamentos
@return: Um queryset contendo as informações de aceso a equipamentos cadastrados
@raise EquipamentoError: Falha ao pesquisar as informações de acesso a equipamentos.
"""
try:
results = EquipamentoAcesso.objects.all()
if ugroups is not None:
results = results.filter(
equipamento__grupos__direitosgrupoequipamento__ugrupo__in=ugroups, equipamento__grupos__direitosgrupoequipamento__escrita='1')
if equipamento is not None:
results = results.filter(equipamento=equipamento)
if protocolo is not None:
results = results.filter(tipo_acesso__protocolo=protocolo)
return results
except Exception as e:
cls.log.error(
u'Falha ao pesquisar as informações de acesso a equipamentos.')
raise EquipamentoError(
e, u'Falha ao pesquisar oas informações de acesso a equipamentos.')
|
[
"def",
"search",
"(",
"cls",
",",
"ugroups",
"=",
"None",
",",
"equipamento",
"=",
"None",
",",
"protocolo",
"=",
"None",
")",
":",
"try",
":",
"results",
"=",
"EquipamentoAcesso",
".",
"objects",
".",
"all",
"(",
")",
"if",
"ugroups",
"is",
"not",
"None",
":",
"results",
"=",
"results",
".",
"filter",
"(",
"equipamento__grupos__direitosgrupoequipamento__ugrupo__in",
"=",
"ugroups",
",",
"equipamento__grupos__direitosgrupoequipamento__escrita",
"=",
"'1'",
")",
"if",
"equipamento",
"is",
"not",
"None",
":",
"results",
"=",
"results",
".",
"filter",
"(",
"equipamento",
"=",
"equipamento",
")",
"if",
"protocolo",
"is",
"not",
"None",
":",
"results",
"=",
"results",
".",
"filter",
"(",
"tipo_acesso__protocolo",
"=",
"protocolo",
")",
"return",
"results",
"except",
"Exception",
"as",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao pesquisar as informações de acesso a equipamentos.')",
"",
"raise",
"EquipamentoError",
"(",
"e",
",",
"u'Falha ao pesquisar oas informações de acesso a equipamentos.')",
""
] |
[
1696,
4
] |
[
1718,
85
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
DType21.hostname
|
(self)
|
return bin2str(self.data[:16])
|
Retorna o campo HOSTNAME que contém o 'Unit Hostname
|
Retorna o campo HOSTNAME que contém o 'Unit Hostname
|
def hostname(self) -> str:
"""Retorna o campo HOSTNAME que contém o 'Unit Hostname'"""
return bin2str(self.data[:16])
|
[
"def",
"hostname",
"(",
"self",
")",
"->",
"str",
":",
"return",
"bin2str",
"(",
"self",
".",
"data",
"[",
":",
"16",
"]",
")"
] |
[
456,
4
] |
[
458,
38
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Funcionario.receber_aumento
|
(self, aumento=5000)
|
Soma 5 mil dólares ao salário anual.
|
Soma 5 mil dólares ao salário anual.
|
def receber_aumento(self, aumento=5000):
"""Soma 5 mil dólares ao salário anual."""
self.salario += aumento
|
[
"def",
"receber_aumento",
"(",
"self",
",",
"aumento",
"=",
"5000",
")",
":",
"self",
".",
"salario",
"+=",
"aumento"
] |
[
10,
4
] |
[
12,
31
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
all_indexes
|
(sequencia, valor)
|
Retorna uma lista com todos os índices
de <valor> encontrados em <sequencia>
Se não for encontrado nenhum, retorna
uma lista vazia []
|
Retorna uma lista com todos os índices
de <valor> encontrados em <sequencia>
|
def all_indexes(sequencia, valor):
"""Retorna uma lista com todos os índices
de <valor> encontrados em <sequencia>
Se não for encontrado nenhum, retorna
uma lista vazia []
"""
pass
|
[
"def",
"all_indexes",
"(",
"sequencia",
",",
"valor",
")",
":",
"pass"
] |
[
21,
0
] |
[
28,
8
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
potencia_de_2
|
()
|
Lê um número e retorna a entrada caso
ela seja potência de 2, caso não seja, não
faz retorno
str -> int
|
Lê um número e retorna a entrada caso
ela seja potência de 2, caso não seja, não
faz retorno
|
def potencia_de_2():
""" Lê um número e retorna a entrada caso
ela seja potência de 2, caso não seja, não
faz retorno
str -> int
"""
permanecer = True
#Laço infinito para prender o usuário caso não
#digite a informação que se pede
while permanecer:
#O laço funciona com a saída explicita
#e a permanencia implicita na condicional
#que é disparada ao achar um caracter inválido
permanecer = False
errado = False
numero = str(input("Digite um número inteiro : "))
#Caracteres esperados na entrada do usuario
numeros = ["0","1","2","3","4","5","6","7","8","9"]
#Conferindo entrada vazia
if len(numero) != 0:
#Conferindo número negativo
if numero[0] == "-":
if len(numero) > 1:
for index in range(1,len(numero)):
if numero[index] not in numeros:
errado = True
else:
errado = True
else:
#Conferindo números positivos
for num in numero:
if num not in numeros:
errado = True
else:
errado = True
if errado:
permanecer = True
print("Entrada inválida. ",end="")
#Convertendo a entrada para inteiro
#Conferindo se a entrada é potencia de 2
numero = int(numero)
dividido = numero
while True:
resto = dividido % 2
dividido = dividido / 2
if dividido == 1:
return numero
elif resto > 0:
break
|
[
"def",
"potencia_de_2",
"(",
")",
":",
"permanecer",
"=",
"True",
"#Laço infinito para prender o usuário caso não",
"#digite a informação que se pede",
"while",
"permanecer",
":",
"#O laço funciona com a saída explicita",
"#e a permanencia implicita na condicional",
"#que é disparada ao achar um caracter inválido",
"permanecer",
"=",
"False",
"errado",
"=",
"False",
"numero",
"=",
"str",
"(",
"input",
"(",
"\"Digite um número inteiro : \")",
")",
"",
"#Caracteres esperados na entrada do usuario",
"numeros",
"=",
"[",
"\"0\"",
",",
"\"1\"",
",",
"\"2\"",
",",
"\"3\"",
",",
"\"4\"",
",",
"\"5\"",
",",
"\"6\"",
",",
"\"7\"",
",",
"\"8\"",
",",
"\"9\"",
"]",
"#Conferindo entrada vazia",
"if",
"len",
"(",
"numero",
")",
"!=",
"0",
":",
"#Conferindo número negativo",
"if",
"numero",
"[",
"0",
"]",
"==",
"\"-\"",
":",
"if",
"len",
"(",
"numero",
")",
">",
"1",
":",
"for",
"index",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"numero",
")",
")",
":",
"if",
"numero",
"[",
"index",
"]",
"not",
"in",
"numeros",
":",
"errado",
"=",
"True",
"else",
":",
"errado",
"=",
"True",
"else",
":",
"#Conferindo números positivos",
"for",
"num",
"in",
"numero",
":",
"if",
"num",
"not",
"in",
"numeros",
":",
"errado",
"=",
"True",
"else",
":",
"errado",
"=",
"True",
"if",
"errado",
":",
"permanecer",
"=",
"True",
"print",
"(",
"\"Entrada inválida. \",",
"e",
"nd=",
"\"",
"\")",
" ",
"#Convertendo a entrada para inteiro ",
"#Conferindo se a entrada é potencia de 2",
"numero",
"=",
"int",
"(",
"numero",
")",
"dividido",
"=",
"numero",
"while",
"True",
":",
"resto",
"=",
"dividido",
"%",
"2",
"dividido",
"=",
"dividido",
"/",
"2",
"if",
"dividido",
"==",
"1",
":",
"return",
"numero",
"elif",
"resto",
">",
"0",
":",
"break"
] |
[
7,
0
] |
[
63,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Bau.remover_brinquedo
|
(self, brinquedo)
|
Remove um Brinquedo da lista de brinquedos do seu tipo ou remove um tipo de Brinquedo.
|
Remove um Brinquedo da lista de brinquedos do seu tipo ou remove um tipo de Brinquedo.
|
def remover_brinquedo(self, brinquedo):
"""Remove um Brinquedo da lista de brinquedos do seu tipo ou remove um tipo de Brinquedo."""
if len(self.brinquedos[brinquedo.nome]) <= 1:
del self.brinquedos[brinquedo.nome]
else:
self.brinquedos[brinquedo.nome].remove(brinquedo)
|
[
"def",
"remover_brinquedo",
"(",
"self",
",",
"brinquedo",
")",
":",
"if",
"len",
"(",
"self",
".",
"brinquedos",
"[",
"brinquedo",
".",
"nome",
"]",
")",
"<=",
"1",
":",
"del",
"self",
".",
"brinquedos",
"[",
"brinquedo",
".",
"nome",
"]",
"else",
":",
"self",
".",
"brinquedos",
"[",
"brinquedo",
".",
"nome",
"]",
".",
"remove",
"(",
"brinquedo",
")"
] |
[
35,
4
] |
[
41,
61
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
CNS._generate_second_case
|
(self, cns: list)
|
return self._change_cns(cns, 15 - diff, diff)
|
Gera um CNS válido para os casos que se inicia com 7, 8 ou 9.
|
Gera um CNS válido para os casos que se inicia com 7, 8 ou 9.
|
def _generate_second_case(self, cns: list) -> list:
"""Gera um CNS válido para os casos que se inicia com 7, 8 ou 9."""
# Gerar os próximos 14 dígitos
cns = cns + [str(sample(list(range(10)), 1)[0]) for i in range(14)]
sum = self._sum_algorithm(cns)
rest = sum % 11
if rest == 0:
return cns
# Resto para o próximo múltiplo de 11
diff = 11 - rest
# Verificar qual é o mais próximo
return self._change_cns(cns, 15 - diff, diff)
|
[
"def",
"_generate_second_case",
"(",
"self",
",",
"cns",
":",
"list",
")",
"->",
"list",
":",
"# Gerar os próximos 14 dígitos",
"cns",
"=",
"cns",
"+",
"[",
"str",
"(",
"sample",
"(",
"list",
"(",
"range",
"(",
"10",
")",
")",
",",
"1",
")",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"14",
")",
"]",
"sum",
"=",
"self",
".",
"_sum_algorithm",
"(",
"cns",
")",
"rest",
"=",
"sum",
"%",
"11",
"if",
"rest",
"==",
"0",
":",
"return",
"cns",
"# Resto para o próximo múltiplo de 11",
"diff",
"=",
"11",
"-",
"rest",
"# Verificar qual é o mais próximo",
"return",
"self",
".",
"_change_cns",
"(",
"cns",
",",
"15",
"-",
"diff",
",",
"diff",
")"
] |
[
80,
4
] |
[
94,
53
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
get_formatted_name
|
(first_name, last_name)
|
return full_name.title()
|
Devolve um nome completo formatado.
|
Devolve um nome completo formatado.
|
def get_formatted_name(first_name, last_name):
"""Devolve um nome completo formatado."""
full_name = first_name + ' ' + last_name
return full_name.title()
|
[
"def",
"get_formatted_name",
"(",
"first_name",
",",
"last_name",
")",
":",
"full_name",
"=",
"first_name",
"+",
"' '",
"+",
"last_name",
"return",
"full_name",
".",
"title",
"(",
")"
] |
[
2,
0
] |
[
5,
28
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
put_static_assets_into_storage
|
(
assets: dict, prefix: str, storage, ignore_missing_assets: bool = True
)
|
return _assets
|
Armazena os arquivos assets em um object storage
|
Armazena os arquivos assets em um object storage
|
def put_static_assets_into_storage(
assets: dict, prefix: str, storage, ignore_missing_assets: bool = True
) -> List[dict]:
"""Armazena os arquivos assets em um object storage"""
_assets = []
for asset_name, asset_path in assets.items():
if not asset_path and ignore_missing_assets:
continue
_assets.append(
{"asset_id": asset_name, "asset_url": storage.register(asset_path, prefix)}
)
return _assets
|
[
"def",
"put_static_assets_into_storage",
"(",
"assets",
":",
"dict",
",",
"prefix",
":",
"str",
",",
"storage",
",",
"ignore_missing_assets",
":",
"bool",
"=",
"True",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"_assets",
"=",
"[",
"]",
"for",
"asset_name",
",",
"asset_path",
"in",
"assets",
".",
"items",
"(",
")",
":",
"if",
"not",
"asset_path",
"and",
"ignore_missing_assets",
":",
"continue",
"_assets",
".",
"append",
"(",
"{",
"\"asset_id\"",
":",
"asset_name",
",",
"\"asset_url\"",
":",
"storage",
".",
"register",
"(",
"asset_path",
",",
"prefix",
")",
"}",
")",
"return",
"_assets"
] |
[
128,
0
] |
[
142,
18
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Car.get_descriptive_name
|
(self)
|
return long_name
|
Retonra o nome do veículo de modo formatado.
|
Retonra o nome do veículo de modo formatado.
|
def get_descriptive_name(self):
""" Retonra o nome do veículo de modo formatado."""
long_name = str(self.year) + ', ' + self.make.title() + ', ' + self.model.title()
return long_name
|
[
"def",
"get_descriptive_name",
"(",
"self",
")",
":",
"long_name",
"=",
"str",
"(",
"self",
".",
"year",
")",
"+",
"', '",
"+",
"self",
".",
"make",
".",
"title",
"(",
")",
"+",
"', '",
"+",
"self",
".",
"model",
".",
"title",
"(",
")",
"return",
"long_name"
] |
[
18,
4
] |
[
21,
24
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
RoteiroResource.handle_delete
|
(self, request, user, *args, **kwargs)
|
Trata as requisições de DELETE para remover um Roteiro.
URL: roteiro/<id_roteiro>/
|
Trata as requisições de DELETE para remover um Roteiro.
|
def handle_delete(self, request, user, *args, **kwargs):
"""Trata as requisições de DELETE para remover um Roteiro.
URL: roteiro/<id_roteiro>/
"""
try:
script_id = kwargs.get('id_roteiro')
if script_id is None:
return self.response_error(233)
if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
Roteiro.remove(user, script_id)
return self.response(dumps_networkapi({}))
except RoteiroNotFoundError:
return self.response_error(165, script_id)
except RoteiroHasEquipamentoError:
return self.response_error(197, script_id)
except (RoteiroError, GrupoError):
return self.response_error(1)
|
[
"def",
"handle_delete",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"script_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_roteiro'",
")",
"if",
"script_id",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"233",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"SCRIPT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"Roteiro",
".",
"remove",
"(",
"user",
",",
"script_id",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"RoteiroNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"165",
",",
"script_id",
")",
"except",
"RoteiroHasEquipamentoError",
":",
"return",
"self",
".",
"response_error",
"(",
"197",
",",
"script_id",
")",
"except",
"(",
"RoteiroError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] |
[
216,
4
] |
[
238,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
ListaBemLoka.__rshift__
|
(self, pos)
|
return self.pop(pos)
|
Remove um item com >>
|
Remove um item com >>
|
def __rshift__(self, pos):
"""Remove um item com >>"""
return self.pop(pos)
|
[
"def",
"__rshift__",
"(",
"self",
",",
"pos",
")",
":",
"return",
"self",
".",
"pop",
"(",
"pos",
")"
] |
[
9,
4
] |
[
11,
28
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
ServiceConfiguration.criar_arquivo_configuracao
|
(self)
|
Cria o arquivo de configuração caso o mesmo não exista
|
Cria o arquivo de configuração caso o mesmo não exista
|
def criar_arquivo_configuracao(self):
'''Cria o arquivo de configuração caso o mesmo não exista'''
path = os.getcwd + "/configuration.conf"
if (not os.path.exists(path)):
Utilidades().gravar_arquivo_configuracao(
Utilidades().get_initial_configuration())
|
[
"def",
"criar_arquivo_configuracao",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"getcwd",
"+",
"\"/configuration.conf\"",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"Utilidades",
"(",
")",
".",
"gravar_arquivo_configuracao",
"(",
"Utilidades",
"(",
")",
".",
"get_initial_configuration",
"(",
")",
")"
] |
[
96,
4
] |
[
101,
57
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
find_num_
|
(num)
|
return n if n != "" else 0
|
Função para encontrar números dentro de iteráveis
Ela também funciona para floats
Retornará uma string somente com números
Se não encontrar nenhum número, retornará 0
|
Função para encontrar números dentro de iteráveis
Ela também funciona para floats
Retornará uma string somente com números
Se não encontrar nenhum número, retornará 0
|
def find_num_(num):
"""Função para encontrar números dentro de iteráveis
Ela também funciona para floats
Retornará uma string somente com números
Se não encontrar nenhum número, retornará 0"""
num = str(num)
n = "".join([char
if (
char.isnumeric()
or char == '.'
and num[index-1].isnumeric()
and num[index+1].isnumeric()
)
else ""
for index, char in enumerate(num)
])
return n if n != "" else 0
|
[
"def",
"find_num_",
"(",
"num",
")",
":",
"num",
"=",
"str",
"(",
"num",
")",
"n",
"=",
"\"\"",
".",
"join",
"(",
"[",
"char",
"if",
"(",
"char",
".",
"isnumeric",
"(",
")",
"or",
"char",
"==",
"'.'",
"and",
"num",
"[",
"index",
"-",
"1",
"]",
".",
"isnumeric",
"(",
")",
"and",
"num",
"[",
"index",
"+",
"1",
"]",
".",
"isnumeric",
"(",
")",
")",
"else",
"\"\"",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"num",
")",
"]",
")",
"return",
"n",
"if",
"n",
"!=",
"\"\"",
"else",
"0"
] |
[
31,
0
] |
[
47,
30
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
plot_serie_barra
|
(Name, resps, exata, plist)
|
Plota a evolucao da intensidade de cada fonte em funcao do refinamento da malha, plota tambem uma linha que
contem a resposta exata
|
Plota a evolucao da intensidade de cada fonte em funcao do refinamento da malha, plota tambem uma linha que
contem a resposta exata
|
def plot_serie_barra(Name, resps, exata, plist):
''''Plota a evolucao da intensidade de cada fonte em funcao do refinamento da malha, plota tambem uma linha que
contem a resposta exata '''
width = 0.35
matrix = resps[0]
for i in range(1, len(resps)):
matrix = np.vstack((matrix, resps[i]))
for i in range(len(plist)):
plt.clf()
data = matrix[:, i:i + 1].reshape(5)
data = pd.DataFrame({
'Intensidade calculada': data,
'Intensidade exata': np.ones(len(data)) * exata[i]
})
my_colors = list(
islice(cycle(['darkturquoise', 'deepskyblue', 'darkcyan', 'lightseagreen', 'c']), None, len(data)))
data['Intensidade calculada'].plot(kind='bar', width=width, color=my_colors,
title='Evolução da intensidade com N, {}, P = {}'.format(Name, plist[i]), legend=True)
data['Intensidade exata'].plot()
ax = plt.gca()
ax.set_xticklabels(('128', '256', '512', '1024', '2048'))
# ax.set_xticklabels(('128', '256', '512'))
ax.set_xlabel("N", fontsize=12)
ax.set_ylabel("Intensidade da fonte", fontsize=12)
ax.legend(labels=['Intensidade exata', 'Intensidade calculada'], loc='lower left')
# plt.show()
plt.savefig('{}.png'.format('plots/barras_pp' + Name + 'P=' + str(plist[i])))
|
[
"def",
"plot_serie_barra",
"(",
"Name",
",",
"resps",
",",
"exata",
",",
"plist",
")",
":",
"width",
"=",
"0.35",
"matrix",
"=",
"resps",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"resps",
")",
")",
":",
"matrix",
"=",
"np",
".",
"vstack",
"(",
"(",
"matrix",
",",
"resps",
"[",
"i",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"plist",
")",
")",
":",
"plt",
".",
"clf",
"(",
")",
"data",
"=",
"matrix",
"[",
":",
",",
"i",
":",
"i",
"+",
"1",
"]",
".",
"reshape",
"(",
"5",
")",
"data",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'Intensidade calculada'",
":",
"data",
",",
"'Intensidade exata'",
":",
"np",
".",
"ones",
"(",
"len",
"(",
"data",
")",
")",
"*",
"exata",
"[",
"i",
"]",
"}",
")",
"my_colors",
"=",
"list",
"(",
"islice",
"(",
"cycle",
"(",
"[",
"'darkturquoise'",
",",
"'deepskyblue'",
",",
"'darkcyan'",
",",
"'lightseagreen'",
",",
"'c'",
"]",
")",
",",
"None",
",",
"len",
"(",
"data",
")",
")",
")",
"data",
"[",
"'Intensidade calculada'",
"]",
".",
"plot",
"(",
"kind",
"=",
"'bar'",
",",
"width",
"=",
"width",
",",
"color",
"=",
"my_colors",
",",
"title",
"=",
"'Evolução da intensidade com N, {}, P = {}'.f",
"o",
"rmat(N",
"a",
"me, ",
"p",
"ist[i",
"]",
")",
",",
" ",
"l",
"gend=T",
"r",
"ue)\r",
"",
"data",
"[",
"'Intensidade exata'",
"]",
".",
"plot",
"(",
")",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
".",
"set_xticklabels",
"(",
"(",
"'128'",
",",
"'256'",
",",
"'512'",
",",
"'1024'",
",",
"'2048'",
")",
")",
"# ax.set_xticklabels(('128', '256', '512'))\r",
"ax",
".",
"set_xlabel",
"(",
"\"N\"",
",",
"fontsize",
"=",
"12",
")",
"ax",
".",
"set_ylabel",
"(",
"\"Intensidade da fonte\"",
",",
"fontsize",
"=",
"12",
")",
"ax",
".",
"legend",
"(",
"labels",
"=",
"[",
"'Intensidade exata'",
",",
"'Intensidade calculada'",
"]",
",",
"loc",
"=",
"'lower left'",
")",
"# plt.show()\r",
"plt",
".",
"savefig",
"(",
"'{}.png'",
".",
"format",
"(",
"'plots/barras_pp'",
"+",
"Name",
"+",
"'P='",
"+",
"str",
"(",
"plist",
"[",
"i",
"]",
")",
")",
")"
] |
[
223,
0
] |
[
251,
85
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
TestePesquisaAnonima.test_resposta_unica
|
(self)
|
Testa se uma única resposta é armazenada de forma apropriada.
|
Testa se uma única resposta é armazenada de forma apropriada.
|
def test_resposta_unica(self):
"""Testa se uma única resposta é armazenada de forma apropriada."""
pergunta = "Qual a primeira língua que você aprendeu a falar?"
minha_pesquisa = PesquisaAnonima(
pergunta=pergunta
)
minha_pesquisa.conjunto_respostas(
nova_resposta='Português'
)
self.assertIn('Português', minha_pesquisa.respostas)
|
[
"def",
"test_resposta_unica",
"(",
"self",
")",
":",
"pergunta",
"=",
"\"Qual a primeira língua que você aprendeu a falar?\"",
"minha_pesquisa",
"=",
"PesquisaAnonima",
"(",
"pergunta",
"=",
"pergunta",
")",
"minha_pesquisa",
".",
"conjunto_respostas",
"(",
"nova_resposta",
"=",
"'Português'",
")",
"self",
".",
"assertIn",
"(",
"'Português',",
" ",
"inha_pesquisa.",
"r",
"espostas)",
""
] |
[
6,
4
] |
[
16,
61
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
test_get_prescriptions_by_id
|
(client)
|
Teste get /prescriptions/id - Compara response data com dados do banco e valida status_code 200
|
Teste get /prescriptions/id - Compara response data com dados do banco e valida status_code 200
|
def test_get_prescriptions_by_id(client):
"""Teste get /prescriptions/id - Compara response data com dados do banco e valida status_code 200"""
access_token = get_access(client)
idPrescription = '20'
response = client.get('/prescriptions/' + idPrescription, headers=make_headers(access_token))
data = json.loads(response.data)['data']
prescription = session.query(Prescription).get(idPrescription)
assert response.status_code == 200
assert data['idPrescription'] == str(prescription.id)
assert data['concilia'] == prescription.concilia
assert data['bed'] == prescription.bed
assert data['status'] == prescription.status
|
[
"def",
"test_get_prescriptions_by_id",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"idPrescription",
"=",
"'20'",
"response",
"=",
"client",
".",
"get",
"(",
"'/prescriptions/'",
"+",
"idPrescription",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")",
"[",
"'data'",
"]",
"prescription",
"=",
"session",
".",
"query",
"(",
"Prescription",
")",
".",
"get",
"(",
"idPrescription",
")",
"assert",
"response",
".",
"status_code",
"==",
"200",
"assert",
"data",
"[",
"'idPrescription'",
"]",
"==",
"str",
"(",
"prescription",
".",
"id",
")",
"assert",
"data",
"[",
"'concilia'",
"]",
"==",
"prescription",
".",
"concilia",
"assert",
"data",
"[",
"'bed'",
"]",
"==",
"prescription",
".",
"bed",
"assert",
"data",
"[",
"'status'",
"]",
"==",
"prescription",
".",
"status"
] |
[
26,
0
] |
[
41,
48
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
DoJobsConcurrently
|
(
func: callable,
jobs: list = [],
executor: concurrent.futures.Executor = concurrent.futures.ThreadPoolExecutor,
max_workers: int = 1,
success_callback: callable = (lambda *k: k),
exception_callback: callable = (lambda *k: k),
update_bar: callable = (lambda *k: k),
)
|
Executa uma lista de tarefas concorrentemente.
Params:
func (callable): função a ser executada concorrentemente.
jobs (list[Dict]): Lista com argumentos utilizados pela função a ser executada.
executor (concurrent.futures.Executor): Classe responsável por executar a
lista de jobs concorrentemente.
max_workers (integer)
success_callback (callable): Função executada ao finalizar a execução de cada job.
exception_callback (callable): Função executada durante o tratamento de exceções.
update_bar (callable): Função responsável por atualizar a posição da barra de status.
Returns:
None
|
Executa uma lista de tarefas concorrentemente.
|
def DoJobsConcurrently(
func: callable,
jobs: list = [],
executor: concurrent.futures.Executor = concurrent.futures.ThreadPoolExecutor,
max_workers: int = 1,
success_callback: callable = (lambda *k: k),
exception_callback: callable = (lambda *k: k),
update_bar: callable = (lambda *k: k),
):
"""Executa uma lista de tarefas concorrentemente.
Params:
func (callable): função a ser executada concorrentemente.
jobs (list[Dict]): Lista com argumentos utilizados pela função a ser executada.
executor (concurrent.futures.Executor): Classe responsável por executar a
lista de jobs concorrentemente.
max_workers (integer)
success_callback (callable): Função executada ao finalizar a execução de cada job.
exception_callback (callable): Função executada durante o tratamento de exceções.
update_bar (callable): Função responsável por atualizar a posição da barra de status.
Returns:
None
"""
poison_pill = PoisonPill()
with executor(max_workers=max_workers) as _executor:
futures = {
_executor.submit(func, **job, poison_pill=poison_pill): job for job in jobs
}
try:
for future in concurrent.futures.as_completed(futures):
job = futures[future]
try:
result = future.result()
except Exception as exc:
exception_callback(exc, job)
else:
success_callback(result)
finally:
update_bar()
except KeyboardInterrupt:
logging.info(
"Finalizando as tarefas pendentes antes de encerrar."
" Isso poderá levar alguns segundos."
)
poison_pill.poisoned = True
raise
|
[
"def",
"DoJobsConcurrently",
"(",
"func",
":",
"callable",
",",
"jobs",
":",
"list",
"=",
"[",
"]",
",",
"executor",
":",
"concurrent",
".",
"futures",
".",
"Executor",
"=",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
",",
"max_workers",
":",
"int",
"=",
"1",
",",
"success_callback",
":",
"callable",
"=",
"(",
"lambda",
"*",
"k",
":",
"k",
")",
",",
"exception_callback",
":",
"callable",
"=",
"(",
"lambda",
"*",
"k",
":",
"k",
")",
",",
"update_bar",
":",
"callable",
"=",
"(",
"lambda",
"*",
"k",
":",
"k",
")",
",",
")",
":",
"poison_pill",
"=",
"PoisonPill",
"(",
")",
"with",
"executor",
"(",
"max_workers",
"=",
"max_workers",
")",
"as",
"_executor",
":",
"futures",
"=",
"{",
"_executor",
".",
"submit",
"(",
"func",
",",
"*",
"*",
"job",
",",
"poison_pill",
"=",
"poison_pill",
")",
":",
"job",
"for",
"job",
"in",
"jobs",
"}",
"try",
":",
"for",
"future",
"in",
"concurrent",
".",
"futures",
".",
"as_completed",
"(",
"futures",
")",
":",
"job",
"=",
"futures",
"[",
"future",
"]",
"try",
":",
"result",
"=",
"future",
".",
"result",
"(",
")",
"except",
"Exception",
"as",
"exc",
":",
"exception_callback",
"(",
"exc",
",",
"job",
")",
"else",
":",
"success_callback",
"(",
"result",
")",
"finally",
":",
"update_bar",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"logging",
".",
"info",
"(",
"\"Finalizando as tarefas pendentes antes de encerrar.\"",
"\" Isso poderá levar alguns segundos.\"",
")",
"poison_pill",
".",
"poisoned",
"=",
"True",
"raise"
] |
[
60,
0
] |
[
108,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
paths_parser
|
(args, d_source, h_source, d_desc, h_desc)
|
return parser
|
Parser utilizado para capturar informações sobre path de origem e path de destino
dos comandos de tools
|
Parser utilizado para capturar informações sobre path de origem e path de destino
dos comandos de tools
|
def paths_parser(args, d_source, h_source, d_desc, h_desc):
"""Parser utilizado para capturar informações sobre path de origem e path de destino
dos comandos de tools """
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--source-path", "-p", default=d_source, help=h_source)
parser.add_argument("--desc-path", "-d", default=d_desc, help=h_desc)
return parser
|
[
"def",
"paths_parser",
"(",
"args",
",",
"d_source",
",",
"h_source",
",",
"d_desc",
",",
"h_desc",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"\"--source-path\"",
",",
"\"-p\"",
",",
"default",
"=",
"d_source",
",",
"help",
"=",
"h_source",
")",
"parser",
".",
"add_argument",
"(",
"\"--desc-path\"",
",",
"\"-d\"",
",",
"default",
"=",
"d_desc",
",",
"help",
"=",
"h_desc",
")",
"return",
"parser"
] |
[
56,
0
] |
[
63,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
ola
|
(nome, cpf, idade=0, maiusculo=False, *args, **kwargs)
|
Essa função diz OLá.
:param nome str: Nome da pessoa
:param cpf str: Nome da pessoa
:param idade int: Nome da pessoa
:param args: Argumentos extras posicionais
:param kwargs: Argumentos extras nomeados
:returns None:
|
Essa função diz OLá.
|
def ola(nome, cpf, idade=0, maiusculo=False, *args, **kwargs):
"""Essa função diz OLá.
:param nome str: Nome da pessoa
:param cpf str: Nome da pessoa
:param idade int: Nome da pessoa
:param args: Argumentos extras posicionais
:param kwargs: Argumentos extras nomeados
:returns None:
"""
valor = "Eu sou local"
def funcao_dentro_de_funcao(): # inner function / closure
nonlocal valor
valor = "Mudando a variavel do escopo imediatamente anterior!"
def outra_closure():
global valor
valor = "Mudando a variavel global"
print(args)
print(kwargs)
if maiusculo:
msg = f"Olá, {nome}".upper()
else:
msg = f"Olá, {nome}, {cpf}, idade: {idade}"
print(msg)
|
[
"def",
"ola",
"(",
"nome",
",",
"cpf",
",",
"idade",
"=",
"0",
",",
"maiusculo",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"valor",
"=",
"\"Eu sou local\"",
"def",
"funcao_dentro_de_funcao",
"(",
")",
":",
"# inner function / closure",
"nonlocal",
"valor",
"valor",
"=",
"\"Mudando a variavel do escopo imediatamente anterior!\"",
"def",
"outra_closure",
"(",
")",
":",
"global",
"valor",
"valor",
"=",
"\"Mudando a variavel global\"",
"print",
"(",
"args",
")",
"print",
"(",
"kwargs",
")",
"if",
"maiusculo",
":",
"msg",
"=",
"f\"Olá, {nome}\".",
"u",
"pper(",
")",
"",
"else",
":",
"msg",
"=",
"f\"Olá, {nome}, {cpf}, idade: {idade}\"",
"print",
"(",
"msg",
")"
] |
[
4,
0
] |
[
35,
14
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Pesquisador.carregaDadosGlobais
|
(self)
|
return
|
Carrega todas as tabelas necessárias.
Returns:
type: None.
|
Carrega todas as tabelas necessárias.
|
def carregaDadosGlobais(self):
"""Carrega todas as tabelas necessárias.
Returns:
type: None.
"""
#----Carrega os dados externos em dataframes uma única vez para ser utililizado.
#----Alguns arquivos precisam de trabalho adicional
paths = self.validaPath()
if self.__PONTUA:
self.Pontos = pd.read_excel(paths['pathPontos'])
if self.__SAAP:
self.SAAP = pd.read_excel(paths['pathSAAP'])
# try:
# self.CAPES = pd.read_csv(paths['pathCAPES'])
# #----Dados da tabela CAPES precisam ser normalizados, sem acentos para comparação de textos.
# self.CAPES = self.CAPES.applymap(unidecode)
# except IOError:
# #LOG.error("Não foi encontrada: Tabela de TABELA_EQUIVALENCIA_CNPQ_CAPES")
# self.CAPES = []
#
# try:
# #----encoding do CNPq precisa evoluir
# self.QUALIS = pd.read_csv(paths['pathQualis'], encoding = "ISO-8859-1", index_col=0)
# self.QUALIS = self.QUALIS.reset_index()
# #----Coluna de areas tem muitos whitespaces escondidos. stripped.
# self.QUALIS["area"] = self.QUALIS["area"].apply(lambda val: val.strip())
# #----Normaliza e codifica para comparar áreas
# self.QUALIS['area'] = self.QUALIS['area'].str.normalize('NFKD').str.encode('ISO-8859-1', 'ignore')
# #----Este arquivo é muito grande e muitas comparações vão ser feitas. Categorias nas áreas vão agilizar o processamento.
# self.QUALIS['area'] = self.QUALIS['area'].astype('category')
# except pd.errors.EmptyDataError as error:
# tmp = None
# return
return
|
[
"def",
"carregaDadosGlobais",
"(",
"self",
")",
":",
"#----Carrega os dados externos em dataframes uma única vez para ser utililizado.",
"#----Alguns arquivos precisam de trabalho adicional",
"paths",
"=",
"self",
".",
"validaPath",
"(",
")",
"if",
"self",
".",
"__PONTUA",
":",
"self",
".",
"Pontos",
"=",
"pd",
".",
"read_excel",
"(",
"paths",
"[",
"'pathPontos'",
"]",
")",
"if",
"self",
".",
"__SAAP",
":",
"self",
".",
"SAAP",
"=",
"pd",
".",
"read_excel",
"(",
"paths",
"[",
"'pathSAAP'",
"]",
")",
"# try:",
"# self.CAPES = pd.read_csv(paths['pathCAPES'])",
"# #----Dados da tabela CAPES precisam ser normalizados, sem acentos para comparação de textos.",
"# self.CAPES = self.CAPES.applymap(unidecode)",
"# except IOError:",
"# #LOG.error(\"Não foi encontrada: Tabela de TABELA_EQUIVALENCIA_CNPQ_CAPES\")",
"# self.CAPES = []",
"#",
"# try:",
"# #----encoding do CNPq precisa evoluir",
"# self.QUALIS = pd.read_csv(paths['pathQualis'], encoding = \"ISO-8859-1\", index_col=0)",
"# self.QUALIS = self.QUALIS.reset_index()",
"# #----Coluna de areas tem muitos whitespaces escondidos. stripped.",
"# self.QUALIS[\"area\"] = self.QUALIS[\"area\"].apply(lambda val: val.strip())",
"# #----Normaliza e codifica para comparar áreas",
"# self.QUALIS['area'] = self.QUALIS['area'].str.normalize('NFKD').str.encode('ISO-8859-1', 'ignore')",
"# #----Este arquivo é muito grande e muitas comparações vão ser feitas. Categorias nas áreas vão agilizar o processamento.",
"# self.QUALIS['area'] = self.QUALIS['area'].astype('category')",
"# except pd.errors.EmptyDataError as error:",
"# tmp = None",
"# return",
"return"
] |
[
355,
4
] |
[
392,
14
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Autenticador.authenticate
|
(self, request, username, password)
|
return None
|
Autentica o usuário no SCA, sem revalidar a sessão
|
Autentica o usuário no SCA, sem revalidar a sessão
|
def authenticate(self, request, username, password):
"Autentica o usuário no SCA, sem revalidar a sessão"
del request
password = bytes(password, 'utf-8')
session = requests.session()
response = session.post(
url=settings.AUTH_MPRJ,
data={
'username': username,
'password': base64.b64encode(password).decode("utf-8")
})
if response.status_code == 200:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
response = session.get(url=settings.AITJ_MPRJ_USERINFO)
corpo = json.loads(response.content.decode('utf-8'))
user = User(username=username)
user.is_staff = False
user.is_superuser = False
user.first_name = corpo['userDetails']['nome']
user.save()
return user
return None
|
[
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"username",
",",
"password",
")",
":",
"del",
"request",
"password",
"=",
"bytes",
"(",
"password",
",",
"'utf-8'",
")",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"response",
"=",
"session",
".",
"post",
"(",
"url",
"=",
"settings",
".",
"AUTH_MPRJ",
",",
"data",
"=",
"{",
"'username'",
":",
"username",
",",
"'password'",
":",
"base64",
".",
"b64encode",
"(",
"password",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"}",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"try",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"response",
"=",
"session",
".",
"get",
"(",
"url",
"=",
"settings",
".",
"AITJ_MPRJ_USERINFO",
")",
"corpo",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"user",
"=",
"User",
"(",
"username",
"=",
"username",
")",
"user",
".",
"is_staff",
"=",
"False",
"user",
".",
"is_superuser",
"=",
"False",
"user",
".",
"first_name",
"=",
"corpo",
"[",
"'userDetails'",
"]",
"[",
"'nome'",
"]",
"user",
".",
"save",
"(",
")",
"return",
"user",
"return",
"None"
] |
[
10,
4
] |
[
34,
19
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Moderation.blacklist
|
(self, ctx, user: Union[discord.Member, discord.User], *, reason: str = None)
|
Deixa uma pessoa na lista negra.
A lista negra é uma lista de usuários que impede
elas de usarem os comandos do bot.
**Veja também**: Comando `whitelist`.
|
Deixa uma pessoa na lista negra.
|
async def blacklist(self, ctx, user: Union[discord.Member, discord.User], *, reason: str = None):
"""Deixa uma pessoa na lista negra.
A lista negra é uma lista de usuários que impede
elas de usarem os comandos do bot.
**Veja também**: Comando `whitelist`."""
appinfo = await self.client.application_info()
if user in appinfo.team.members:
await ctx.reply("Você não pode dar blacklist em membros do time!")
return
fields = (
Field(name="user_id", type="TEXT NOT NULL"),
Field(name="reason", type="TEXT")
)
async with create_async_database("main.db") as wrap:
await wrap.create_table_if_absent("blacklisteds", fields)
write_blacklist(user, reason)
await ctx.reply(f"O usuário {user} foi banido de usar o bot.")
|
[
"async",
"def",
"blacklist",
"(",
"self",
",",
"ctx",
",",
"user",
":",
"Union",
"[",
"discord",
".",
"Member",
",",
"discord",
".",
"User",
"]",
",",
"*",
",",
"reason",
":",
"str",
"=",
"None",
")",
":",
"appinfo",
"=",
"await",
"self",
".",
"client",
".",
"application_info",
"(",
")",
"if",
"user",
"in",
"appinfo",
".",
"team",
".",
"members",
":",
"await",
"ctx",
".",
"reply",
"(",
"\"Você não pode dar blacklist em membros do time!\")",
"",
"return",
"fields",
"=",
"(",
"Field",
"(",
"name",
"=",
"\"user_id\"",
",",
"type",
"=",
"\"TEXT NOT NULL\"",
")",
",",
"Field",
"(",
"name",
"=",
"\"reason\"",
",",
"type",
"=",
"\"TEXT\"",
")",
")",
"async",
"with",
"create_async_database",
"(",
"\"main.db\"",
")",
"as",
"wrap",
":",
"await",
"wrap",
".",
"create_table_if_absent",
"(",
"\"blacklisteds\"",
",",
"fields",
")",
"write_blacklist",
"(",
"user",
",",
"reason",
")",
"await",
"ctx",
".",
"reply",
"(",
"f\"O usuário {user} foi banido de usar o bot.\")",
""
] |
[
40,
4
] |
[
59,
71
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
uploadb
|
(request)
|
return render(request, "uploadb.html", {'cliente': cliente}, context)
|
Função para carregar o boleto/arquivo para o 'cliente'.
Essa função é chamada pelo funcionário (específico) lançar o boleto
|
Função para carregar o boleto/arquivo para o 'cliente'.
Essa função é chamada pelo funcionário (específico) lançar o boleto
|
def uploadb(request):
"""Função para carregar o boleto/arquivo para o 'cliente'.
Essa função é chamada pelo funcionário (específico) lançar o boleto"""
context = {}
cliente = Cliente.objects.all()
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, "uploadb.html", {'cliente': cliente}, context)
|
[
"def",
"uploadb",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"cliente",
"=",
"Cliente",
".",
"objects",
".",
"all",
"(",
")",
"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",
",",
"\"uploadb.html\"",
",",
"{",
"'cliente'",
":",
"cliente",
"}",
",",
"context",
")"
] |
[
546,
0
] |
[
556,
73
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
generate
|
(conf=None, arquivo_processamento=None, driver=None)
|
Organiza e gera a partir dos parametros enviados o arquivo de remessa.
Keyword arguments:
conf -- nome do arquivo de configuracao sem o ".prod.conf"
arquivo_processamento -- caminho para o arquivo que será processado
driver -- driver que será utilizado para a leitura correta do arquivo_processamento (csv, default)
|
Organiza e gera a partir dos parametros enviados o arquivo de remessa.
Keyword arguments:
conf -- nome do arquivo de configuracao sem o ".prod.conf"
arquivo_processamento -- caminho para o arquivo que será processado
driver -- driver que será utilizado para a leitura correta do arquivo_processamento (csv, default)
|
def generate(conf=None, arquivo_processamento=None, driver=None):
"""Organiza e gera a partir dos parametros enviados o arquivo de remessa.
Keyword arguments:
conf -- nome do arquivo de configuracao sem o ".prod.conf"
arquivo_processamento -- caminho para o arquivo que será processado
driver -- driver que será utilizado para a leitura correta do arquivo_processamento (csv, default)
"""
conf_json = check_conf(conf)
if( conf_json == False ):
return
odict_ha = ha.default_header_arquivo()
odict_hl = hl.default_header_lote()
#vamos iterar sobre o conf_json e alimentar o odict_ha e o odict_hl
for indice in conf_json.keys():
if(indice in odict_ha.keys()) :
odict_ha[ indice ] = conf_json[ indice ]
if( indice in odict_hl.keys() ):
odict_hl[ indice ] = conf_json[ indice ]
#vamos fazer a leitura das contas
#carregamento automatico do modulo
try:
modname = "cnab240.drivers."+driver
module = importlib.import_module( modname )
contas = module.exec( arquivo_processamento )
except Exception as e:
#Caso nao consiga carregar o modulo
print ("Driver '"+driver+"' não encontrado")
return
bla = dict()
bla['header_arquivo'] = odict_ha
bla['header_lote'] = odict_hl
bla['segmento_a_contas'] = contas
#manda processar
print ( rp.generate(bla, conf_json), end='' )
|
[
"def",
"generate",
"(",
"conf",
"=",
"None",
",",
"arquivo_processamento",
"=",
"None",
",",
"driver",
"=",
"None",
")",
":",
"conf_json",
"=",
"check_conf",
"(",
"conf",
")",
"if",
"(",
"conf_json",
"==",
"False",
")",
":",
"return",
"odict_ha",
"=",
"ha",
".",
"default_header_arquivo",
"(",
")",
"odict_hl",
"=",
"hl",
".",
"default_header_lote",
"(",
")",
"#vamos iterar sobre o conf_json e alimentar o odict_ha e o odict_hl\r",
"for",
"indice",
"in",
"conf_json",
".",
"keys",
"(",
")",
":",
"if",
"(",
"indice",
"in",
"odict_ha",
".",
"keys",
"(",
")",
")",
":",
"odict_ha",
"[",
"indice",
"]",
"=",
"conf_json",
"[",
"indice",
"]",
"if",
"(",
"indice",
"in",
"odict_hl",
".",
"keys",
"(",
")",
")",
":",
"odict_hl",
"[",
"indice",
"]",
"=",
"conf_json",
"[",
"indice",
"]",
"#vamos fazer a leitura das contas\r",
"#carregamento automatico do modulo\r",
"try",
":",
"modname",
"=",
"\"cnab240.drivers.\"",
"+",
"driver",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"modname",
")",
"contas",
"=",
"module",
".",
"exec",
"(",
"arquivo_processamento",
")",
"except",
"Exception",
"as",
"e",
":",
"#Caso nao consiga carregar o modulo\r",
"print",
"(",
"\"Driver '\"",
"+",
"driver",
"+",
"\"' não encontrado\")",
"\r",
"return",
"bla",
"=",
"dict",
"(",
")",
"bla",
"[",
"'header_arquivo'",
"]",
"=",
"odict_ha",
"bla",
"[",
"'header_lote'",
"]",
"=",
"odict_hl",
"bla",
"[",
"'segmento_a_contas'",
"]",
"=",
"contas",
"#manda processar\r",
"print",
"(",
"rp",
".",
"generate",
"(",
"bla",
",",
"conf_json",
")",
",",
"end",
"=",
"''",
")"
] |
[
28,
0
] |
[
71,
49
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
EquipamentoAmbienteResource.handle_put
|
(self, request, user, *args, **kwargs)
|
Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente.
URL: equipamentoambiente/update/$
|
Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente.
|
def handle_put(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para inserir uma associação entre um Equipamento e um Ambiente.
URL: equipamentoambiente/update/$
"""
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()
try:
equip_environment = EquipamentoAmbiente().get_by_equipment_environment(
equip_id, environment_id)
equip_environment.is_router = is_router
equip_environment.save()
except EquipamentoAmbienteNotFoundError:
self.log.warning(
u'Falha ao alterar a associação equipamento/ambiente, associação não existe %s/%s.' % (equip_id, environment_id))
pass
except Exception, e:
self.log.error(
u'Falha ao alterar a associação equipamento/ambiente: %s/%s.' % (equip_id, environment_id))
raise EquipamentoError(
e, u'Falha ao alterar a associação equipamento/ambiente: %s/%s.' % (equip_id, environment_id))
equip_environment_map = dict()
equip_environment_map['id'] = equip_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_put",
"(",
"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",
"(",
")",
"try",
":",
"equip_environment",
"=",
"EquipamentoAmbiente",
"(",
")",
".",
"get_by_equipment_environment",
"(",
"equip_id",
",",
"environment_id",
")",
"equip_environment",
".",
"is_router",
"=",
"is_router",
"equip_environment",
".",
"save",
"(",
")",
"except",
"EquipamentoAmbienteNotFoundError",
":",
"self",
".",
"log",
".",
"warning",
"(",
"u'Falha ao alterar a associação equipamento/ambiente, associação não existe %s/%s.' % (e",
"u",
"p",
"_id, env",
"i",
"onment_id))",
"",
"",
"pass",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Falha ao alterar a associação equipamento/ambiente: %s/%s.' %",
"(",
"q",
"uip_id, ",
"e",
"vironment_id))",
"",
"",
"raise",
"EquipamentoError",
"(",
"e",
",",
"u'Falha ao alterar a associação equipamento/ambiente: %s/%s.' %",
"(",
"q",
"uip_id, ",
"e",
"vironment_id))",
"",
"",
"equip_environment_map",
"=",
"dict",
"(",
")",
"equip_environment_map",
"[",
"'id'",
"]",
"=",
"equip_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",
")"
] |
[
481,
4
] |
[
563,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Pyvidesk.tickets
|
(self)
|
return Tickets(token=self.token)
|
Retorna um objeto de tickets do pyvidesk
|
Retorna um objeto de tickets do pyvidesk
|
def tickets(self):
"""Retorna um objeto de tickets do pyvidesk"""
return Tickets(token=self.token)
|
[
"def",
"tickets",
"(",
"self",
")",
":",
"return",
"Tickets",
"(",
"token",
"=",
"self",
".",
"token",
")"
] |
[
17,
4
] |
[
19,
40
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
try_register_documents_renditions
|
(
documents: List[str],
get_rendition_data: callable,
article_rendition_factory: callable,
)
|
return list(set(orphans))
|
Registra as manifestações de documentos na base de dados do OPAC
As manifestações que não puderem ser registradas serão consideradas como
órfãos.
Args:
documents (Iterable): iterável com os identicadores dos documentos
a serem registrados.
get_rendition_data (callable): Recupera os dados de manifestações
de um documento.
article_rendition_factory (callable): Recupera uma instância de
artigo da base OPAC e popula as suas manifestações de acordo
com os dados apresentados.
Returns:
List[str] orphans: Lista contendo todos os identificadores dos
documentos em que as manifestações que não puderam ser registradas
na base de dados do OPAC.
|
Registra as manifestações de documentos na base de dados do OPAC
|
def try_register_documents_renditions(
documents: List[str],
get_rendition_data: callable,
article_rendition_factory: callable,
) -> List[str]:
"""Registra as manifestações de documentos na base de dados do OPAC
As manifestações que não puderem ser registradas serão consideradas como
órfãos.
Args:
documents (Iterable): iterável com os identicadores dos documentos
a serem registrados.
get_rendition_data (callable): Recupera os dados de manifestações
de um documento.
article_rendition_factory (callable): Recupera uma instância de
artigo da base OPAC e popula as suas manifestações de acordo
com os dados apresentados.
Returns:
List[str] orphans: Lista contendo todos os identificadores dos
documentos em que as manifestações que não puderam ser registradas
na base de dados do OPAC.
"""
orphans = []
for document in documents:
try:
data = get_rendition_data(document)
article = article_rendition_factory(document, data)
article.save()
except models.Article.DoesNotExist:
logging.info(
'Could not possible save rendition for document, probably '
'document %s isn\'t in OPAC database.' % document
)
orphans.append(document)
return list(set(orphans))
|
[
"def",
"try_register_documents_renditions",
"(",
"documents",
":",
"List",
"[",
"str",
"]",
",",
"get_rendition_data",
":",
"callable",
",",
"article_rendition_factory",
":",
"callable",
",",
")",
"->",
"List",
"[",
"str",
"]",
":",
"orphans",
"=",
"[",
"]",
"for",
"document",
"in",
"documents",
":",
"try",
":",
"data",
"=",
"get_rendition_data",
"(",
"document",
")",
"article",
"=",
"article_rendition_factory",
"(",
"document",
",",
"data",
")",
"article",
".",
"save",
"(",
")",
"except",
"models",
".",
"Article",
".",
"DoesNotExist",
":",
"logging",
".",
"info",
"(",
"'Could not possible save rendition for document, probably '",
"'document %s isn\\'t in OPAC database.'",
"%",
"document",
")",
"orphans",
".",
"append",
"(",
"document",
")",
"return",
"list",
"(",
"set",
"(",
"orphans",
")",
")"
] |
[
323,
0
] |
[
362,
29
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
MyServer.run
|
(self, app)
|
pragma: no cover.
|
pragma: no cover.
|
def run(self, app):
"""pragma: no cover."""
handler_cls = self.options.get('handler_class', FixedHandler)
server_cls = self.options.get('server_class', WSGIServer)
srv = make_server(self.host, self.port, app, server_cls, handler_cls)
# THIS IS THE ONLY CHANGE TO THE ORIGINAL CLASS METHOD!
self.srv = srv
srv.serve_forever()
|
[
"def",
"run",
"(",
"self",
",",
"app",
")",
":",
"handler_cls",
"=",
"self",
".",
"options",
".",
"get",
"(",
"'handler_class'",
",",
"FixedHandler",
")",
"server_cls",
"=",
"self",
".",
"options",
".",
"get",
"(",
"'server_class'",
",",
"WSGIServer",
")",
"srv",
"=",
"make_server",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"app",
",",
"server_cls",
",",
"handler_cls",
")",
"# THIS IS THE ONLY CHANGE TO THE ORIGINAL CLASS METHOD!",
"self",
".",
"srv",
"=",
"srv",
"srv",
".",
"serve_forever",
"(",
")"
] |
[
18,
4
] |
[
26,
27
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
TesteFuncionario.setUp
|
(self)
|
Cria um conjunto de informações que podems ser usados
em todos os métodos de teste.
|
Cria um conjunto de informações que podems ser usados
em todos os métodos de teste.
|
def setUp(self):
"""Cria um conjunto de informações que podems ser usados
em todos os métodos de teste."""
self.alberto = Funcionario(
nome='alberto',
sobrenome='mendes',
salario=50000
)
|
[
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"alberto",
"=",
"Funcionario",
"(",
"nome",
"=",
"'alberto'",
",",
"sobrenome",
"=",
"'mendes'",
",",
"salario",
"=",
"50000",
")"
] |
[
8,
4
] |
[
15,
9
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Audio.musicrecommender
|
(self, ctx, *, artistas)
|
Gera recomendações de músicas personalizadas para você, baseado nos artistas que você gosta.
Caso queira colocar mais de um artista, separe por vírgulas.
Ex: Barões da Pesadinha, Zeca Paugordinho, Pablo Vomittar, Chitãozinho e só loló, Pita-Umzinho & Cheira pó
|
Gera recomendações de músicas personalizadas para você, baseado nos artistas que você gosta.
Caso queira colocar mais de um artista, separe por vírgulas.
Ex: Barões da Pesadinha, Zeca Paugordinho, Pablo Vomittar, Chitãozinho e só loló, Pita-Umzinho & Cheira pó
|
async def musicrecommender(self, ctx, *, artistas):
"""Gera recomendações de músicas personalizadas para você, baseado nos artistas que você gosta.
Caso queira colocar mais de um artista, separe por vírgulas.
Ex: Barões da Pesadinha, Zeca Paugordinho, Pablo Vomittar, Chitãozinho e só loló, Pita-Umzinho & Cheira pó"""
artists = artistas.split(',')
recommend = self.Musicrecommend(ctx, artists, self.client)
await recommend.start(ctx)
|
[
"async",
"def",
"musicrecommender",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"artistas",
")",
":",
"artists",
"=",
"artistas",
".",
"split",
"(",
"','",
")",
"recommend",
"=",
"self",
".",
"Musicrecommend",
"(",
"ctx",
",",
"artists",
",",
"self",
".",
"client",
")",
"await",
"recommend",
".",
"start",
"(",
"ctx",
")"
] |
[
348,
4
] |
[
354,
34
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Carro.nome_descritivo
|
(self)
|
return nome_carro.title()
|
Devolve um nome descritivo, formatado de modo elegante.
|
Devolve um nome descritivo, formatado de modo elegante.
|
def nome_descritivo(self):
"""Devolve um nome descritivo, formatado de modo elegante."""
nome_carro = str(self.ano) + " " + self.fabricante + " " + self.modelo
return nome_carro.title()
|
[
"def",
"nome_descritivo",
"(",
"self",
")",
":",
"nome_carro",
"=",
"str",
"(",
"self",
".",
"ano",
")",
"+",
"\" \"",
"+",
"self",
".",
"fabricante",
"+",
"\" \"",
"+",
"self",
".",
"modelo",
"return",
"nome_carro",
".",
"title",
"(",
")"
] |
[
11,
4
] |
[
14,
33
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
known_path_rec
|
(kb, loc, dest, path, visited)
|
return False
|
Algoritmo de Busca: Pesquisa em profundidade que constrói um caminho explorado para o destino.
|
Algoritmo de Busca: Pesquisa em profundidade que constrói um caminho explorado para o destino.
|
def known_path_rec(kb, loc, dest, path, visited):
"""Algoritmo de Busca: Pesquisa em profundidade que constrói um caminho explorado para o destino."""
if loc == dest:
return True
# Gerador de vizinhos explorados (mas ainda não visitados pela pesquisa)
neighborhood = (l for l in neighbors(loc) if l not in visited
and (kb[l].is_explored or l == dest))
# Iterar sobre cada vizinho
for n in neighborhood:
# Adiciona o nó ao caminho
path.append(n)
visited.add(n)
# Chamada recursiva
if known_path_rec(kb, n, dest, path, visited):
return True
# Backtrack: este nó não conduz ao destino
visited.remove(n)
path.remove(n)
return False
|
[
"def",
"known_path_rec",
"(",
"kb",
",",
"loc",
",",
"dest",
",",
"path",
",",
"visited",
")",
":",
"if",
"loc",
"==",
"dest",
":",
"return",
"True",
"# Gerador de vizinhos explorados (mas ainda não visitados pela pesquisa)",
"neighborhood",
"=",
"(",
"l",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"if",
"l",
"not",
"in",
"visited",
"and",
"(",
"kb",
"[",
"l",
"]",
".",
"is_explored",
"or",
"l",
"==",
"dest",
")",
")",
"# Iterar sobre cada vizinho",
"for",
"n",
"in",
"neighborhood",
":",
"# Adiciona o nó ao caminho",
"path",
".",
"append",
"(",
"n",
")",
"visited",
".",
"add",
"(",
"n",
")",
"# Chamada recursiva",
"if",
"known_path_rec",
"(",
"kb",
",",
"n",
",",
"dest",
",",
"path",
",",
"visited",
")",
":",
"return",
"True",
"# Backtrack: este nó não conduz ao destino",
"visited",
".",
"remove",
"(",
"n",
")",
"path",
".",
"remove",
"(",
"n",
")",
"return",
"False"
] |
[
75,
0
] |
[
100,
14
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
BoletoPDF._drawReciboSacado
|
(self, boleto_dados, x, y)
|
return (self.width, ((linha_inicial + 3) * self.height_line))
|
Imprime o Recibo do Sacado para modelo de página inteira
:param boleto_dados: Objeto com os dados do boleto a ser preenchido.
Deve ser subclasse de :class:`pyboleto.data.BoletoData`
:type boleto_dados: :class:`pyboleto.data.BoletoData`
|
Imprime o Recibo do Sacado para modelo de página inteira
|
def _drawReciboSacado(self, boleto_dados, x, y):
"""Imprime o Recibo do Sacado para modelo de página inteira
:param boleto_dados: Objeto com os dados do boleto a ser preenchido.
Deve ser subclasse de :class:`pyboleto.data.BoletoData`
:type boleto_dados: :class:`pyboleto.data.BoletoData`
"""
self.pdf_canvas.saveState()
self.pdf_canvas.translate(x, y)
linha_inicial = 15
# Horizontal Lines
self.pdf_canvas.setLineWidth(1)
self.__horizontalLine(0,
(linha_inicial + 0) * self.height_line,
self.width)
self.__horizontalLine(0,
(linha_inicial + 1) * self.height_line,
self.width)
self.__horizontalLine(0,
(linha_inicial + 2) * self.height_line,
self.width)
self.pdf_canvas.setLineWidth(2)
self.__horizontalLine(0,
(linha_inicial + 3) * self.height_line,
self.width)
# Vertical Lines
self.pdf_canvas.setLineWidth(1)
self.__verticalLine(
self.width - (30 * mm),
(linha_inicial + 0) * self.height_line,
3 * self.height_line
)
self.__verticalLine(
self.width - (30 * mm) - (35 * mm),
(linha_inicial + 1) * self.height_line,
2 * self.height_line
)
self.__verticalLine(
self.width - (30 * mm) - (35 * mm) - (40 * mm),
(linha_inicial + 1) * self.height_line,
2 * self.height_line
)
# Head
self.pdf_canvas.setLineWidth(2)
self.__verticalLine(40 * mm,
(linha_inicial + 3) * self.height_line,
self.height_line)
self.__verticalLine(60 * mm,
(linha_inicial + 3) * self.height_line,
self.height_line)
if boleto_dados.logo_image:
logo_image_path = load_image(boleto_dados.logo_image)
self.pdf_canvas.drawImage(
logo_image_path,
0, (linha_inicial + 3) * self.height_line + 3,
40 * mm,
self.height_line,
preserveAspectRatio=True,
anchor='sw'
)
self.pdf_canvas.setFont('Helvetica-Bold', 18)
self.pdf_canvas.drawCentredString(
50 * mm,
(linha_inicial + 3) * self.height_line + 3,
boleto_dados.codigo_dv_banco
)
self.pdf_canvas.setFont('Helvetica-Bold', 11.5)
self.pdf_canvas.drawRightString(
self.width,
(linha_inicial + 3) * self.height_line + 3,
'Recibo do Sacado'
)
# Titles
self.pdf_canvas.setFont('Helvetica', 6)
self.delta_title = self.height_line - (6 + 1)
self.pdf_canvas.drawRightString(
self.width,
self.height_line,
'Autenticação Mecânica'
)
self.pdf_canvas.drawString(
0,
(((linha_inicial + 2) * self.height_line)) + self.delta_title,
'Cedente'
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) - (40 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.delta_title,
'Agência/Código Cedente'
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.delta_title,
'CPF/CNPJ Cedente'
)
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.delta_title,
'Vencimento'
)
self.pdf_canvas.drawString(
0,
(((linha_inicial + 1) * self.height_line)) + self.delta_title,
'Sacado')
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) - (40 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.delta_title,
'Nosso Número')
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.delta_title,
'N. do documento')
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.delta_title,
'Data Documento'
)
self.pdf_canvas.drawString(
0,
(((linha_inicial + 0) * self.height_line)) + self.delta_title,
'Endereço Cedente'
)
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 0) * self.height_line)) + self.delta_title,
'Valor Documento'
)
self.pdf_canvas.drawString(
0,
(((linha_inicial + 0) * self.height_line - 3 * cm)) +
self.delta_title,
'Demonstrativo'
)
# Values
self.pdf_canvas.setFont('Helvetica', 9)
heigh_font = 9 + 1
self.pdf_canvas.drawString(
0 + self.space,
(((linha_inicial + 2) * self.height_line)) + self.space,
boleto_dados.cedente
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) - (40 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.space,
boleto_dados.agencia_conta_cedente
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.space,
boleto_dados.cedente_documento
)
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 2) * self.height_line)) + self.space,
boleto_dados.data_vencimento.strftime('%d/%m/%Y')
)
# Take care of long field
sacado0 = boleto_dados.sacado[0]
while (stringWidth(sacado0,
self.pdf_canvas._fontname,
self.pdf_canvas._fontsize
) > 8.4 * cm):
# sacado0 = sacado0[:-2] + u'\u2026'
sacado0 = sacado0[:-4] + u'...'
self.pdf_canvas.drawString(
0 + self.space,
(((linha_inicial + 1) * self.height_line)) + self.space,
sacado0
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) - (40 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.space,
boleto_dados.format_nosso_numero()
)
self.pdf_canvas.drawString(
self.width - (30 * mm) - (35 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.space,
boleto_dados.numero_documento
)
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 1) * self.height_line)) + self.space,
boleto_dados.data_documento.strftime('%d/%m/%Y')
)
valor_documento = self._formataValorParaExibir(
boleto_dados.valor_documento
)
self.pdf_canvas.drawString(
0 + self.space,
(((linha_inicial + 0) * self.height_line)) + self.space,
boleto_dados.cedente_endereco
)
self.pdf_canvas.drawString(
self.width - (30 * mm) + self.space,
(((linha_inicial + 0) * self.height_line)) + self.space,
valor_documento
)
self.pdf_canvas.setFont('Courier', 9)
demonstrativo = boleto_dados.demonstrativo[0:25]
for i in range(len(demonstrativo)):
self.pdf_canvas.drawString(
2 * self.space,
(-3 * cm + ((linha_inicial + 0) * self.height_line)) -
(i * heigh_font),
demonstrativo[i])
self.pdf_canvas.setFont('Helvetica', 9)
self.pdf_canvas.restoreState()
return (self.width, ((linha_inicial + 3) * self.height_line))
|
[
"def",
"_drawReciboSacado",
"(",
"self",
",",
"boleto_dados",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"pdf_canvas",
".",
"saveState",
"(",
")",
"self",
".",
"pdf_canvas",
".",
"translate",
"(",
"x",
",",
"y",
")",
"linha_inicial",
"=",
"15",
"# Horizontal Lines",
"self",
".",
"pdf_canvas",
".",
"setLineWidth",
"(",
"1",
")",
"self",
".",
"__horizontalLine",
"(",
"0",
",",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"width",
")",
"self",
".",
"__horizontalLine",
"(",
"0",
",",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"width",
")",
"self",
".",
"__horizontalLine",
"(",
"0",
",",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"width",
")",
"self",
".",
"pdf_canvas",
".",
"setLineWidth",
"(",
"2",
")",
"self",
".",
"__horizontalLine",
"(",
"0",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"width",
")",
"# Vertical Lines",
"self",
".",
"pdf_canvas",
".",
"setLineWidth",
"(",
"1",
")",
"self",
".",
"__verticalLine",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
",",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
",",
"3",
"*",
"self",
".",
"height_line",
")",
"self",
".",
"__verticalLine",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
",",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
",",
"2",
"*",
"self",
".",
"height_line",
")",
"self",
".",
"__verticalLine",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"-",
"(",
"40",
"*",
"mm",
")",
",",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
",",
"2",
"*",
"self",
".",
"height_line",
")",
"# Head",
"self",
".",
"pdf_canvas",
".",
"setLineWidth",
"(",
"2",
")",
"self",
".",
"__verticalLine",
"(",
"40",
"*",
"mm",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"height_line",
")",
"self",
".",
"__verticalLine",
"(",
"60",
"*",
"mm",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
",",
"self",
".",
"height_line",
")",
"if",
"boleto_dados",
".",
"logo_image",
":",
"logo_image_path",
"=",
"load_image",
"(",
"boleto_dados",
".",
"logo_image",
")",
"self",
".",
"pdf_canvas",
".",
"drawImage",
"(",
"logo_image_path",
",",
"0",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
"+",
"3",
",",
"40",
"*",
"mm",
",",
"self",
".",
"height_line",
",",
"preserveAspectRatio",
"=",
"True",
",",
"anchor",
"=",
"'sw'",
")",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Helvetica-Bold'",
",",
"18",
")",
"self",
".",
"pdf_canvas",
".",
"drawCentredString",
"(",
"50",
"*",
"mm",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
"+",
"3",
",",
"boleto_dados",
".",
"codigo_dv_banco",
")",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Helvetica-Bold'",
",",
"11.5",
")",
"self",
".",
"pdf_canvas",
".",
"drawRightString",
"(",
"self",
".",
"width",
",",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
"+",
"3",
",",
"'Recibo do Sacado'",
")",
"# Titles",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Helvetica'",
",",
"6",
")",
"self",
".",
"delta_title",
"=",
"self",
".",
"height_line",
"-",
"(",
"6",
"+",
"1",
")",
"self",
".",
"pdf_canvas",
".",
"drawRightString",
"(",
"self",
".",
"width",
",",
"self",
".",
"height_line",
",",
"'Autenticação Mecânica'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Cedente'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"-",
"(",
"40",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Agência/Código Cedente'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'CPF/CNPJ Cedente'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Vencimento'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Sacado'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"-",
"(",
"40",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Nosso Número')",
"",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'N. do documento'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Data Documento'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Endereço Cedente'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Valor Documento'",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
"-",
"3",
"*",
"cm",
")",
")",
"+",
"self",
".",
"delta_title",
",",
"'Demonstrativo'",
")",
"# Values",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Helvetica'",
",",
"9",
")",
"heigh_font",
"=",
"9",
"+",
"1",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"cedente",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"-",
"(",
"40",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"agencia_conta_cedente",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"cedente_documento",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"2",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"data_vencimento",
".",
"strftime",
"(",
"'%d/%m/%Y'",
")",
")",
"# Take care of long field",
"sacado0",
"=",
"boleto_dados",
".",
"sacado",
"[",
"0",
"]",
"while",
"(",
"stringWidth",
"(",
"sacado0",
",",
"self",
".",
"pdf_canvas",
".",
"_fontname",
",",
"self",
".",
"pdf_canvas",
".",
"_fontsize",
")",
">",
"8.4",
"*",
"cm",
")",
":",
"# sacado0 = sacado0[:-2] + u'\\u2026'",
"sacado0",
"=",
"sacado0",
"[",
":",
"-",
"4",
"]",
"+",
"u'...'",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"sacado0",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"-",
"(",
"40",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"format_nosso_numero",
"(",
")",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"-",
"(",
"35",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"numero_documento",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"1",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"data_documento",
".",
"strftime",
"(",
"'%d/%m/%Y'",
")",
")",
"valor_documento",
"=",
"self",
".",
"_formataValorParaExibir",
"(",
"boleto_dados",
".",
"valor_documento",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"0",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"boleto_dados",
".",
"cedente_endereco",
")",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"self",
".",
"width",
"-",
"(",
"30",
"*",
"mm",
")",
"+",
"self",
".",
"space",
",",
"(",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
")",
")",
"+",
"self",
".",
"space",
",",
"valor_documento",
")",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Courier'",
",",
"9",
")",
"demonstrativo",
"=",
"boleto_dados",
".",
"demonstrativo",
"[",
"0",
":",
"25",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"demonstrativo",
")",
")",
":",
"self",
".",
"pdf_canvas",
".",
"drawString",
"(",
"2",
"*",
"self",
".",
"space",
",",
"(",
"-",
"3",
"*",
"cm",
"+",
"(",
"(",
"linha_inicial",
"+",
"0",
")",
"*",
"self",
".",
"height_line",
")",
")",
"-",
"(",
"i",
"*",
"heigh_font",
")",
",",
"demonstrativo",
"[",
"i",
"]",
")",
"self",
".",
"pdf_canvas",
".",
"setFont",
"(",
"'Helvetica'",
",",
"9",
")",
"self",
".",
"pdf_canvas",
".",
"restoreState",
"(",
")",
"return",
"(",
"self",
".",
"width",
",",
"(",
"(",
"linha_inicial",
"+",
"3",
")",
"*",
"self",
".",
"height_line",
")",
")"
] |
[
170,
4
] |
[
402,
69
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
greet_users
|
(names)
|
return msg
|
Exibe uma saudação simples a cada usuário da lista.
|
Exibe uma saudação simples a cada usuário da lista.
|
def greet_users(names):
"""Exibe uma saudação simples a cada usuário da lista."""
msg = 'Hello, ' + name.title() + '!'
return msg
|
[
"def",
"greet_users",
"(",
"names",
")",
":",
"msg",
"=",
"'Hello, '",
"+",
"name",
".",
"title",
"(",
")",
"+",
"'!'",
"return",
"msg"
] |
[
5,
0
] |
[
8,
14
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
RestClient.post
|
(self, url, request_data, content_type=None, auth_map=None)
|
Envia uma requisição POST.
Envia o parâmetro request_data no corpo da requisição e
retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
|
Envia uma requisição POST.
Envia o parâmetro request_data no corpo da requisição e
retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
|
def post(self, url, request_data, content_type=None, auth_map=None):
"""Envia uma requisição POST.
Envia o parâmetro request_data no corpo da requisição e
retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
"""
try:
request = Request(url)
request.add_data(request_data)
if auth_map is None:
request.add_header('NETWORKAPI_USERNAME', 'ORQUESTRACAO')
request.add_header(
'NETWORKAPI_PASSWORD', '93522a36bf2a18e0cc25857e06bbfe8b')
else:
for key, value in auth_map.iteritems():
request.add_header(key, value)
if content_type != None:
request.add_header('Content-Type', content_type)
content = urlopen(request).read()
response_code = 200
return response_code, content
except HTTPError, e:
response_code = e.code
content = e.read()
return response_code, content
except Exception, e:
raise RestError(e, e.message)
|
[
"def",
"post",
"(",
"self",
",",
"url",
",",
"request_data",
",",
"content_type",
"=",
"None",
",",
"auth_map",
"=",
"None",
")",
":",
"try",
":",
"request",
"=",
"Request",
"(",
"url",
")",
"request",
".",
"add_data",
"(",
"request_data",
")",
"if",
"auth_map",
"is",
"None",
":",
"request",
".",
"add_header",
"(",
"'NETWORKAPI_USERNAME'",
",",
"'ORQUESTRACAO'",
")",
"request",
".",
"add_header",
"(",
"'NETWORKAPI_PASSWORD'",
",",
"'93522a36bf2a18e0cc25857e06bbfe8b'",
")",
"else",
":",
"for",
"key",
",",
"value",
"in",
"auth_map",
".",
"iteritems",
"(",
")",
":",
"request",
".",
"add_header",
"(",
"key",
",",
"value",
")",
"if",
"content_type",
"!=",
"None",
":",
"request",
".",
"add_header",
"(",
"'Content-Type'",
",",
"content_type",
")",
"content",
"=",
"urlopen",
"(",
"request",
")",
".",
"read",
"(",
")",
"response_code",
"=",
"200",
"return",
"response_code",
",",
"content",
"except",
"HTTPError",
",",
"e",
":",
"response_code",
"=",
"e",
".",
"code",
"content",
"=",
"e",
".",
"read",
"(",
")",
"return",
"response_code",
",",
"content",
"except",
"Exception",
",",
"e",
":",
"raise",
"RestError",
"(",
"e",
",",
"e",
".",
"message",
")"
] |
[
75,
4
] |
[
104,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
perceive
|
(kb, loc)
|
return wumpus, pit, gold
|
Retorna uma tupla que contém as percepções locais do agente.
Devolve nenhuma se o agente foi morto pelo Wumpus ou caiu em um poço.
|
Retorna uma tupla que contém as percepções locais do agente.
Devolve nenhuma se o agente foi morto pelo Wumpus ou caiu em um poço.
|
def perceive(kb, loc):
"""Retorna uma tupla que contém as percepções locais do agente.
Devolve nenhuma se o agente foi morto pelo Wumpus ou caiu em um poço."""
if kb[loc].pit == Status.Present or kb[loc].wumpus == Status.Present:
# O agente foi morto e não há percepções
return None
# Construir percepções
wumpus, pit, gold = (Status.Absent,) * 3
# Olhar células vizinhas para atualizar as percepções
for room in [kb[l] for l in neighbors(loc)]:
# Verifique se o wumpus está nesta sala
if room.wumpus == Status.Present:
wumpus = Status.Present
elif room.wumpus == Status.LikelyPresent and wumpus != Status.Present:
wumpus = Status.LikelyPresent
# Verifique se há poços nesta sala
if room.pit == Status.Present:
pit = Status.Present
elif room.pit == Status.LikelyPresent and pit != Status.Present:
pit = Status.LikelyPresent
# Verifique se o ouro está nesta célula
if kb[loc].gold == Status.Present:
gold = Status.Present
# Retorna percepções como tupla
return wumpus, pit, gold
|
[
"def",
"perceive",
"(",
"kb",
",",
"loc",
")",
":",
"if",
"kb",
"[",
"loc",
"]",
".",
"pit",
"==",
"Status",
".",
"Present",
"or",
"kb",
"[",
"loc",
"]",
".",
"wumpus",
"==",
"Status",
".",
"Present",
":",
"# O agente foi morto e não há percepções",
"return",
"None",
"# Construir percepções",
"wumpus",
",",
"pit",
",",
"gold",
"=",
"(",
"Status",
".",
"Absent",
",",
")",
"*",
"3",
"# Olhar células vizinhas para atualizar as percepções",
"for",
"room",
"in",
"[",
"kb",
"[",
"l",
"]",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"]",
":",
"# Verifique se o wumpus está nesta sala",
"if",
"room",
".",
"wumpus",
"==",
"Status",
".",
"Present",
":",
"wumpus",
"=",
"Status",
".",
"Present",
"elif",
"room",
".",
"wumpus",
"==",
"Status",
".",
"LikelyPresent",
"and",
"wumpus",
"!=",
"Status",
".",
"Present",
":",
"wumpus",
"=",
"Status",
".",
"LikelyPresent",
"# Verifique se há poços nesta sala",
"if",
"room",
".",
"pit",
"==",
"Status",
".",
"Present",
":",
"pit",
"=",
"Status",
".",
"Present",
"elif",
"room",
".",
"pit",
"==",
"Status",
".",
"LikelyPresent",
"and",
"pit",
"!=",
"Status",
".",
"Present",
":",
"pit",
"=",
"Status",
".",
"LikelyPresent",
"# Verifique se o ouro está nesta célula",
"if",
"kb",
"[",
"loc",
"]",
".",
"gold",
"==",
"Status",
".",
"Present",
":",
"gold",
"=",
"Status",
".",
"Present",
"# Retorna percepções como tupla",
"return",
"wumpus",
",",
"pit",
",",
"gold"
] |
[
12,
0
] |
[
45,
26
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Item.nome
|
(self)
|
return self.__nome
|
Dar acesso a variavel privada __nome como propriedade.
Returns:
[int, float]: Leitura de valor no formato int ou float
|
Dar acesso a variavel privada __nome como propriedade.
|
def nome(self) -> str:
"""Dar acesso a variavel privada __nome como propriedade.
Returns:
[int, float]: Leitura de valor no formato int ou float
"""
return self.__nome
|
[
"def",
"nome",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"__nome"
] |
[
11,
4
] |
[
17,
26
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
NetworkData.get_scope_subnets
|
(cls, scope_name)
|
Retorna somente os itens de subnet de um escopo especifico.
|
Retorna somente os itens de subnet de um escopo especifico.
|
def get_scope_subnets(cls, scope_name):
""" Retorna somente os itens de subnet de um escopo especifico."""
for full_scope in NetworkData.yaml.networks:
scopes_name = list(full_scope.keys())
scopes_name = scopes_name[0]
if scopes_name == scope_name:
configs = (list(full_scope.values()))
subnets_list = ((configs[0][1]['subnets']))
return subnets_list
|
[
"def",
"get_scope_subnets",
"(",
"cls",
",",
"scope_name",
")",
":",
"for",
"full_scope",
"in",
"NetworkData",
".",
"yaml",
".",
"networks",
":",
"scopes_name",
"=",
"list",
"(",
"full_scope",
".",
"keys",
"(",
")",
")",
"scopes_name",
"=",
"scopes_name",
"[",
"0",
"]",
"if",
"scopes_name",
"==",
"scope_name",
":",
"configs",
"=",
"(",
"list",
"(",
"full_scope",
".",
"values",
"(",
")",
")",
")",
"subnets_list",
"=",
"(",
"(",
"configs",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"'subnets'",
"]",
")",
")",
"return",
"subnets_list"
] |
[
40,
4
] |
[
52,
35
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
show_magicians
|
(nomes)
|
return magico
|
Exibe uma lista com nomes de mágicos.
|
Exibe uma lista com nomes de mágicos.
|
def show_magicians(nomes):
"""Exibe uma lista com nomes de mágicos."""
magico = nome.title() # Atribui o valor nome.title() a variável criada mágico
return magico
|
[
"def",
"show_magicians",
"(",
"nomes",
")",
":",
"magico",
"=",
"nome",
".",
"title",
"(",
")",
"# Atribui o valor nome.title() a variável criada mágico",
"return",
"magico"
] |
[
5,
0
] |
[
8,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
GuessTest.test_match_almost
|
(self)
|
Cenário 4: Tentativa tem 1 exato e 1 fora de lugar
|
Cenário 4: Tentativa tem 1 exato e 1 fora de lugar
|
def test_match_almost(self):
""" Cenário 4: Tentativa tem 1 exato e 1 fora de lugar """
self.assertEqual(guess.match('1234', '1528'), '+-*-')
|
[
"def",
"test_match_almost",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"guess",
".",
"match",
"(",
"'1234'",
",",
"'1528'",
")",
",",
"'+-*-'",
")"
] |
[
15,
4
] |
[
17,
61
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
acha_intervalo_aprx_suc
|
(phi)
|
Da uma dica pra achar o intervalo
|
Da uma dica pra achar o intervalo
|
def acha_intervalo_aprx_suc(phi):
''' Da uma dica pra achar o intervalo'''
phi_ = diff(phi)
sol1 = solve(phi_)
sol0 = solve(phi_ + 1)
sol2 = solve(phi_ - 1)
if len(sol1) != len(sol0) or len(sol0) != len(sol2):
print(sol0)
print(sol1)
print(sol2)
else:
for i in range(len(sol0)):
print(sol0[i].evalf(), '|', sol1[i].evalf(), '|', sol2[i].evalf())
|
[
"def",
"acha_intervalo_aprx_suc",
"(",
"phi",
")",
":",
"phi_",
"=",
"diff",
"(",
"phi",
")",
"sol1",
"=",
"solve",
"(",
"phi_",
")",
"sol0",
"=",
"solve",
"(",
"phi_",
"+",
"1",
")",
"sol2",
"=",
"solve",
"(",
"phi_",
"-",
"1",
")",
"if",
"len",
"(",
"sol1",
")",
"!=",
"len",
"(",
"sol0",
")",
"or",
"len",
"(",
"sol0",
")",
"!=",
"len",
"(",
"sol2",
")",
":",
"print",
"(",
"sol0",
")",
"print",
"(",
"sol1",
")",
"print",
"(",
"sol2",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sol0",
")",
")",
":",
"print",
"(",
"sol0",
"[",
"i",
"]",
".",
"evalf",
"(",
")",
",",
"'|'",
",",
"sol1",
"[",
"i",
"]",
".",
"evalf",
"(",
")",
",",
"'|'",
",",
"sol2",
"[",
"i",
"]",
".",
"evalf",
"(",
")",
")"
] |
[
125,
0
] |
[
138,
78
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
EquipamentoAmbiente.remove
|
(cls, authenticated_user, equip_id, environ_id)
|
Pesquisa e remove uma associação entre um Equipamento e um Ambiente.
@return: Nothing
@raise EquipamentoAmbienteNotFoundError: Não existe associação entre o equipamento e o ambiente.
@raise EquipamentoError: Falha ao remover uma associação entre um Equipamento e um Ambiente.
|
Pesquisa e remove uma associação entre um Equipamento e um Ambiente.
|
def remove(cls, authenticated_user, equip_id, environ_id):
"""Pesquisa e remove uma associação entre um Equipamento e um Ambiente.
@return: Nothing
@raise EquipamentoAmbienteNotFoundError: Não existe associação entre o equipamento e o ambiente.
@raise EquipamentoError: Falha ao remover uma associação entre um Equipamento e um Ambiente.
"""
try:
equipenvironment = EquipamentoAmbiente.objects.get(
equipamento__id=equip_id, ambiente__id=environ_id)
equipenvironment.delete()
except ObjectDoesNotExist, n:
cls.log.error(u'Não existe um equipamento_ambiente com o equipamento = %s e o ambiente = %s.' % (
equip_id, environ_id))
raise EquipamentoAmbienteNotFoundError(
n, u'Não existe um equipamento_ambiente com o equipamento = %s e o ambiente = %s.' % (equip_id, environ_id))
except Exception as e:
cls.log.error(
u'Falha ao remover uma associação entre um Equipamento e um Ambiente.')
raise EquipamentoError(
e, u'Falha ao remover uma associação entre um Equipamento e um Ambiente.')
|
[
"def",
"remove",
"(",
"cls",
",",
"authenticated_user",
",",
"equip_id",
",",
"environ_id",
")",
":",
"try",
":",
"equipenvironment",
"=",
"EquipamentoAmbiente",
".",
"objects",
".",
"get",
"(",
"equipamento__id",
"=",
"equip_id",
",",
"ambiente__id",
"=",
"environ_id",
")",
"equipenvironment",
".",
"delete",
"(",
")",
"except",
"ObjectDoesNotExist",
",",
"n",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Não existe um equipamento_ambiente com o equipamento = %s e o ambiente = %s.' ",
" ",
"",
"equip_id",
",",
"environ_id",
")",
")",
"raise",
"EquipamentoAmbienteNotFoundError",
"(",
"n",
",",
"u'Não existe um equipamento_ambiente com o equipamento = %s e o ambiente = %s.' ",
" ",
"e",
"quip_id,",
" ",
"nviron_id)",
")",
"",
"except",
"Exception",
"as",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao remover uma associação entre um Equipamento e um Ambiente.')",
"",
"raise",
"EquipamentoError",
"(",
"e",
",",
"u'Falha ao remover uma associação entre um Equipamento e um Ambiente.')",
""
] |
[
1391,
4
] |
[
1415,
92
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
GrupoEquipamentoResource.handle_get
|
(self, request, user, *args, **kwargs)
|
Trata as requisições de GET para listar todos os grupos de equipamento.
URL: egrupo/$
|
Trata as requisições de GET para listar todos os grupos de equipamento.
|
def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições de GET para listar todos os grupos de equipamento.
URL: egrupo/$
"""
try:
if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
egroups = EGrupo.search()
map_list = []
for egroup in egroups:
egroup_map = dict()
egroup_map['id'] = egroup.id
egroup_map['nome'] = egroup.nome
map_list.append(egroup_map)
return self.response(dumps_networkapi({'grupo': map_list}))
except (GrupoError):
return self.response_error(1)
|
[
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_GROUP_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"egroups",
"=",
"EGrupo",
".",
"search",
"(",
")",
"map_list",
"=",
"[",
"]",
"for",
"egroup",
"in",
"egroups",
":",
"egroup_map",
"=",
"dict",
"(",
")",
"egroup_map",
"[",
"'id'",
"]",
"=",
"egroup",
".",
"id",
"egroup_map",
"[",
"'nome'",
"]",
"=",
"egroup",
".",
"nome",
"map_list",
".",
"append",
"(",
"egroup_map",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'grupo'",
":",
"map_list",
"}",
")",
")",
"except",
"(",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] |
[
41,
4
] |
[
63,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
UsuarioGetResource.handle_get
|
(self, request, user, *args, **kwargs)
|
Trata as requisições de GET para listar Usuarios.
URLs: usuario/get/$
|
Trata as requisições de GET para listar Usuarios.
|
def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições de GET para listar Usuarios.
URLs: usuario/get/$
"""
try:
if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.READ_OPERATION):
return self.not_authorized()
list_groups = []
user_groups_list = []
map_list = []
for user in Usuario.objects.all():
user_map = dict()
user_map['id'] = user.id
user_map['user'] = user.user
user_map['nome'] = user.nome
user_map['ativo'] = user.ativo
user_map['email'] = user.email
groups = None
groups = UsuarioGrupo.list_by_user_id(user.id)
if groups is not None and len(groups) > 0:
for group in groups:
user_groups_list.append(
UGrupo.get_by_pk(group.ugrupo_id))
for user_group in user_groups_list:
list_groups.append(user_group.nome)
if (len(list_groups) > 3):
user_map['is_more'] = True
else:
user_map['is_more'] = False
user_map['grupos'] = list_groups if len(
list_groups) > 0 else [None]
list_groups = []
user_groups_list = []
map_list.append(user_map)
return self.response(dumps_networkapi({'usuario': map_list}))
except UserNotAuthorizedError:
return self.not_authorized()
except (UsuarioError, GrupoError):
return self.response_error(1)
|
[
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"USER_ADMINISTRATION",
",",
"AdminPermission",
".",
"READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"list_groups",
"=",
"[",
"]",
"user_groups_list",
"=",
"[",
"]",
"map_list",
"=",
"[",
"]",
"for",
"user",
"in",
"Usuario",
".",
"objects",
".",
"all",
"(",
")",
":",
"user_map",
"=",
"dict",
"(",
")",
"user_map",
"[",
"'id'",
"]",
"=",
"user",
".",
"id",
"user_map",
"[",
"'user'",
"]",
"=",
"user",
".",
"user",
"user_map",
"[",
"'nome'",
"]",
"=",
"user",
".",
"nome",
"user_map",
"[",
"'ativo'",
"]",
"=",
"user",
".",
"ativo",
"user_map",
"[",
"'email'",
"]",
"=",
"user",
".",
"email",
"groups",
"=",
"None",
"groups",
"=",
"UsuarioGrupo",
".",
"list_by_user_id",
"(",
"user",
".",
"id",
")",
"if",
"groups",
"is",
"not",
"None",
"and",
"len",
"(",
"groups",
")",
">",
"0",
":",
"for",
"group",
"in",
"groups",
":",
"user_groups_list",
".",
"append",
"(",
"UGrupo",
".",
"get_by_pk",
"(",
"group",
".",
"ugrupo_id",
")",
")",
"for",
"user_group",
"in",
"user_groups_list",
":",
"list_groups",
".",
"append",
"(",
"user_group",
".",
"nome",
")",
"if",
"(",
"len",
"(",
"list_groups",
")",
">",
"3",
")",
":",
"user_map",
"[",
"'is_more'",
"]",
"=",
"True",
"else",
":",
"user_map",
"[",
"'is_more'",
"]",
"=",
"False",
"user_map",
"[",
"'grupos'",
"]",
"=",
"list_groups",
"if",
"len",
"(",
"list_groups",
")",
">",
"0",
"else",
"[",
"None",
"]",
"list_groups",
"=",
"[",
"]",
"user_groups_list",
"=",
"[",
"]",
"map_list",
".",
"append",
"(",
"user_map",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'usuario'",
":",
"map_list",
"}",
")",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"(",
"UsuarioError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] |
[
32,
4
] |
[
82,
41
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
SistemaLivros.listar_livros
|
(self)
|
Lista todos os livros existentes no sistema, exibindo
somente seu titulo e autor, idependente de conter outros
dados
|
Lista todos os livros existentes no sistema, exibindo
somente seu titulo e autor, idependente de conter outros
dados
|
def listar_livros(self):
""" Lista todos os livros existentes no sistema, exibindo
somente seu titulo e autor, idependente de conter outros
dados """
for dado in self.dados:
titulo = dado["titulo"]
autor = dado["autor"]
print(f"Título: {titulo}\nAutor: {autor}\n")
|
[
"def",
"listar_livros",
"(",
"self",
")",
":",
"for",
"dado",
"in",
"self",
".",
"dados",
":",
"titulo",
"=",
"dado",
"[",
"\"titulo\"",
"]",
"autor",
"=",
"dado",
"[",
"\"autor\"",
"]",
"print",
"(",
"f\"Título: {titulo}\\nAutor: {autor}\\n\")",
""
] |
[
45,
4
] |
[
52,
57
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
test_get_interventions_by_reason
|
(client)
|
Teste get /intervention/reasons - Compara quantidade de rasões enviadas com quantidade salva no banco e valida status_code 200
|
Teste get /intervention/reasons - Compara quantidade de rasões enviadas com quantidade salva no banco e valida status_code 200
|
def test_get_interventions_by_reason(client):
"""Teste get /intervention/reasons - Compara quantidade de rasões enviadas com quantidade salva no banco e valida status_code 200"""
access_token = get_access(client)
qtdReasons = session.query(InterventionReason).count()
response = client.get('/intervention/reasons', headers=make_headers(access_token))
data = json.loads(response.data)['data']
assert response.status_code == 200
assert qtdReasons == len(data)
|
[
"def",
"test_get_interventions_by_reason",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"qtdReasons",
"=",
"session",
".",
"query",
"(",
"InterventionReason",
")",
".",
"count",
"(",
")",
"response",
"=",
"client",
".",
"get",
"(",
"'/intervention/reasons'",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")",
"[",
"'data'",
"]",
"assert",
"response",
".",
"status_code",
"==",
"200",
"assert",
"qtdReasons",
"==",
"len",
"(",
"data",
")"
] |
[
17,
0
] |
[
27,
34
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
campo_tem_algum_numero
|
(valor_campo, nome_campo, lista_de_erros)
|
Verifica se possui algum dígito numérico
|
Verifica se possui algum dígito numérico
|
def campo_tem_algum_numero(valor_campo, nome_campo, lista_de_erros):
"""Verifica se possui algum dígito numérico"""
if any(char.isdigit() for char in valor_campo):
lista_de_erros[nome_campo] = "Não inclua números nesse campo"
|
[
"def",
"campo_tem_algum_numero",
"(",
"valor_campo",
",",
"nome_campo",
",",
"lista_de_erros",
")",
":",
"if",
"any",
"(",
"char",
".",
"isdigit",
"(",
")",
"for",
"char",
"in",
"valor_campo",
")",
":",
"lista_de_erros",
"[",
"nome_campo",
"]",
"=",
"\"Não inclua números nesse campo\""
] |
[
8,
0
] |
[
11,
71
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
ask
|
(kb, loc, direction, goal)
|
return None
|
Retorna uma ação de acordo com o estado atual do conhecimento.
A ação é uma tupla: o primeiro elemento é o tipo da ação,
o segundo elemento é uma lista de movimento se o tipo é Action.Move ou atirar,
e o terceiro (caso contrário), é none.
|
Retorna uma ação de acordo com o estado atual do conhecimento.
A ação é uma tupla: o primeiro elemento é o tipo da ação,
o segundo elemento é uma lista de movimento se o tipo é Action.Move ou atirar,
e o terceiro (caso contrário), é none.
|
def ask(kb, loc, direction, goal):
"""Retorna uma ação de acordo com o estado atual do conhecimento.
A ação é uma tupla: o primeiro elemento é o tipo da ação,
o segundo elemento é uma lista de movimento se o tipo é Action.Move ou atirar,
e o terceiro (caso contrário), é none."""
# Se o agente está procurando ouro
if goal == Goal.SeekGold:
# Verifica se esta sala contém o ouro
if kb[loc].gold == Status.Present:
return Action.Grab, None
# Obtém o primeiro quarto vizinho seguro e inexplorado (se houver)
state = lambda r: r.is_safe() and r.is_unexplored
dest = next((l for l in neighbors(loc) if state(kb[l])), None)
if dest:
return Action.Move, (spins(loc, direction, dest),)
# Obtém qualquer espaço seguro e inexplorado (se o agente pode alcançá-lo)
state = lambda r, l: r.is_safe() and any(kb[x].is_explored for x in neighbors(l))
dest = next((l for l in kb.unexplored if state(kb[l], l)), None)
if dest:
path = known_path(kb, loc, dest)
return Action.Move, path_to_spins(path, direction)
# Obtém uma sala vizinha que pode conter o Wumpus, mas sem poços
state = lambda r: r.is_safe(Entity.Pit) and r.is_unsafe(Entity.Wumpus)
dest = next((l for l in neighbors(loc) if state(kb[l])), None)
if dest:
return Action.Shoot, spins(loc, direction, dest)
# Obtém um quarto que podem conter o Wumpus mas não poços
state = lambda r: r.is_safe(Entity.Pit) and r.is_unsafe(Entity.Wumpus)
dest = next((l for l in kb.unexplored if state(kb[l])), None)
if dest:
# Obtém uma célula vizinha explorada
dest = next((l for l in neighbors(dest) if kb[l].is_explored))
path = known_path(kb, loc, dest)
return Action.Move, path_to_spins(path, direction)
# Obtém um quarto vizinho que pode conter o Wumpus
state = lambda r: r.is_dangerous(Entity.Wumpus)
dest = next((l for l in neighbors(loc) if state(kb[l])), None)
if dest:
return Action.Shoot, spins(loc, direction, dest)
# Obtém um quarto vizinho que pode conter um poço
rooms = [l for l in kb.unexplored if kb[l].is_dangerous(Entity.Pit)]
if rooms:
dest = random.choice(rooms)
path = known_path(kb, loc, dest)
return Action.Move, path_to_spins(path, direction)
# Obtém uma célula inexplorada
dest = next((l for l in kb.unexplored), None)
if dest:
path = known_path(kb, loc, dest)
return Action.Move, path_to_spins(path, direction)
elif goal == Goal.BackToEntry:
# Voltar para a entrada
path = known_path(kb, loc, (0, 0))
return Action.Move, path_to_spins(path, direction)
# Incapaz de encontrar uma ação
return None
|
[
"def",
"ask",
"(",
"kb",
",",
"loc",
",",
"direction",
",",
"goal",
")",
":",
"# Se o agente está procurando ouro",
"if",
"goal",
"==",
"Goal",
".",
"SeekGold",
":",
"# Verifica se esta sala contém o ouro",
"if",
"kb",
"[",
"loc",
"]",
".",
"gold",
"==",
"Status",
".",
"Present",
":",
"return",
"Action",
".",
"Grab",
",",
"None",
"# Obtém o primeiro quarto vizinho seguro e inexplorado (se houver)",
"state",
"=",
"lambda",
"r",
":",
"r",
".",
"is_safe",
"(",
")",
"and",
"r",
".",
"is_unexplored",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"if",
"state",
"(",
"kb",
"[",
"l",
"]",
")",
")",
",",
"None",
")",
"if",
"dest",
":",
"return",
"Action",
".",
"Move",
",",
"(",
"spins",
"(",
"loc",
",",
"direction",
",",
"dest",
")",
",",
")",
"# Obtém qualquer espaço seguro e inexplorado (se o agente pode alcançá-lo)",
"state",
"=",
"lambda",
"r",
",",
"l",
":",
"r",
".",
"is_safe",
"(",
")",
"and",
"any",
"(",
"kb",
"[",
"x",
"]",
".",
"is_explored",
"for",
"x",
"in",
"neighbors",
"(",
"l",
")",
")",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"kb",
".",
"unexplored",
"if",
"state",
"(",
"kb",
"[",
"l",
"]",
",",
"l",
")",
")",
",",
"None",
")",
"if",
"dest",
":",
"path",
"=",
"known_path",
"(",
"kb",
",",
"loc",
",",
"dest",
")",
"return",
"Action",
".",
"Move",
",",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
"# Obtém uma sala vizinha que pode conter o Wumpus, mas sem poços",
"state",
"=",
"lambda",
"r",
":",
"r",
".",
"is_safe",
"(",
"Entity",
".",
"Pit",
")",
"and",
"r",
".",
"is_unsafe",
"(",
"Entity",
".",
"Wumpus",
")",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"if",
"state",
"(",
"kb",
"[",
"l",
"]",
")",
")",
",",
"None",
")",
"if",
"dest",
":",
"return",
"Action",
".",
"Shoot",
",",
"spins",
"(",
"loc",
",",
"direction",
",",
"dest",
")",
"# Obtém um quarto que podem conter o Wumpus mas não poços",
"state",
"=",
"lambda",
"r",
":",
"r",
".",
"is_safe",
"(",
"Entity",
".",
"Pit",
")",
"and",
"r",
".",
"is_unsafe",
"(",
"Entity",
".",
"Wumpus",
")",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"kb",
".",
"unexplored",
"if",
"state",
"(",
"kb",
"[",
"l",
"]",
")",
")",
",",
"None",
")",
"if",
"dest",
":",
"# Obtém uma célula vizinha explorada ",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"neighbors",
"(",
"dest",
")",
"if",
"kb",
"[",
"l",
"]",
".",
"is_explored",
")",
")",
"path",
"=",
"known_path",
"(",
"kb",
",",
"loc",
",",
"dest",
")",
"return",
"Action",
".",
"Move",
",",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
"# Obtém um quarto vizinho que pode conter o Wumpus",
"state",
"=",
"lambda",
"r",
":",
"r",
".",
"is_dangerous",
"(",
"Entity",
".",
"Wumpus",
")",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"if",
"state",
"(",
"kb",
"[",
"l",
"]",
")",
")",
",",
"None",
")",
"if",
"dest",
":",
"return",
"Action",
".",
"Shoot",
",",
"spins",
"(",
"loc",
",",
"direction",
",",
"dest",
")",
"# Obtém um quarto vizinho que pode conter um poço",
"rooms",
"=",
"[",
"l",
"for",
"l",
"in",
"kb",
".",
"unexplored",
"if",
"kb",
"[",
"l",
"]",
".",
"is_dangerous",
"(",
"Entity",
".",
"Pit",
")",
"]",
"if",
"rooms",
":",
"dest",
"=",
"random",
".",
"choice",
"(",
"rooms",
")",
"path",
"=",
"known_path",
"(",
"kb",
",",
"loc",
",",
"dest",
")",
"return",
"Action",
".",
"Move",
",",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
"# Obtém uma célula inexplorada",
"dest",
"=",
"next",
"(",
"(",
"l",
"for",
"l",
"in",
"kb",
".",
"unexplored",
")",
",",
"None",
")",
"if",
"dest",
":",
"path",
"=",
"known_path",
"(",
"kb",
",",
"loc",
",",
"dest",
")",
"return",
"Action",
".",
"Move",
",",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
"elif",
"goal",
"==",
"Goal",
".",
"BackToEntry",
":",
"# Voltar para a entrada",
"path",
"=",
"known_path",
"(",
"kb",
",",
"loc",
",",
"(",
"0",
",",
"0",
")",
")",
"return",
"Action",
".",
"Move",
",",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
"# Incapaz de encontrar uma ação",
"return",
"None"
] |
[
112,
0
] |
[
181,
13
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
MainProgram.CreateImage
|
(self, path)
|
return TkImage
|
Cria um objeto de imagem ImageTk proporcial a resolução da tela.
No primeiro parâmetro do método ImageFile.resize é passado uma tupla
contendo as medidas x e y para a criação da imagem. Essas medidas são
armazenadas nas variáveis xSize e ySize.
Parâmetros
----------
path: string
Caminho das imagens
|
Cria um objeto de imagem ImageTk proporcial a resolução da tela.
No primeiro parâmetro do método ImageFile.resize é passado uma tupla
contendo as medidas x e y para a criação da imagem. Essas medidas são
armazenadas nas variáveis xSize e ySize.
|
def CreateImage(self, path):
"""Cria um objeto de imagem ImageTk proporcial a resolução da tela.
No primeiro parâmetro do método ImageFile.resize é passado uma tupla
contendo as medidas x e y para a criação da imagem. Essas medidas são
armazenadas nas variáveis xSize e ySize.
Parâmetros
----------
path: string
Caminho das imagens
"""
ImageFile = Image.open(path)
ImageWidth, ImageHeight = ImageFile.size
if self.WindowsZoom == 100:
xSize = ImageWidth
ySize = ImageHeight
elif self.WindowsZoom == 125:
xSize = ImageWidth - (ImageWidth * 0.25)
ySize = ImageHeight - (ImageHeight * 0.25)
elif self.WindowsZoom == 150:
xSize = ImageWidth - (ImageWidth * 0.50)
ySize = ImageHeight - (ImageHeight * 0.50)
elif self.WindowsZoom == 175:
xSize = ImageWidth - (ImageWidth * 0.75)
ySize = ImageHeight - (ImageHeight * 0.75)
TkImage = ImageTk.PhotoImage(ImageFile.resize((int(xSize), int(ySize)), Image.ANTIALIAS))
return TkImage
|
[
"def",
"CreateImage",
"(",
"self",
",",
"path",
")",
":",
"ImageFile",
"=",
"Image",
".",
"open",
"(",
"path",
")",
"ImageWidth",
",",
"ImageHeight",
"=",
"ImageFile",
".",
"size",
"if",
"self",
".",
"WindowsZoom",
"==",
"100",
":",
"xSize",
"=",
"ImageWidth",
"ySize",
"=",
"ImageHeight",
"elif",
"self",
".",
"WindowsZoom",
"==",
"125",
":",
"xSize",
"=",
"ImageWidth",
"-",
"(",
"ImageWidth",
"*",
"0.25",
")",
"ySize",
"=",
"ImageHeight",
"-",
"(",
"ImageHeight",
"*",
"0.25",
")",
"elif",
"self",
".",
"WindowsZoom",
"==",
"150",
":",
"xSize",
"=",
"ImageWidth",
"-",
"(",
"ImageWidth",
"*",
"0.50",
")",
"ySize",
"=",
"ImageHeight",
"-",
"(",
"ImageHeight",
"*",
"0.50",
")",
"elif",
"self",
".",
"WindowsZoom",
"==",
"175",
":",
"xSize",
"=",
"ImageWidth",
"-",
"(",
"ImageWidth",
"*",
"0.75",
")",
"ySize",
"=",
"ImageHeight",
"-",
"(",
"ImageHeight",
"*",
"0.75",
")",
"TkImage",
"=",
"ImageTk",
".",
"PhotoImage",
"(",
"ImageFile",
".",
"resize",
"(",
"(",
"int",
"(",
"xSize",
")",
",",
"int",
"(",
"ySize",
")",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
")",
"return",
"TkImage"
] |
[
122,
4
] |
[
156,
22
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
div
|
(x :int, y: int)
|
Função de divisão.
|
Função de divisão.
|
def div(x :int, y: int) -> int:
"""Função de divisão."""
try:
return x / y
except ZeroDivisionError:
return 'Divisao por zero mal sucedida!!'
|
[
"def",
"div",
"(",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"int",
":",
"try",
":",
"return",
"x",
"/",
"y",
"except",
"ZeroDivisionError",
":",
"return",
"'Divisao por zero mal sucedida!!'"
] |
[
15,
0
] |
[
21,
48
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
flatten_list
|
(_list: list)
|
return f_list
|
Retorna uma lista nivelada, isto é, retira todo e qualquer aninhamento existente.
Args:
_list (list): Lista inicial que deseja nivelar.
Returns:
list: Lista nivelada, ou seja, sem aninhamento.
|
Retorna uma lista nivelada, isto é, retira todo e qualquer aninhamento existente.
|
def flatten_list(_list: list):
"""Retorna uma lista nivelada, isto é, retira todo e qualquer aninhamento existente.
Args:
_list (list): Lista inicial que deseja nivelar.
Returns:
list: Lista nivelada, ou seja, sem aninhamento.
"""
f_list = []
for element in _list:
if type(element) != list:
f_list.append(element)
else:
f_list.extend(flatten_list(element))
return f_list
|
[
"def",
"flatten_list",
"(",
"_list",
":",
"list",
")",
":",
"f_list",
"=",
"[",
"]",
"for",
"element",
"in",
"_list",
":",
"if",
"type",
"(",
"element",
")",
"!=",
"list",
":",
"f_list",
".",
"append",
"(",
"element",
")",
"else",
":",
"f_list",
".",
"extend",
"(",
"flatten_list",
"(",
"element",
")",
")",
"return",
"f_list"
] |
[
7,
0
] |
[
25,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Estado_de_um_orcamento.aplica_desconto_extra
|
(self, orçamento: Orcamento)
|
Método abstrato. Obrigatoriedade de implementação na classe filha.
Args:
orçameto (Class Orçamento): valor do orçamento.
|
Método abstrato. Obrigatoriedade de implementação na classe filha.
|
def aplica_desconto_extra(self, orçamento: Orcamento) -> float:
"""Método abstrato. Obrigatoriedade de implementação na classe filha.
Args:
orçameto (Class Orçamento): valor do orçamento.
"""
pass
|
[
"def",
"aplica_desconto_extra",
"(",
"self",
",",
"or",
"ça",
"mento:",
" ",
"rcamento)",
" ",
"> ",
"loat:",
"",
"pass"
] |
[
104,
4
] |
[
110,
12
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
MeuJogador.resultado_da_cacada
|
(self, comida_ganha)
|
Dá os retornos a cada rodada dos jogadores
|
Dá os retornos a cada rodada dos jogadores
|
def resultado_da_cacada(self, comida_ganha):
""" Dá os retornos a cada rodada dos jogadores """
pass
|
[
"def",
"resultado_da_cacada",
"(",
"self",
",",
"comida_ganha",
")",
":",
"pass"
] |
[
35,
4
] |
[
37,
12
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
is_symbol
|
(s)
|
return isinstance(s, str) and s[:1].isalpha()
|
Um string s é um símbolo se ele começa com um caracter alfabético.
|
Um string s é um símbolo se ele começa com um caracter alfabético.
|
def is_symbol(s):
"Um string s é um símbolo se ele começa com um caracter alfabético."
return isinstance(s, str) and s[:1].isalpha()
|
[
"def",
"is_symbol",
"(",
"s",
")",
":",
"return",
"isinstance",
"(",
"s",
",",
"str",
")",
"and",
"s",
"[",
":",
"1",
"]",
".",
"isalpha",
"(",
")"
] |
[
126,
0
] |
[
128,
49
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
BaseDoc.validate_list
|
(self, docs: List[str])
|
return [self.validate(doc) for doc in docs]
|
Método para validar uma lista de documentos desejado.
|
Método para validar uma lista de documentos desejado.
|
def validate_list(self, docs: List[str]) -> List[bool]:
"""Método para validar uma lista de documentos desejado."""
return [self.validate(doc) for doc in docs]
|
[
"def",
"validate_list",
"(",
"self",
",",
"docs",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"return",
"[",
"self",
".",
"validate",
"(",
"doc",
")",
"for",
"doc",
"in",
"docs",
"]"
] |
[
11,
4
] |
[
13,
51
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Contrato.tipo
|
(self)
|
return self.__tipo
|
Da acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido
|
Da acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido
|
def tipo(self) -> str:
"""Da acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido"""
return self.__tipo
|
[
"def",
"tipo",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"__tipo"
] |
[
32,
4
] |
[
35,
26
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
_req_pagseguro
|
(params)
|
return retorno
|
Faz requisição de validação ao PagSeguro
|
Faz requisição de validação ao PagSeguro
|
def _req_pagseguro(params):
""" Faz requisição de validação ao PagSeguro """
params_encode = urllib.urlencode(params)
res = urllib.urlopen('https://pagseguro.uol.com.br/Security/NPI/Default.aspx', params_encode)
retorno = res.read()
res.close()
return retorno
|
[
"def",
"_req_pagseguro",
"(",
"params",
")",
":",
"params_encode",
"=",
"urllib",
".",
"urlencode",
"(",
"params",
")",
"res",
"=",
"urllib",
".",
"urlopen",
"(",
"'https://pagseguro.uol.com.br/Security/NPI/Default.aspx'",
",",
"params_encode",
")",
"retorno",
"=",
"res",
".",
"read",
"(",
")",
"res",
".",
"close",
"(",
")",
"return",
"retorno"
] |
[
122,
0
] |
[
128,
18
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
get_hashtags
|
(df: pd.DataFrame)
|
return hashtags_df
|
Função para extrair hashtags de uma coluna com strings no formato: '['hashtag1', 'hashtag2']'
|
Função para extrair hashtags de uma coluna com strings no formato: '['hashtag1', 'hashtag2']'
|
def get_hashtags(df: pd.DataFrame) -> pd.DataFrame:
"Função para extrair hashtags de uma coluna com strings no formato: '['hashtag1', 'hashtag2']' "
all_hashtags = []
for i in range(len(df)):
raw = df["hashtags"].iloc[i][1:-1]
if len(raw) == 0: continue
hashtags = [tag_to_clean.strip()[1:-1] for tag_to_clean in raw.split(",")]
all_hashtags.extend(hashtags)
hashtags_df = pd.DataFrame(all_hashtags, columns=["hashtag"])
return hashtags_df
|
[
"def",
"get_hashtags",
"(",
"df",
":",
"pd",
".",
"DataFrame",
")",
"->",
"pd",
".",
"DataFrame",
":",
"all_hashtags",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"df",
")",
")",
":",
"raw",
"=",
"df",
"[",
"\"hashtags\"",
"]",
".",
"iloc",
"[",
"i",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"len",
"(",
"raw",
")",
"==",
"0",
":",
"continue",
"hashtags",
"=",
"[",
"tag_to_clean",
".",
"strip",
"(",
")",
"[",
"1",
":",
"-",
"1",
"]",
"for",
"tag_to_clean",
"in",
"raw",
".",
"split",
"(",
"\",\"",
")",
"]",
"all_hashtags",
".",
"extend",
"(",
"hashtags",
")",
"hashtags_df",
"=",
"pd",
".",
"DataFrame",
"(",
"all_hashtags",
",",
"columns",
"=",
"[",
"\"hashtag\"",
"]",
")",
"return",
"hashtags_df"
] |
[
65,
0
] |
[
77,
22
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Wall.__satisfaction_test
|
(self, wall)
|
return "Sim" if c_wall.issubset(self.__joint_set) else "Não"
|
Tenta construir uma parede seguindo as regras do problema
|
Tenta construir uma parede seguindo as regras do problema
|
def __satisfaction_test(self, wall):
"""Tenta construir uma parede seguindo as regras do problema"""
if list(filter(lambda x: not self.__is_permutation(x), wall)) != []:
return False
c_wall = chain.from_iterable(map(acc_sum, wall))
if UNIQUE(list(c_wall)):
c_wall = set(c_wall)
else:
return False
print(c_wall)
print(self.__joint_set)
return "Sim" if c_wall.issubset(self.__joint_set) else "Não"
|
[
"def",
"__satisfaction_test",
"(",
"self",
",",
"wall",
")",
":",
"if",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"not",
"self",
".",
"__is_permutation",
"(",
"x",
")",
",",
"wall",
")",
")",
"!=",
"[",
"]",
":",
"return",
"False",
"c_wall",
"=",
"chain",
".",
"from_iterable",
"(",
"map",
"(",
"acc_sum",
",",
"wall",
")",
")",
"if",
"UNIQUE",
"(",
"list",
"(",
"c_wall",
")",
")",
":",
"c_wall",
"=",
"set",
"(",
"c_wall",
")",
"else",
":",
"return",
"False",
"print",
"(",
"c_wall",
")",
"print",
"(",
"self",
".",
"__joint_set",
")",
"return",
"\"Sim\"",
"if",
"c_wall",
".",
"issubset",
"(",
"self",
".",
"__joint_set",
")",
"else",
"\"Não\""
] |
[
36,
4
] |
[
48,
69
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
create_fleet
|
(ai_settings, screen, ship, aliens)
|
Cria uma frota completa de alienigenas.
|
Cria uma frota completa de alienigenas.
|
def create_fleet(ai_settings, screen, ship, aliens):
"""Cria uma frota completa de alienigenas."""
# Cria um alienigena e calcula o numero de alienigenas em uma linha
alien = Alien(ai_settings, screen)
number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
# Cria a frota de alienigenas
for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
create_alien(ai_settings, screen, aliens, alien_number, row_number)
|
[
"def",
"create_fleet",
"(",
"ai_settings",
",",
"screen",
",",
"ship",
",",
"aliens",
")",
":",
"# Cria um alienigena e calcula o numero de alienigenas em uma linha",
"alien",
"=",
"Alien",
"(",
"ai_settings",
",",
"screen",
")",
"number_aliens_x",
"=",
"get_number_aliens_x",
"(",
"ai_settings",
",",
"alien",
".",
"rect",
".",
"width",
")",
"number_rows",
"=",
"get_number_rows",
"(",
"ai_settings",
",",
"ship",
".",
"rect",
".",
"height",
",",
"alien",
".",
"rect",
".",
"height",
")",
"# Cria a frota de alienigenas",
"for",
"row_number",
"in",
"range",
"(",
"number_rows",
")",
":",
"for",
"alien_number",
"in",
"range",
"(",
"number_aliens_x",
")",
":",
"create_alien",
"(",
"ai_settings",
",",
"screen",
",",
"aliens",
",",
"alien_number",
",",
"row_number",
")"
] |
[
173,
0
] |
[
183,
78
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
make_factor
|
(var, e, bn)
|
return Factor(variables, cpt)
|
Retorne o fator para a distribuição conjunta var in bn dada e.
Ou seja, a distribuição conjunta completa da bn, projetada de acordo com e,
É o produto pontual desses fatores para as variáveis de bn.
|
Retorne o fator para a distribuição conjunta var in bn dada e.
Ou seja, a distribuição conjunta completa da bn, projetada de acordo com e,
É o produto pontual desses fatores para as variáveis de bn.
|
def make_factor(var, e, bn):
"""Retorne o fator para a distribuição conjunta var in bn dada e.
Ou seja, a distribuição conjunta completa da bn, projetada de acordo com e,
É o produto pontual desses fatores para as variáveis de bn."""
node = bn.variable_node(var)
variables = [X for X in [var] + node.parents if X not in e]
cpt = {
event_values(e1, variables): node.p(e1[var], e1)
for e1 in all_events(variables, bn, e)
}
return Factor(variables, cpt)
|
[
"def",
"make_factor",
"(",
"var",
",",
"e",
",",
"bn",
")",
":",
"node",
"=",
"bn",
".",
"variable_node",
"(",
"var",
")",
"variables",
"=",
"[",
"X",
"for",
"X",
"in",
"[",
"var",
"]",
"+",
"node",
".",
"parents",
"if",
"X",
"not",
"in",
"e",
"]",
"cpt",
"=",
"{",
"event_values",
"(",
"e1",
",",
"variables",
")",
":",
"node",
".",
"p",
"(",
"e1",
"[",
"var",
"]",
",",
"e1",
")",
"for",
"e1",
"in",
"all_events",
"(",
"variables",
",",
"bn",
",",
"e",
")",
"}",
"return",
"Factor",
"(",
"variables",
",",
"cpt",
")"
] |
[
326,
0
] |
[
336,
33
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
update
|
(rid, tabela, **kwargs)
|
Função que recebe como parâmetro obrigatório o nome da tabela e o id da linha que deseja editar,
além dos valores de nome da coluna e dados a serem atualizados
|
Função que recebe como parâmetro obrigatório o nome da tabela e o id da linha que deseja editar,
além dos valores de nome da coluna e dados a serem atualizados
|
def update(rid, tabela, **kwargs):
""" Função que recebe como parâmetro obrigatório o nome da tabela e o id da linha que deseja editar,
além dos valores de nome da coluna e dados a serem atualizados """
banco = Banco()
banco.connect()
for coluna, valor in kwargs.items():
banco.execute(f'UPDATE {tabela} SET {coluna}="{valor}" WHERE id={rid}')
banco.persist()
banco.disconnect()
|
[
"def",
"update",
"(",
"rid",
",",
"tabela",
",",
"*",
"*",
"kwargs",
")",
":",
"banco",
"=",
"Banco",
"(",
")",
"banco",
".",
"connect",
"(",
")",
"for",
"coluna",
",",
"valor",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"banco",
".",
"execute",
"(",
"f'UPDATE {tabela} SET {coluna}=\"{valor}\" WHERE id={rid}'",
")",
"banco",
".",
"persist",
"(",
")",
"banco",
".",
"disconnect",
"(",
")"
] |
[
160,
0
] |
[
169,
22
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
register_documents
|
(**kwargs)
|
Registra documentos na base de dados do OPAC a partir de
informações vindas da API do `Kernel`. Armazena como órfãos nas variáveis
do Airflow os documentos que não puderam ser salvos.
|
Registra documentos na base de dados do OPAC a partir de
informações vindas da API do `Kernel`. Armazena como órfãos nas variáveis
do Airflow os documentos que não puderam ser salvos.
|
def register_documents(**kwargs):
"""Registra documentos na base de dados do OPAC a partir de
informações vindas da API do `Kernel`. Armazena como órfãos nas variáveis
do Airflow os documentos que não puderam ser salvos."""
mongo_connect()
tasks = kwargs["ti"].xcom_pull(key="tasks", task_ids="read_changes_task")
def _get_relation_data(document_id: str) -> Tuple[str, Dict]:
"""Recupera informações sobre o relacionamento entre o
DocumentsBundle e o Document.
Retorna uma tupla contendo o identificador da issue onde o
documento está relacionado e o item do relacionamento.
>> _get_relation_data("67TH7T7CyPPmgtVrGXhWXVs")
('0034-8910-2019-v53', {'id': '67TH7T7CyPPmgtVrGXhWXVs', 'order': '01'})
:param document_id: Identificador único de um documento
"""
for issue_id, items in known_documents.items():
for item in items:
if document_id == item["id"]:
return (issue_id, item)
return ()
def _get_known_documents(**kwargs) -> Dict[str, List[str]]:
"""Recupera a lista de todos os documentos que estão relacionados com
um `DocumentsBundle`.
Levando em consideração que a DAG que detecta mudanças na API do Kernel
roda de forma assíncrona em relação a DAG de espelhamento/sincronização.
É possível que algumas situações especiais ocorram onde em uma rodada
**anterior** o **evento de registro** de um `Document` foi capturado mas a
atualização de seu `DocumentsBundle` não ocorreu (elas ocorrem em transações
distintas e possuem timestamps também distintos). O documento será
registrado como **órfão** e sua `task` não será processada na próxima
execução.
Na próxima execução a task `register_issue_task` entenderá que o
`bundle` é órfão e não conhecerá os seus documentos (known_documents)
e consequentemente o documento continuará órfão.
Uma solução para este problema é atualizar a lista de documentos
conhecidos a partir da lista de eventos de `get` de `bundles`.
"""
known_documents = kwargs["ti"].xcom_pull(
key="i_documents", task_ids="register_issues_task"
)
issues_recently_updated = [
get_id(task["id"]) for task in filter_changes(tasks, "bundles", "get")
if known_documents.get(get_id(task["id"])) is None
]
for issue_id in issues_recently_updated:
known_documents.setdefault(issue_id, [])
known_documents[issue_id] = list(
itertools.chain(
known_documents[issue_id], fetch_bundles(issue_id).get("items", [])
)
)
return known_documents
known_documents = _get_known_documents(**kwargs)
# TODO: Em caso de um update no document é preciso atualizar o registro
# Precisamos de uma nova task?
documents_to_get = itertools.chain(
Variable.get("orphan_documents", default_var=[], deserialize_json=True),
(get_id(task["id"]) for task in filter_changes(tasks, "documents", "get")),
)
orphans = try_register_documents(
documents_to_get, _get_relation_data, fetch_documents_front, ArticleFactory
)
Variable.set("orphan_documents", orphans, serialize_json=True)
|
[
"def",
"register_documents",
"(",
"*",
"*",
"kwargs",
")",
":",
"mongo_connect",
"(",
")",
"tasks",
"=",
"kwargs",
"[",
"\"ti\"",
"]",
".",
"xcom_pull",
"(",
"key",
"=",
"\"tasks\"",
",",
"task_ids",
"=",
"\"read_changes_task\"",
")",
"def",
"_get_relation_data",
"(",
"document_id",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"Dict",
"]",
":",
"\"\"\"Recupera informações sobre o relacionamento entre o \n DocumentsBundle e o Document.\n\n Retorna uma tupla contendo o identificador da issue onde o\n documento está relacionado e o item do relacionamento.\n\n >> _get_relation_data(\"67TH7T7CyPPmgtVrGXhWXVs\")\n ('0034-8910-2019-v53', {'id': '67TH7T7CyPPmgtVrGXhWXVs', 'order': '01'})\n\n :param document_id: Identificador único de um documento\n \"\"\"",
"for",
"issue_id",
",",
"items",
"in",
"known_documents",
".",
"items",
"(",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"document_id",
"==",
"item",
"[",
"\"id\"",
"]",
":",
"return",
"(",
"issue_id",
",",
"item",
")",
"return",
"(",
")",
"def",
"_get_known_documents",
"(",
"*",
"*",
"kwargs",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"\"\"\"Recupera a lista de todos os documentos que estão relacionados com\n um `DocumentsBundle`.\n\n Levando em consideração que a DAG que detecta mudanças na API do Kernel\n roda de forma assíncrona em relação a DAG de espelhamento/sincronização.\n\n É possível que algumas situações especiais ocorram onde em uma rodada\n **anterior** o **evento de registro** de um `Document` foi capturado mas a \n atualização de seu `DocumentsBundle` não ocorreu (elas ocorrem em transações\n distintas e possuem timestamps também distintos). O documento será\n registrado como **órfão** e sua `task` não será processada na próxima\n execução.\n\n Na próxima execução a task `register_issue_task` entenderá que o\n `bundle` é órfão e não conhecerá os seus documentos (known_documents)\n e consequentemente o documento continuará órfão.\n\n Uma solução para este problema é atualizar a lista de documentos\n conhecidos a partir da lista de eventos de `get` de `bundles`.\n \"\"\"",
"known_documents",
"=",
"kwargs",
"[",
"\"ti\"",
"]",
".",
"xcom_pull",
"(",
"key",
"=",
"\"i_documents\"",
",",
"task_ids",
"=",
"\"register_issues_task\"",
")",
"issues_recently_updated",
"=",
"[",
"get_id",
"(",
"task",
"[",
"\"id\"",
"]",
")",
"for",
"task",
"in",
"filter_changes",
"(",
"tasks",
",",
"\"bundles\"",
",",
"\"get\"",
")",
"if",
"known_documents",
".",
"get",
"(",
"get_id",
"(",
"task",
"[",
"\"id\"",
"]",
")",
")",
"is",
"None",
"]",
"for",
"issue_id",
"in",
"issues_recently_updated",
":",
"known_documents",
".",
"setdefault",
"(",
"issue_id",
",",
"[",
"]",
")",
"known_documents",
"[",
"issue_id",
"]",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"known_documents",
"[",
"issue_id",
"]",
",",
"fetch_bundles",
"(",
"issue_id",
")",
".",
"get",
"(",
"\"items\"",
",",
"[",
"]",
")",
")",
")",
"return",
"known_documents",
"known_documents",
"=",
"_get_known_documents",
"(",
"*",
"*",
"kwargs",
")",
"# TODO: Em caso de um update no document é preciso atualizar o registro",
"# Precisamos de uma nova task?",
"documents_to_get",
"=",
"itertools",
".",
"chain",
"(",
"Variable",
".",
"get",
"(",
"\"orphan_documents\"",
",",
"default_var",
"=",
"[",
"]",
",",
"deserialize_json",
"=",
"True",
")",
",",
"(",
"get_id",
"(",
"task",
"[",
"\"id\"",
"]",
")",
"for",
"task",
"in",
"filter_changes",
"(",
"tasks",
",",
"\"documents\"",
",",
"\"get\"",
")",
")",
",",
")",
"orphans",
"=",
"try_register_documents",
"(",
"documents_to_get",
",",
"_get_relation_data",
",",
"fetch_documents_front",
",",
"ArticleFactory",
")",
"Variable",
".",
"set",
"(",
"\"orphan_documents\"",
",",
"orphans",
",",
"serialize_json",
"=",
"True",
")"
] |
[
534,
0
] |
[
617,
66
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
reschedule
|
()
|
Zere os segundos de now e some mais 1 minuto.
|
Zere os segundos de now e some mais 1 minuto.
|
def reschedule():
"""Zere os segundos de now e some mais 1 minuto."""
new_target = datetime.now().replace(second=0, microsecond=0)
new_target += timedelta(minutes=1)
print(new_target)
scheduler.enterabs(new_target.timestamp(),
priority=100,
action=google_request)
|
[
"def",
"reschedule",
"(",
")",
":",
"new_target",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"replace",
"(",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"new_target",
"+=",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"print",
"(",
"new_target",
")",
"scheduler",
".",
"enterabs",
"(",
"new_target",
".",
"timestamp",
"(",
")",
",",
"priority",
"=",
"100",
",",
"action",
"=",
"google_request",
")"
] |
[
8,
0
] |
[
16,
45
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
TestValidateDocs.test_incorrect_argument
|
(self)
|
Test a função quando os argumentos estão incorretos
|
Test a função quando os argumentos estão incorretos
|
def test_incorrect_argument(self):
"""Test a função quando os argumentos estão incorretos"""
with self.assertRaises(TypeError):
docbr.validate_docs([('cpf', docbr.CPF().generate())])
|
[
"def",
"test_incorrect_argument",
"(",
"self",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"TypeError",
")",
":",
"docbr",
".",
"validate_docs",
"(",
"[",
"(",
"'cpf'",
",",
"docbr",
".",
"CPF",
"(",
")",
".",
"generate",
"(",
")",
")",
"]",
")"
] |
[
43,
4
] |
[
46,
66
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
global_average_pooling
|
(x)
|
return K.mean(x, axis = (2, 3))
|
Aplica o GBP nos ouputs do max pooling da rede.
|
Aplica o GBP nos ouputs do max pooling da rede.
|
def global_average_pooling(x):
"""Aplica o GBP nos ouputs do max pooling da rede."""
return K.mean(x, axis = (2, 3))
|
[
"def",
"global_average_pooling",
"(",
"x",
")",
":",
"return",
"K",
".",
"mean",
"(",
"x",
",",
"axis",
"=",
"(",
"2",
",",
"3",
")",
")"
] |
[
9,
0
] |
[
11,
35
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
JournalFactory
|
(data)
|
return journal
|
Produz instância de `models.Journal` a partir dos dados retornados do
endpoint `/journals/:journal_id` do Kernel.
|
Produz instância de `models.Journal` a partir dos dados retornados do
endpoint `/journals/:journal_id` do Kernel.
|
def JournalFactory(data):
"""Produz instância de `models.Journal` a partir dos dados retornados do
endpoint `/journals/:journal_id` do Kernel.
"""
metadata = data["metadata"]
journal = models.Journal()
journal._id = journal.jid = data.get("id")
journal.title = metadata.get("title", "")
journal.title_iso = metadata.get("title_iso", "")
journal.short_title = metadata.get("short_title", "")
journal.acronym = metadata.get("acronym", "")
journal.scielo_issn = metadata.get("scielo_issn", "")
journal.print_issn = metadata.get("print_issn", "")
journal.eletronic_issn = metadata.get("electronic_issn", "")
# Subject Categories
journal.subject_categories = metadata.get("subject_categories", [])
# Métricas
journal.metrics = models.JounalMetrics(**metadata.get("metrics", {}))
# Issue count
journal.issue_count = len(data.get("items", []))
# Mission
journal.mission = [
models.Mission(**{"language": m["language"], "description": m["value"]})
for m in metadata.get("mission", [])
]
# Study Area
journal.study_areas = metadata.get("subject_areas", [])
# Sponsors
sponsors = metadata.get("sponsors", [])
journal.sponsors = [s["name"] for s in sponsors if sponsors]
# TODO: Verificar se esse e-mail é o que deve ser colocado no editor.
# Editor mail
if metadata.get("contact", ""):
contact = metadata.get("contact")
journal.editor_email = EMAIL_SPLIT_REGEX.split(contact.get("email", ""))[
0
].strip()
journal.online_submission_url = metadata.get("online_submission_url", "")
journal.logo_url = metadata.get("logo_url", "")
journal.current_status = metadata.get("status", {}).get("status")
journal.created = data.get("created", "")
journal.updated = data.get("updated", "")
return journal
|
[
"def",
"JournalFactory",
"(",
"data",
")",
":",
"metadata",
"=",
"data",
"[",
"\"metadata\"",
"]",
"journal",
"=",
"models",
".",
"Journal",
"(",
")",
"journal",
".",
"_id",
"=",
"journal",
".",
"jid",
"=",
"data",
".",
"get",
"(",
"\"id\"",
")",
"journal",
".",
"title",
"=",
"metadata",
".",
"get",
"(",
"\"title\"",
",",
"\"\"",
")",
"journal",
".",
"title_iso",
"=",
"metadata",
".",
"get",
"(",
"\"title_iso\"",
",",
"\"\"",
")",
"journal",
".",
"short_title",
"=",
"metadata",
".",
"get",
"(",
"\"short_title\"",
",",
"\"\"",
")",
"journal",
".",
"acronym",
"=",
"metadata",
".",
"get",
"(",
"\"acronym\"",
",",
"\"\"",
")",
"journal",
".",
"scielo_issn",
"=",
"metadata",
".",
"get",
"(",
"\"scielo_issn\"",
",",
"\"\"",
")",
"journal",
".",
"print_issn",
"=",
"metadata",
".",
"get",
"(",
"\"print_issn\"",
",",
"\"\"",
")",
"journal",
".",
"eletronic_issn",
"=",
"metadata",
".",
"get",
"(",
"\"electronic_issn\"",
",",
"\"\"",
")",
"# Subject Categories",
"journal",
".",
"subject_categories",
"=",
"metadata",
".",
"get",
"(",
"\"subject_categories\"",
",",
"[",
"]",
")",
"# Métricas",
"journal",
".",
"metrics",
"=",
"models",
".",
"JounalMetrics",
"(",
"*",
"*",
"metadata",
".",
"get",
"(",
"\"metrics\"",
",",
"{",
"}",
")",
")",
"# Issue count",
"journal",
".",
"issue_count",
"=",
"len",
"(",
"data",
".",
"get",
"(",
"\"items\"",
",",
"[",
"]",
")",
")",
"# Mission",
"journal",
".",
"mission",
"=",
"[",
"models",
".",
"Mission",
"(",
"*",
"*",
"{",
"\"language\"",
":",
"m",
"[",
"\"language\"",
"]",
",",
"\"description\"",
":",
"m",
"[",
"\"value\"",
"]",
"}",
")",
"for",
"m",
"in",
"metadata",
".",
"get",
"(",
"\"mission\"",
",",
"[",
"]",
")",
"]",
"# Study Area",
"journal",
".",
"study_areas",
"=",
"metadata",
".",
"get",
"(",
"\"subject_areas\"",
",",
"[",
"]",
")",
"# Sponsors",
"sponsors",
"=",
"metadata",
".",
"get",
"(",
"\"sponsors\"",
",",
"[",
"]",
")",
"journal",
".",
"sponsors",
"=",
"[",
"s",
"[",
"\"name\"",
"]",
"for",
"s",
"in",
"sponsors",
"if",
"sponsors",
"]",
"# TODO: Verificar se esse e-mail é o que deve ser colocado no editor.",
"# Editor mail",
"if",
"metadata",
".",
"get",
"(",
"\"contact\"",
",",
"\"\"",
")",
":",
"contact",
"=",
"metadata",
".",
"get",
"(",
"\"contact\"",
")",
"journal",
".",
"editor_email",
"=",
"EMAIL_SPLIT_REGEX",
".",
"split",
"(",
"contact",
".",
"get",
"(",
"\"email\"",
",",
"\"\"",
")",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"journal",
".",
"online_submission_url",
"=",
"metadata",
".",
"get",
"(",
"\"online_submission_url\"",
",",
"\"\"",
")",
"journal",
".",
"logo_url",
"=",
"metadata",
".",
"get",
"(",
"\"logo_url\"",
",",
"\"\"",
")",
"journal",
".",
"current_status",
"=",
"metadata",
".",
"get",
"(",
"\"status\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"status\"",
")",
"journal",
".",
"created",
"=",
"data",
".",
"get",
"(",
"\"created\"",
",",
"\"\"",
")",
"journal",
".",
"updated",
"=",
"data",
".",
"get",
"(",
"\"updated\"",
",",
"\"\"",
")",
"return",
"journal"
] |
[
287,
0
] |
[
340,
18
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Admin.__init__
|
(self, first_name, last_name, login_attempts)
|
Inicializa os atributos da classe User, em seguida inicializa os atributos
da classe Admin
|
Inicializa os atributos da classe User, em seguida inicializa os atributos
da classe Admin
|
def __init__(self, first_name, last_name, login_attempts):
"""Inicializa os atributos da classe User, em seguida inicializa os atributos
da classe Admin"""
super().__init__(first_name, last_name, login_attempts)
self.privileges = "Your're admin and can: add post, delete post and can bane user."
|
[
"def",
"__init__",
"(",
"self",
",",
"first_name",
",",
"last_name",
",",
"login_attempts",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"first_name",
",",
"last_name",
",",
"login_attempts",
")",
"self",
".",
"privileges",
"=",
"\"Your're admin and can: add post, delete post and can bane user.\""
] |
[
51,
4
] |
[
55,
91
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
envia_nf_por_email
|
(nota_fiscal: Any)
|
Envia email assim que uma NF é criada. Padrão observadores aplicado.
Args:
nota_fiscal.py (class Nota_fiscal): Cria Nota fiscal
|
Envia email assim que uma NF é criada. Padrão observadores aplicado.
|
def envia_nf_por_email(nota_fiscal: Any):
"""Envia email assim que uma NF é criada. Padrão observadores aplicado.
Args:
nota_fiscal.py (class Nota_fiscal): Cria Nota fiscal
"""
print(f'\nEnviando nota fiscal {nota_fiscal.cnpj} por e-mail.')
|
[
"def",
"envia_nf_por_email",
"(",
"nota_fiscal",
":",
"Any",
")",
":",
"print",
"(",
"f'\\nEnviando nota fiscal {nota_fiscal.cnpj} por e-mail.'",
")"
] |
[
4,
0
] |
[
10,
67
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
insert
|
(tabela, *args)
|
Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
e os dados para inserção como *args e os insere na tabela escolhida
|
Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
e os dados para inserção como *args e os insere na tabela escolhida
|
def insert(tabela, *args):
""" Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
e os dados para inserção como *args e os insere na tabela escolhida """
banco = Banco()
banco.connect()
banco.execute(f"INSERT INTO {tabela} VALUES (NULL{', ?' * len(args)})", args)
banco.persist()
banco.disconnect()
|
[
"def",
"insert",
"(",
"tabela",
",",
"*",
"args",
")",
":",
"banco",
"=",
"Banco",
"(",
")",
"banco",
".",
"connect",
"(",
")",
"banco",
".",
"execute",
"(",
"f\"INSERT INTO {tabela} VALUES (NULL{', ?' * len(args)})\"",
",",
"args",
")",
"banco",
".",
"persist",
"(",
")",
"banco",
".",
"disconnect",
"(",
")"
] |
[
149,
0
] |
[
157,
22
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
adicionarPalavra
|
(nome,texto)
|
[adiciona uma palavra a um arquivo]
Args:
nome ([str]): [nome do arquivo]
texto ([str]): [titulo do input da palavra a ser adicionada]
|
[adiciona uma palavra a um arquivo]
|
def adicionarPalavra(nome,texto):
"""[adiciona uma palavra a um arquivo]
Args:
nome ([str]): [nome do arquivo]
texto ([str]): [titulo do input da palavra a ser adicionada]
"""
try:
a = open(nome,'at')
except:
print('Erro ao adicionar nova palavra.')
else:
while True:
l = lerArquivo(nome)
palavra = str(input(texto)).strip()
if palavra == '':
print('='*42)
print('Erro! Digite uma palavra.',end=' ')
continue
if palavra in l:
print('='*42)
print('Essa Palavra É Repetida. Tente Novamente.',end=' ')
continue
break
try:
a.write(f',{palavra}')
except:
print('Erro ao escrever a palavra')
else:
print('='*42)
print('Nova palavra adicionada com sucesso.')
a.close()
|
[
"def",
"adicionarPalavra",
"(",
"nome",
",",
"texto",
")",
":",
"try",
":",
"a",
"=",
"open",
"(",
"nome",
",",
"'at'",
")",
"except",
":",
"print",
"(",
"'Erro ao adicionar nova palavra.'",
")",
"else",
":",
"while",
"True",
":",
"l",
"=",
"lerArquivo",
"(",
"nome",
")",
"palavra",
"=",
"str",
"(",
"input",
"(",
"texto",
")",
")",
".",
"strip",
"(",
")",
"if",
"palavra",
"==",
"''",
":",
"print",
"(",
"'='",
"*",
"42",
")",
"print",
"(",
"'Erro! Digite uma palavra.'",
",",
"end",
"=",
"' '",
")",
"continue",
"if",
"palavra",
"in",
"l",
":",
"print",
"(",
"'='",
"*",
"42",
")",
"print",
"(",
"'Essa Palavra É Repetida. Tente Novamente.',",
"e",
"nd=",
"'",
" ')",
"",
"continue",
"break",
"try",
":",
"a",
".",
"write",
"(",
"f',{palavra}'",
")",
"except",
":",
"print",
"(",
"'Erro ao escrever a palavra'",
")",
"else",
":",
"print",
"(",
"'='",
"*",
"42",
")",
"print",
"(",
"'Nova palavra adicionada com sucesso.'",
")",
"a",
".",
"close",
"(",
")"
] |
[
96,
0
] |
[
127,
17
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
ScoreBoard.prep_level
|
(self)
|
Transforma o nivel em uma imagem renderizada.
|
Transforma o nivel em uma imagem renderizada.
|
def prep_level(self):
"""Transforma o nivel em uma imagem renderizada."""
self.level_image = self.font.render('Level '+str(self.stats.level), True,
self.text_color,
self.ai_settings.bg_color)
# Posiciona o nivel abaixo da pontuacao
self.level_rect = self.level_image.get_rect()
self.level_rect.right = self.score_rect.right
self.level_rect.top = self.score_rect.bottom + 10
|
[
"def",
"prep_level",
"(",
"self",
")",
":",
"self",
".",
"level_image",
"=",
"self",
".",
"font",
".",
"render",
"(",
"'Level '",
"+",
"str",
"(",
"self",
".",
"stats",
".",
"level",
")",
",",
"True",
",",
"self",
".",
"text_color",
",",
"self",
".",
"ai_settings",
".",
"bg_color",
")",
"# Posiciona o nivel abaixo da pontuacao",
"self",
".",
"level_rect",
"=",
"self",
".",
"level_image",
".",
"get_rect",
"(",
")",
"self",
".",
"level_rect",
".",
"right",
"=",
"self",
".",
"score_rect",
".",
"right",
"self",
".",
"level_rect",
".",
"top",
"=",
"self",
".",
"score_rect",
".",
"bottom",
"+",
"10"
] |
[
55,
4
] |
[
64,
57
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
|
Interface.convert_cidr
|
(cls, cidr)
|
TEMPORARIO, converte notaçcao em cidr para endereço completo.
|
TEMPORARIO, converte notaçcao em cidr para endereço completo.
|
def convert_cidr(cls, cidr):
""" TEMPORARIO, converte notaçcao em cidr para endereço completo."""
cidr = int(cidr)
if cidr == 24:
return '255.255.255.0'
elif cidr == 30:
return '255.255.255.252'
|
[
"def",
"convert_cidr",
"(",
"cls",
",",
"cidr",
")",
":",
"cidr",
"=",
"int",
"(",
"cidr",
")",
"if",
"cidr",
"==",
"24",
":",
"return",
"'255.255.255.0'",
"elif",
"cidr",
"==",
"30",
":",
"return",
"'255.255.255.252'"
] |
[
59,
4
] |
[
68,
36
] | null |
python
|
pt
|
['pt', 'pt', 'pt']
|
True
| true | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.