identifier
stringlengths 0
89
| parameters
stringlengths 0
399
| return_statement
stringlengths 0
982
⌀ | docstring
stringlengths 10
3.04k
| docstring_summary
stringlengths 0
3.04k
| function
stringlengths 13
25.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | argument_list
null | language
stringclasses 3
values | docstring_language
stringclasses 4
values | docstring_language_predictions
stringclasses 4
values | is_langid_reliable
stringclasses 2
values | is_langid_extra_reliable
bool 1
class | type
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
p_instrif3 | (t) | instrif : IF condiciones THEN instrlistabloque instrelseif ELSE instrlistabloque END IF PTCOMA | instrif : IF condiciones THEN instrlistabloque instrelseif ELSE instrlistabloque END IF PTCOMA | def p_instrif3(t):
'instrif : IF condiciones THEN instrlistabloque instrelseif ELSE instrlistabloque END IF PTCOMA'
t[0] = getinstrif3(t) | [
"def",
"p_instrif3",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getinstrif3",
"(",
"t",
")"
] | [
820,
0
] | [
822,
25
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Counter.calc_minutes | (self) | return int(self.calc_seconds() // MINUTE) | Calcula los minutos transcurridos | Calcula los minutos transcurridos | def calc_minutes(self):
"""Calcula los minutos transcurridos"""
return int(self.calc_seconds() // MINUTE) | [
"def",
"calc_minutes",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"calc_seconds",
"(",
")",
"//",
"MINUTE",
")"
] | [
29,
4
] | [
32,
49
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
PlacesExtractor.boot_writer | (self) | Función que arrancaba y configuraba el writer de este extractor leyendo de la configuración del soporte de
salida configurada para la ejecución.
| Función que arrancaba y configuraba el writer de este extractor leyendo de la configuración del soporte de
salida configurada para la ejecución.
| def boot_writer(self):
"""Función que arrancaba y configuraba el writer de este extractor leyendo de la configuración del soporte de
salida configurada para la ejecución.
"""
if self._output_config:
self._boot_writer()
else:
self._writer = PrinterWriter() | [
"def",
"boot_writer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_output_config",
":",
"self",
".",
"_boot_writer",
"(",
")",
"else",
":",
"self",
".",
"_writer",
"=",
"PrinterWriter",
"(",
")"
] | [
231,
4
] | [
238,
42
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Car.increment_odometer | (self, miles) | Agregar la cantidad dada a la lectura del odómetro | Agregar la cantidad dada a la lectura del odómetro | def increment_odometer(self, miles):
"""Agregar la cantidad dada a la lectura del odómetro"""
self.odometer_reading += miles | [
"def",
"increment_odometer",
"(",
"self",
",",
"miles",
")",
":",
"self",
".",
"odometer_reading",
"+=",
"miles"
] | [
34,
4
] | [
36,
38
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_instrucciones_instruccion | (t) | instrucciones : instruccion | instrucciones : instruccion | def p_instrucciones_instruccion(t):
'instrucciones : instruccion '
t[0] = [t[1]] | [
"def",
"p_instrucciones_instruccion",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]"
] | [
282,
0
] | [
284,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
FingerprintKeyerUnitTestCase.test_fingerprint_keyer_without_sorting | (self) | Testea la creación de una key fingerprint sin ordenar los tokens. | Testea la creación de una key fingerprint sin ordenar los tokens. | def test_fingerprint_keyer_without_sorting(self):
"""Testea la creación de una key fingerprint sin ordenar los tokens."""
input_output_strings = [
("bbb\taaa", "bbb aaa"),
("aaa\tbbb", "aaa bbb"),
]
for inp_string, out_exp in input_output_strings:
self.assertEqual(fingerprint_keyer(inp_string, False, False),
out_exp) | [
"def",
"test_fingerprint_keyer_without_sorting",
"(",
"self",
")",
":",
"input_output_strings",
"=",
"[",
"(",
"\"bbb\\taaa\"",
",",
"\"bbb aaa\"",
")",
",",
"(",
"\"aaa\\tbbb\"",
",",
"\"aaa bbb\"",
")",
",",
"]",
"for",
"inp_string",
",",
"out_exp",
"in",
"input_output_strings",
":",
"self",
".",
"assertEqual",
"(",
"fingerprint_keyer",
"(",
"inp_string",
",",
"False",
",",
"False",
")",
",",
"out_exp",
")"
] | [
62,
4
] | [
70,
37
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
puntos_poligono_frecuencia | (bins_val, bins) | return puntos_x, puntos_y | Calcula los puntos X e Y para crear el polígono de frecuencias.
Esta función supone que los intervalos de clase son de igual amplitud.
Args:
bins_val (list): Altura de los rectángulos del historigrama,
devueltos por la función hist() de matplotlib.
bins (list): En español, rectángulos, son los intervalos de clase
devueltos por la función hist() de matplotlib.
Returns:
float list, float list:
puntos del eje de abscisas, puntos del eje de ordenadas
| Calcula los puntos X e Y para crear el polígono de frecuencias. | def puntos_poligono_frecuencia(bins_val, bins):
"""Calcula los puntos X e Y para crear el polígono de frecuencias.
Esta función supone que los intervalos de clase son de igual amplitud.
Args:
bins_val (list): Altura de los rectángulos del historigrama,
devueltos por la función hist() de matplotlib.
bins (list): En español, rectángulos, son los intervalos de clase
devueltos por la función hist() de matplotlib.
Returns:
float list, float list:
puntos del eje de abscisas, puntos del eje de ordenadas
"""
# Cantidad de rectángulos (número de clases)
n_bins = len(bins)
# Ancho de los intervalos de clase.
ancho_bins = (bins[0] + bins[1]) / 2
# Puntos en X e Y.
puntos_x = [0.0] # Se modificará el 0.0 por la extrapolación
puntos_y = [0.0] # Un 0.0 como primer ordenada
# Todas las alturas de los rectángulos son coordenadas en el
# eje de ordenadas, agregando como coordenada extra el 0 al comienzo
# y final de la lista (para poder crear luego el polígono de frecuencias).
for value in bins_val:
puntos_y.append(value)
puntos_y.append(0.0) # Un 0.0 al final de la lista
# Se almacena la coordenada en X del punto medio de cada rectángulo.
for index in range(n_bins-1):
puntos_x.append((bins[index+1] + bins[index]) / 2)
# El primer y último punto (con ordenada 0) son extrapolados en X tomando
# como referencia la distancia media entre los rectángulos.
puntos_x[0] = bins[0] - ancho_bins
puntos_x.append(bins[-1] + ancho_bins)
# Se convierten los datos a float para que matplotlib pueda utilizarlos.
for point in puntos_x:
point = float(point)
for point in puntos_y:
point = float(point)
return puntos_x, puntos_y | [
"def",
"puntos_poligono_frecuencia",
"(",
"bins_val",
",",
"bins",
")",
":",
"# Cantidad de rectángulos (número de clases)",
"n_bins",
"=",
"len",
"(",
"bins",
")",
"# Ancho de los intervalos de clase.",
"ancho_bins",
"=",
"(",
"bins",
"[",
"0",
"]",
"+",
"bins",
"[",
"1",
"]",
")",
"/",
"2",
"# Puntos en X e Y.",
"puntos_x",
"=",
"[",
"0.0",
"]",
"# Se modificará el 0.0 por la extrapolación",
"puntos_y",
"=",
"[",
"0.0",
"]",
"# Un 0.0 como primer ordenada",
"# Todas las alturas de los rectángulos son coordenadas en el",
"# eje de ordenadas, agregando como coordenada extra el 0 al comienzo",
"# y final de la lista (para poder crear luego el polígono de frecuencias).",
"for",
"value",
"in",
"bins_val",
":",
"puntos_y",
".",
"append",
"(",
"value",
")",
"puntos_y",
".",
"append",
"(",
"0.0",
")",
"# Un 0.0 al final de la lista",
"# Se almacena la coordenada en X del punto medio de cada rectángulo.",
"for",
"index",
"in",
"range",
"(",
"n_bins",
"-",
"1",
")",
":",
"puntos_x",
".",
"append",
"(",
"(",
"bins",
"[",
"index",
"+",
"1",
"]",
"+",
"bins",
"[",
"index",
"]",
")",
"/",
"2",
")",
"# El primer y último punto (con ordenada 0) son extrapolados en X tomando",
"# como referencia la distancia media entre los rectángulos.",
"puntos_x",
"[",
"0",
"]",
"=",
"bins",
"[",
"0",
"]",
"-",
"ancho_bins",
"puntos_x",
".",
"append",
"(",
"bins",
"[",
"-",
"1",
"]",
"+",
"ancho_bins",
")",
"# Se convierten los datos a float para que matplotlib pueda utilizarlos.",
"for",
"point",
"in",
"puntos_x",
":",
"point",
"=",
"float",
"(",
"point",
")",
"for",
"point",
"in",
"puntos_y",
":",
"point",
"=",
"float",
"(",
"point",
")",
"return",
"puntos_x",
",",
"puntos_y"
] | [
163,
0
] | [
210,
29
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Food.__init__ | (self) | Inicializamos los ingredientes | Inicializamos los ingredientes | def __init__(self):
"""Inicializamos los ingredientes"""
self.carne = " - Sin carne"
self.verduras = " - Sin verduras"
self.condimentos = " - Sin condimentos"
self.combo = " - Sin combo" | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"carne",
"=",
"\" - Sin carne\"",
"self",
".",
"verduras",
"=",
"\" - Sin verduras\"",
"self",
".",
"condimentos",
"=",
"\" - Sin condimentos\"",
"self",
".",
"combo",
"=",
"\" - Sin combo\""
] | [
96,
4
] | [
101,
35
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
GameAPI.register_user | (value) | return Users.register_user(value) | registrar nuevo usuario | registrar nuevo usuario | def register_user(value) -> str: # Python 3.8 and earlier
"registrar nuevo usuario"
return Users.register_user(value) | [
"def",
"register_user",
"(",
"value",
")",
"->",
"str",
":",
"# Python 3.8 and earlier\r",
"return",
"Users",
".",
"register_user",
"(",
"value",
")"
] | [
36,
4
] | [
38,
41
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_asignacion_igual_parentesis | (t) | asignacion : ID referencia_id SIGNO_IGUAL PARABRE ins_select_parentesis PARCIERRE PUNTO_COMA | asignacion : ID referencia_id SIGNO_IGUAL PARABRE ins_select_parentesis PARCIERRE PUNTO_COMA | def p_asignacion_igual_parentesis(t):
'''asignacion : ID referencia_id SIGNO_IGUAL PARABRE ins_select_parentesis PARCIERRE PUNTO_COMA'''
t[0] = GenerarBNF()
t[0].produccion = '<ASIGNACION>'
t[0].code += '\n' + '<ASIGNACION>' + ' ::= ' + str(t[1]) + ' ' + t[2].produccion + ' ' + str(t[3]) + ' ' + str(t[4]) + ' ' + t[5].produccion + ' ' + str(t[6]) + ' ' + str(t[7]) + ' ' + t[2].code + ' ' + t[5].code | [
"def",
"p_asignacion_igual_parentesis",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"GenerarBNF",
"(",
")",
"t",
"[",
"0",
"]",
".",
"produccion",
"=",
"'<ASIGNACION>'",
"t",
"[",
"0",
"]",
".",
"code",
"+=",
"'\\n'",
"+",
"'<ASIGNACION>'",
"+",
"' ::= '",
"+",
"str",
"(",
"t",
"[",
"1",
"]",
")",
"+",
"' '",
"+",
"t",
"[",
"2",
"]",
".",
"produccion",
"+",
"' '",
"+",
"str",
"(",
"t",
"[",
"3",
"]",
")",
"+",
"' '",
"+",
"str",
"(",
"t",
"[",
"4",
"]",
")",
"+",
"' '",
"+",
"t",
"[",
"5",
"]",
".",
"produccion",
"+",
"' '",
"+",
"str",
"(",
"t",
"[",
"6",
"]",
")",
"+",
"' '",
"+",
"str",
"(",
"t",
"[",
"7",
"]",
")",
"+",
"' '",
"+",
"t",
"[",
"2",
"]",
".",
"code",
"+",
"' '",
"+",
"t",
"[",
"5",
"]",
".",
"code"
] | [
1921,
0
] | [
1925,
216
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_lista_instrucciones_funcion_math | (t) | lista_funciones_math_esenciales : aritmetica
| lista_id
| POR | lista_funciones_math_esenciales : aritmetica
| lista_id
| POR | def p_lista_instrucciones_funcion_math(t):
'''lista_funciones_math_esenciales : aritmetica
| lista_id
| POR''' | [
"def",
"p_lista_instrucciones_funcion_math",
"(",
"t",
")",
":"
] | [
863,
0
] | [
866,
48
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
introducir_alumno | () | return lista | funcion que permite introducir el nombre del alumno y
procesa el dato introducido para que pueda ser utilizado por el resto de funciones | funcion que permite introducir el nombre del alumno y
procesa el dato introducido para que pueda ser utilizado por el resto de funciones | def introducir_alumno():
"""funcion que permite introducir el nombre del alumno y
procesa el dato introducido para que pueda ser utilizado por el resto de funciones"""
lista = []
alumno = ""
print ("Si quiere finalizar de introducir nombres introduzca la secuencia: ?x?")
while alumno != "?x?":
alumno = input("Introduzca el nombre de un alumno ")
alumno_sin_esp = alumno.strip() #elimina los espacios al inicio y al final de la cadena
alumno_format = alumno_sin_esp.title() #este metodo hace que todos los nombres estén escritos de la mmisma forma (mayúscula al inicio de cada palabra y minusculas el resto) para que puedan ser comparados
if comprobar(alumno_format):
lista.append(alumno_format)
else:
continue
return lista | [
"def",
"introducir_alumno",
"(",
")",
":",
"lista",
"=",
"[",
"]",
"alumno",
"=",
"\"\"",
"print",
"(",
"\"Si quiere finalizar de introducir nombres introduzca la secuencia: ?x?\"",
")",
"while",
"alumno",
"!=",
"\"?x?\"",
":",
"alumno",
"=",
"input",
"(",
"\"Introduzca el nombre de un alumno \"",
")",
"alumno_sin_esp",
"=",
"alumno",
".",
"strip",
"(",
")",
"#elimina los espacios al inicio y al final de la cadena",
"alumno_format",
"=",
"alumno_sin_esp",
".",
"title",
"(",
")",
"#este metodo hace que todos los nombres estén escritos de la mmisma forma (mayúscula al inicio de cada palabra y minusculas el resto) para que puedan ser comparados",
"if",
"comprobar",
"(",
"alumno_format",
")",
":",
"lista",
".",
"append",
"(",
"alumno_format",
")",
"else",
":",
"continue",
"return",
"lista"
] | [
34,
0
] | [
48,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
convolucion | (Ioriginal,Kernel) | Método encargado de realizar una convolución a una imagen
Entrada:
Ioriginal - imagen original en forma de matríz
kernel - kernel para barrer la imagen
Salida:
res - imagen resultante | Método encargado de realizar una convolución a una imagen
Entrada:
Ioriginal - imagen original en forma de matríz
kernel - kernel para barrer la imagen
Salida:
res - imagen resultante | def convolucion(Ioriginal,Kernel):
'''Método encargado de realizar una convolución a una imagen
Entrada:
Ioriginal - imagen original en forma de matríz
kernel - kernel para barrer la imagen
Salida:
res - imagen resultante''' | [
"def",
"convolucion",
"(",
"Ioriginal",
",",
"Kernel",
")",
":"
] | [
4,
0
] | [
10,
34
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
AbstractGMapsExtractor.get_info_obj | (self, xpath_query, external_driver=None) | return element | Busca en el driver, de la instancia o el pasado por argumento, el elemento del navegador que cumpla la query.
Parameters
----------
xpath_query : str
xpath query que se usará para buscar el elemento en el driver
external_driver : webdriver.Chrome
instancia en el que se ejecutará la query. En caso de ser None se usará el que tenga la instancia en su
atributo self._driver
Returns
-------
element : WebElement
instancia de WebElement en caso de que haya alguno encontrado con la query o None
| Busca en el driver, de la instancia o el pasado por argumento, el elemento del navegador que cumpla la query. | def get_info_obj(self, xpath_query, external_driver=None):
"""Busca en el driver, de la instancia o el pasado por argumento, el elemento del navegador que cumpla la query.
Parameters
----------
xpath_query : str
xpath query que se usará para buscar el elemento en el driver
external_driver : webdriver.Chrome
instancia en el que se ejecutará la query. En caso de ser None se usará el que tenga la instancia en su
atributo self._driver
Returns
-------
element : WebElement
instancia de WebElement en caso de que haya alguno encontrado con la query o None
"""
element = None
driver = external_driver if external_driver else self._driver
try:
element = driver.find_element_by_xpath(xpath_query)
except NoSuchElementException:
element = None
return element | [
"def",
"get_info_obj",
"(",
"self",
",",
"xpath_query",
",",
"external_driver",
"=",
"None",
")",
":",
"element",
"=",
"None",
"driver",
"=",
"external_driver",
"if",
"external_driver",
"else",
"self",
".",
"_driver",
"try",
":",
"element",
"=",
"driver",
".",
"find_element_by_xpath",
"(",
"xpath_query",
")",
"except",
"NoSuchElementException",
":",
"element",
"=",
"None",
"return",
"element"
] | [
246,
4
] | [
269,
22
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
AssertionStrategy.add | (self, nano_pub, assertion, tag_config, annotation: Annotation) | realiza el 'assertion' en la nanopublication pasada | realiza el 'assertion' en la nanopublication pasada | def add(self, nano_pub, assertion, tag_config, annotation: Annotation):
"""realiza el 'assertion' en la nanopublication pasada"""
raise NotImplementedError | [
"def",
"add",
"(",
"self",
",",
"nano_pub",
",",
"assertion",
",",
"tag_config",
",",
"annotation",
":",
"Annotation",
")",
":",
"raise",
"NotImplementedError"
] | [
10,
4
] | [
12,
33
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_inst_generales1 | (t) | instrucciones_generales : instrucciones_generales temporales | instrucciones_generales : instrucciones_generales temporales | def p_inst_generales1(t):
'''instrucciones_generales : instrucciones_generales temporales'''
arr1 = []
arr1.append('encabezado')
arr1.append(t[2])
t[1].append(arr1)
t[0] = t[1] | [
"def",
"p_inst_generales1",
"(",
"t",
")",
":",
"arr1",
"=",
"[",
"]",
"arr1",
".",
"append",
"(",
"'encabezado'",
")",
"arr1",
".",
"append",
"(",
"t",
"[",
"2",
"]",
")",
"t",
"[",
"1",
"]",
".",
"append",
"(",
"arr1",
")",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
2275,
0
] | [
2282,
15
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
csv_empresas | (request) | return response | CSV con las empresas de hosting | CSV con las empresas de hosting | def csv_empresas(request):
""" CSV con las empresas de hosting """
fields = ['id', 'nombre']
queryset = Empresa.objects.all()
response = queryset_as_csv_view(request=request, filename='empresas.csv', queryset=queryset, fields=fields)
return response | [
"def",
"csv_empresas",
"(",
"request",
")",
":",
"fields",
"=",
"[",
"'id'",
",",
"'nombre'",
"]",
"queryset",
"=",
"Empresa",
".",
"objects",
".",
"all",
"(",
")",
"response",
"=",
"queryset_as_csv_view",
"(",
"request",
"=",
"request",
",",
"filename",
"=",
"'empresas.csv'",
",",
"queryset",
"=",
"queryset",
",",
"fields",
"=",
"fields",
")",
"return",
"response"
] | [
4,
0
] | [
10,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_executecf | (t) | execute : EXECUTE funcionesLlamada | execute : EXECUTE funcionesLlamada | def p_executecf(t):
'execute : EXECUTE funcionesLlamada'
#text = ''
text = t[2]['c3d']
t[0] = {'text': text, 'c3d': ''} | [
"def",
"p_executecf",
"(",
"t",
")",
":",
"#text = ''",
"text",
"=",
"t",
"[",
"2",
"]",
"[",
"'c3d'",
"]",
"t",
"[",
"0",
"]",
"=",
"{",
"'text'",
":",
"text",
",",
"'c3d'",
":",
"''",
"}"
] | [
2701,
0
] | [
2705,
36
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
pitolat | (rad) | Util solamente por ahora para traducir resultados de AAS a lat y long | Util solamente por ahora para traducir resultados de AAS a lat y long | def pitolat(rad):
"""Util solamente por ahora para traducir resultados de AAS a lat y long"""
sgn = np.sign(rad)
if sgn == 1:
if rad > np.pi/2:
return np.pi/2 - rad%(np.pi/2)
else:
return rad
else:
if rad < -np.pi/2:
return -np.pi/2 + rad%(np.pi/2)
else:
return rad | [
"def",
"pitolat",
"(",
"rad",
")",
":",
"sgn",
"=",
"np",
".",
"sign",
"(",
"rad",
")",
"if",
"sgn",
"==",
"1",
":",
"if",
"rad",
">",
"np",
".",
"pi",
"/",
"2",
":",
"return",
"np",
".",
"pi",
"/",
"2",
"-",
"rad",
"%",
"(",
"np",
".",
"pi",
"/",
"2",
")",
"else",
":",
"return",
"rad",
"else",
":",
"if",
"rad",
"<",
"-",
"np",
".",
"pi",
"/",
"2",
":",
"return",
"-",
"np",
".",
"pi",
"/",
"2",
"+",
"rad",
"%",
"(",
"np",
".",
"pi",
"/",
"2",
")",
"else",
":",
"return",
"rad"
] | [
66,
0
] | [
78,
22
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
TrackedObjects.frame_objects | (self, frame: int) | return objects_in_frame | Crea una lista de los objetos que hay en un frame.
:param frame: número del frame del que se quiere obtener los objetos registrados.
:return: lista de pares de identificador del objeto y objeto.
| Crea una lista de los objetos que hay en un frame. | def frame_objects(self, frame: int) -> List[TrackedObjectDetection]:
"""Crea una lista de los objetos que hay en un frame.
:param frame: número del frame del que se quiere obtener los objetos registrados.
:return: lista de pares de identificador del objeto y objeto.
"""
objects_in_frame: List[TrackedObjectDetection] = list()
for object_tracked in self._tracked_objects:
detection = object_tracked.find_in_frame(frame)
if detection is not None:
objects_in_frame.append(detection)
return objects_in_frame | [
"def",
"frame_objects",
"(",
"self",
",",
"frame",
":",
"int",
")",
"->",
"List",
"[",
"TrackedObjectDetection",
"]",
":",
"objects_in_frame",
":",
"List",
"[",
"TrackedObjectDetection",
"]",
"=",
"list",
"(",
")",
"for",
"object_tracked",
"in",
"self",
".",
"_tracked_objects",
":",
"detection",
"=",
"object_tracked",
".",
"find_in_frame",
"(",
"frame",
")",
"if",
"detection",
"is",
"not",
"None",
":",
"objects_in_frame",
".",
"append",
"(",
"detection",
")",
"return",
"objects_in_frame"
] | [
251,
4
] | [
262,
31
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
cuad_trapecio_datos | (x0, x1, f=None, y0=None, y1=None) | return aprox | Implementación de la regla del trapecio
Parameters
----------
x0: float
Límite inferior del intervalo
x1: float
Límite superior del intervalo
f: function (1 parameter)
La función a integrar
y0: float
El valor de y en el punto medio.
y1: float
El valor de y en el punto medio.
Returns
-------
aprox: Aproximación de la integral por la regla del punto medio
Notes
-----
Este código es parte del curso "Computación", Famaf
Uso:
cuad_trapecio(x0, x1, f=f)
cuad_trapecio(x0, x1, y0=f(x0), y1=f(x1))
| Implementación de la regla del trapecio
Parameters
----------
x0: float
Límite inferior del intervalo
x1: float
Límite superior del intervalo
f: function (1 parameter)
La función a integrar
y0: float
El valor de y en el punto medio.
y1: float
El valor de y en el punto medio. | def cuad_trapecio_datos(x0, x1, f=None, y0=None, y1=None):
"""Implementación de la regla del trapecio
Parameters
----------
x0: float
Límite inferior del intervalo
x1: float
Límite superior del intervalo
f: function (1 parameter)
La función a integrar
y0: float
El valor de y en el punto medio.
y1: float
El valor de y en el punto medio.
Returns
-------
aprox: Aproximación de la integral por la regla del punto medio
Notes
-----
Este código es parte del curso "Computación", Famaf
Uso:
cuad_trapecio(x0, x1, f=f)
cuad_trapecio(x0, x1, y0=f(x0), y1=f(x1))
"""
if x0 > x1:
raise ValueError("Oops! Debe ser a<b")
if (f is None) and (y0 is not None) and (y1 is not None):
aprox = (x1-x0)*(y0+y1)/2
elif (f is not None) and (y0 is None):
try:
y0 = f(x0)
y1 = f(x1)
except:
print(('Error: no fue posible calcular la función'
' Si desea ingresar un dato use y0='))
aprox = (x1-x0)*(y0+y1)/2
else:
raise ValueError("Debe ingresar la función o los datos!")
return aprox | [
"def",
"cuad_trapecio_datos",
"(",
"x0",
",",
"x1",
",",
"f",
"=",
"None",
",",
"y0",
"=",
"None",
",",
"y1",
"=",
"None",
")",
":",
"if",
"x0",
">",
"x1",
":",
"raise",
"ValueError",
"(",
"\"Oops! Debe ser a<b\"",
")",
"if",
"(",
"f",
"is",
"None",
")",
"and",
"(",
"y0",
"is",
"not",
"None",
")",
"and",
"(",
"y1",
"is",
"not",
"None",
")",
":",
"aprox",
"=",
"(",
"x1",
"-",
"x0",
")",
"*",
"(",
"y0",
"+",
"y1",
")",
"/",
"2",
"elif",
"(",
"f",
"is",
"not",
"None",
")",
"and",
"(",
"y0",
"is",
"None",
")",
":",
"try",
":",
"y0",
"=",
"f",
"(",
"x0",
")",
"y1",
"=",
"f",
"(",
"x1",
")",
"except",
":",
"print",
"(",
"(",
"'Error: no fue posible calcular la función'",
"' Si desea ingresar un dato use y0='",
")",
")",
"aprox",
"=",
"(",
"x1",
"-",
"x0",
")",
"*",
"(",
"y0",
"+",
"y1",
")",
"/",
"2",
"else",
":",
"raise",
"ValueError",
"(",
"\"Debe ingresar la función o los datos!\")",
" ",
"return",
"aprox"
] | [
161,
0
] | [
206,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
datfile | () | devuelve datos xyz random para prueba de grafico | devuelve datos xyz random para prueba de grafico | def datfile():
"""devuelve datos xyz random para prueba de grafico"""
def fila():
"""devuelve una fila con valores aleatoreos"""
import random
#datFile= [ ]
for i in range(3):
n = random.randint(0, 500),
datFile=[n] #aumenta la lista
print(datFile)
cont= 500
for c in range(cont):
fila() | [
"def",
"datfile",
"(",
")",
":",
"def",
"fila",
"(",
")",
":",
"\"\"\"devuelve una fila con valores aleatoreos\"\"\"",
"import",
"random",
"#datFile= [ ]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"n",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"500",
")",
",",
"datFile",
"=",
"[",
"n",
"]",
"#aumenta la lista",
"print",
"(",
"datFile",
")",
"cont",
"=",
"500",
"for",
"c",
"in",
"range",
"(",
"cont",
")",
":",
"fila",
"(",
")"
] | [
0,
0
] | [
13,
14
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ServiceCallback.insert_service | (
networkid: int,
service_name: str,
priority: int = 0,
*, cursor
) | Añade un servicio | Añade un servicio | async def insert_service(
networkid: int,
service_name: str,
priority: int = 0,
*, cursor
) -> None:
"""Añade un servicio"""
await cursor.execute(
"INSERT INTO services(id_network, service, priority) VALUES (%s, %s, %s)",
(networkid, service_name, priority)
) | [
"async",
"def",
"insert_service",
"(",
"networkid",
":",
"int",
",",
"service_name",
":",
"str",
",",
"priority",
":",
"int",
"=",
"0",
",",
"*",
",",
"cursor",
")",
"->",
"None",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"INSERT INTO services(id_network, service, priority) VALUES (%s, %s, %s)\"",
",",
"(",
"networkid",
",",
"service_name",
",",
"priority",
")",
")"
] | [
670,
4
] | [
683,
9
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones17 | (p) | funciones : ASIND PABRE expresion PCIERRA | funciones : ASIND PABRE expresion PCIERRA | def p_funciones17(p):
'funciones : ASIND PABRE expresion PCIERRA' | [
"def",
"p_funciones17",
"(",
"p",
")",
":"
] | [
349,
0
] | [
350,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
champions_in_csv | () | return datos | Trae los campeones del archivo y los devuelve en formato de lista | Trae los campeones del archivo y los devuelve en formato de lista | def champions_in_csv():
"""Trae los campeones del archivo y los devuelve en formato de lista"""
datos = []
with open(lol_path()) as file_lol:
champions = csv.reader(file_lol, delimiter=';')
next(champions)
for elem in champions:
datos.append(elem)
return datos | [
"def",
"champions_in_csv",
"(",
")",
":",
"datos",
"=",
"[",
"]",
"with",
"open",
"(",
"lol_path",
"(",
")",
")",
"as",
"file_lol",
":",
"champions",
"=",
"csv",
".",
"reader",
"(",
"file_lol",
",",
"delimiter",
"=",
"';'",
")",
"next",
"(",
"champions",
")",
"for",
"elem",
"in",
"champions",
":",
"datos",
".",
"append",
"(",
"elem",
")",
"return",
"datos"
] | [
9,
0
] | [
17,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_opcion_from_1_0_0_1_0_0_1_0_offno | (t) | opcion_from : ID opcion_sobrenombre GROUP BY campos_c LIMIT opc_lim | opcion_from : ID opcion_sobrenombre GROUP BY campos_c LIMIT opc_lim | def p_opcion_from_1_0_0_1_0_0_1_0_offno(t):
'opcion_from : ID opcion_sobrenombre GROUP BY campos_c LIMIT opc_lim' | [
"def",
"p_opcion_from_1_0_0_1_0_0_1_0_offno",
"(",
"t",
")",
":"
] | [
1744,
0
] | [
1745,
75
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
apply_homography_objects | (objects: List[Object], h: np.ndarray) | return [apply_homography_object(object_, h) for object_ in objects] | Aplica la homografía a una lista de detecciones de objetos.
:param objects: lista de detecciones de objetos.
:param h: matriz de homografía.
:return: lista de detecciones de objetos con la homografía aplicada.
| Aplica la homografía a una lista de detecciones de objetos. | def apply_homography_objects(objects: List[Object], h: np.ndarray) -> List[Object]:
"""Aplica la homografía a una lista de detecciones de objetos.
:param objects: lista de detecciones de objetos.
:param h: matriz de homografía.
:return: lista de detecciones de objetos con la homografía aplicada.
"""
return [apply_homography_object(object_, h) for object_ in objects] | [
"def",
"apply_homography_objects",
"(",
"objects",
":",
"List",
"[",
"Object",
"]",
",",
"h",
":",
"np",
".",
"ndarray",
")",
"->",
"List",
"[",
"Object",
"]",
":",
"return",
"[",
"apply_homography_object",
"(",
"object_",
",",
"h",
")",
"for",
"object_",
"in",
"objects",
"]"
] | [
54,
0
] | [
61,
71
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_instruccion | (t) | instrucciones : instruccion | instrucciones : instruccion | def p_instruccion(t):
'instrucciones : instruccion'
t[0] = [t[1]]
varGramatical.append('instrucciones ::= instruccion')
varSemantico.append('e ') | [
"def",
"p_instruccion",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]",
"varGramatical",
".",
"append",
"(",
"'instrucciones ::= instruccion'",
")",
"varSemantico",
".",
"append",
"(",
"'e '",
")"
] | [
396,
0
] | [
400,
29
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
a | (datos) | return max(datos, key=datos.get) | Devuelve el código de la sección con más alumnos | Devuelve el código de la sección con más alumnos | def a(datos):
"""Devuelve el código de la sección con más alumnos"""
return max(datos, key=datos.get) | [
"def",
"a",
"(",
"datos",
")",
":",
"return",
"max",
"(",
"datos",
",",
"key",
"=",
"datos",
".",
"get",
")"
] | [
57,
0
] | [
59,
36
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
JRODataWriter.setNextFile | (self) | return 1 | Determina el siguiente file que sera escrito
Affected:
self.filename
self.subfolder
self.fp
self.setFile
self.flagIsNewFile
Return:
0 : Si el archivo no puede ser escrito
1 : Si el archivo esta listo para ser escrito
| Determina el siguiente file que sera escrito | def setNextFile(self):
"""Determina el siguiente file que sera escrito
Affected:
self.filename
self.subfolder
self.fp
self.setFile
self.flagIsNewFile
Return:
0 : Si el archivo no puede ser escrito
1 : Si el archivo esta listo para ser escrito
"""
ext = self.ext
path = self.path
if self.fp != None:
self.fp.close()
if not os.path.exists(path):
os.mkdir(path)
timeTuple = time.localtime(self.dataOut.utctime)
subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
fullpath = os.path.join(path, subfolder)
setFile = self.setFile
if not(os.path.exists(fullpath)):
os.mkdir(fullpath)
setFile = -1 # inicializo mi contador de seteo
else:
filesList = os.listdir(fullpath)
if len(filesList) > 0:
filesList = sorted(filesList, key=str.lower)
filen = filesList[-1]
# el filename debera tener el siguiente formato
# 0 1234 567 89A BCDE (hex)
# x YYYY DDD SSS .ext
if isNumber(filen[8:11]):
# inicializo mi contador de seteo al seteo del ultimo file
setFile = int(filen[8:11])
else:
setFile = -1
else:
setFile = -1 # inicializo mi contador de seteo
setFile += 1
# If this is a new day it resets some values
if self.dataOut.datatime.date() > self.fileDate:
setFile = 0
self.nTotalBlocks = 0
filen = '{}{:04d}{:03d}{:03d}{}'.format(
self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
filename = os.path.join(path, subfolder, filen)
fp = open(filename, 'wb')
self.blockIndex = 0
self.filename = filename
self.subfolder = subfolder
self.fp = fp
self.setFile = setFile
self.flagIsNewFile = 1
self.fileDate = self.dataOut.datatime.date()
self.setFirstHeader()
print('[Writing] Opening file: %s' % self.filename)
self.__writeFirstHeader()
return 1 | [
"def",
"setNextFile",
"(",
"self",
")",
":",
"ext",
"=",
"self",
".",
"ext",
"path",
"=",
"self",
".",
"path",
"if",
"self",
".",
"fp",
"!=",
"None",
":",
"self",
".",
"fp",
".",
"close",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
")",
"timeTuple",
"=",
"time",
".",
"localtime",
"(",
"self",
".",
"dataOut",
".",
"utctime",
")",
"subfolder",
"=",
"'d%4.4d%3.3d'",
"%",
"(",
"timeTuple",
".",
"tm_year",
",",
"timeTuple",
".",
"tm_yday",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"subfolder",
")",
"setFile",
"=",
"self",
".",
"setFile",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"fullpath",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"fullpath",
")",
"setFile",
"=",
"-",
"1",
"# inicializo mi contador de seteo",
"else",
":",
"filesList",
"=",
"os",
".",
"listdir",
"(",
"fullpath",
")",
"if",
"len",
"(",
"filesList",
")",
">",
"0",
":",
"filesList",
"=",
"sorted",
"(",
"filesList",
",",
"key",
"=",
"str",
".",
"lower",
")",
"filen",
"=",
"filesList",
"[",
"-",
"1",
"]",
"# el filename debera tener el siguiente formato",
"# 0 1234 567 89A BCDE (hex)",
"# x YYYY DDD SSS .ext",
"if",
"isNumber",
"(",
"filen",
"[",
"8",
":",
"11",
"]",
")",
":",
"# inicializo mi contador de seteo al seteo del ultimo file",
"setFile",
"=",
"int",
"(",
"filen",
"[",
"8",
":",
"11",
"]",
")",
"else",
":",
"setFile",
"=",
"-",
"1",
"else",
":",
"setFile",
"=",
"-",
"1",
"# inicializo mi contador de seteo",
"setFile",
"+=",
"1",
"# If this is a new day it resets some values",
"if",
"self",
".",
"dataOut",
".",
"datatime",
".",
"date",
"(",
")",
">",
"self",
".",
"fileDate",
":",
"setFile",
"=",
"0",
"self",
".",
"nTotalBlocks",
"=",
"0",
"filen",
"=",
"'{}{:04d}{:03d}{:03d}{}'",
".",
"format",
"(",
"self",
".",
"optchar",
",",
"timeTuple",
".",
"tm_year",
",",
"timeTuple",
".",
"tm_yday",
",",
"setFile",
",",
"ext",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"subfolder",
",",
"filen",
")",
"fp",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"self",
".",
"blockIndex",
"=",
"0",
"self",
".",
"filename",
"=",
"filename",
"self",
".",
"subfolder",
"=",
"subfolder",
"self",
".",
"fp",
"=",
"fp",
"self",
".",
"setFile",
"=",
"setFile",
"self",
".",
"flagIsNewFile",
"=",
"1",
"self",
".",
"fileDate",
"=",
"self",
".",
"dataOut",
".",
"datatime",
".",
"date",
"(",
")",
"self",
".",
"setFirstHeader",
"(",
")",
"print",
"(",
"'[Writing] Opening file: %s'",
"%",
"self",
".",
"filename",
")",
"self",
".",
"__writeFirstHeader",
"(",
")",
"return",
"1"
] | [
1413,
4
] | [
1488,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
make_sandwich | (*ingredientes) | Imprime una lista de ingredientes que han sido ordenados | Imprime una lista de ingredientes que han sido ordenados | def make_sandwich(*ingredientes):
""" Imprime una lista de ingredientes que han sido ordenados """
print("\nSandwich con los siguientes ingredientes: ")
for ingrediente in ingredientes:
print("- "+ingrediente) | [
"def",
"make_sandwich",
"(",
"*",
"ingredientes",
")",
":",
"print",
"(",
"\"\\nSandwich con los siguientes ingredientes: \"",
")",
"for",
"ingrediente",
"in",
"ingredientes",
":",
"print",
"(",
"\"- \"",
"+",
"ingrediente",
")"
] | [
8,
0
] | [
12,
31
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
NetworkCallback.get_user_network | (networkid: int, *, cursor) | return user | Obtener el nombre de usuario usado en esa red | Obtener el nombre de usuario usado en esa red | async def get_user_network(networkid: int, *, cursor) -> Tuple[str]:
"""Obtener el nombre de usuario usado en esa red"""
await cursor.execute(
"SELECT user FROM networks WHERE id_network = %s LIMIT 1",
(networkid,)
)
user = await cursor.fetchone()
return user | [
"async",
"def",
"get_user_network",
"(",
"networkid",
":",
"int",
",",
"*",
",",
"cursor",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"SELECT user FROM networks WHERE id_network = %s LIMIT 1\"",
",",
"(",
"networkid",
",",
")",
")",
"user",
"=",
"await",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"user"
] | [
477,
4
] | [
488,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
AbstractGMapsExtractor.export_data | (self, data, is_update=False) | Función encargada de hacer el volcado de la información en el soporte de salida que se haya configurado.
Parameters
----------
data : dict
datos que se van a volcar al soporte de salida (base de datos o fichero)
is_update : bool
flag que determina si se está actualizando, true si es un recovery
Returns
-------
data
devuelve o los mismos datos en caso de no tener una instancia de `writer` o True en caso de que la llamada
la función `write` haya sido satisfactoria
| Función encargada de hacer el volcado de la información en el soporte de salida que se haya configurado. | def export_data(self, data, is_update=False):
"""Función encargada de hacer el volcado de la información en el soporte de salida que se haya configurado.
Parameters
----------
data : dict
datos que se van a volcar al soporte de salida (base de datos o fichero)
is_update : bool
flag que determina si se está actualizando, true si es un recovery
Returns
-------
data
devuelve o los mismos datos en caso de no tener una instancia de `writer` o True en caso de que la llamada
la función `write` haya sido satisfactoria
"""
if self._writer:
return self._writer.write(data, is_update)
else:
return data | [
"def",
"export_data",
"(",
"self",
",",
"data",
",",
"is_update",
"=",
"False",
")",
":",
"if",
"self",
".",
"_writer",
":",
"return",
"self",
".",
"_writer",
".",
"write",
"(",
"data",
",",
"is_update",
")",
"else",
":",
"return",
"data"
] | [
302,
4
] | [
321,
23
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
scrap_place | (arguments) | return results | Función que crea una instancia de `PlacesExtractor` y ejecuta su función `scrap`. Esta función (`scrap_place`)
es llamada por el pool de procesos para paralelizar la extracción de los locales comerciales.
Parameters
----------
arguments : dict
contienen los parámetros para instanciar los scrappers de los locales comerciales (`PlacesExtractor`)
Returns
-------
bool
devuelve True si el local comercial fue correctamente registrado en el soporte de salida que se haya configurado
para la ejecución del programa. False en caso de algún fallo en el volcado al soporte de salida
| Función que crea una instancia de `PlacesExtractor` y ejecuta su función `scrap`. Esta función (`scrap_place`)
es llamada por el pool de procesos para paralelizar la extracción de los locales comerciales. | def scrap_place(arguments):
""" Función que crea una instancia de `PlacesExtractor` y ejecuta su función `scrap`. Esta función (`scrap_place`)
es llamada por el pool de procesos para paralelizar la extracción de los locales comerciales.
Parameters
----------
arguments : dict
contienen los parámetros para instanciar los scrappers de los locales comerciales (`PlacesExtractor`)
Returns
-------
bool
devuelve True si el local comercial fue correctamente registrado en el soporte de salida que se haya configurado
para la ejecución del programa. False en caso de algún fallo en el volcado al soporte de salida
"""
driver_location = arguments.get("driver_location")
url = arguments.get("url")
place_address = arguments.get("place_address")
place_name = arguments.get("place_name")
num_reviews = arguments.get("num_reviews")
output_config = arguments.get("output_config")
postal_code = arguments.get("postal_code")
extraction_date = arguments.get("extraction_date")
places_types = arguments.get("places_types")
scraper = PlacesExtractor(driver_location=driver_location,
url=url,
place_name=place_name,
place_address=place_address,
num_reviews=num_reviews,
output_config=output_config,
postal_code=postal_code,
places_types=places_types,
extraction_date=extraction_date)
results = False
if arguments.get("is_recovery") and arguments.get("place_id"):
results = scraper.recover(place_id=arguments.get("place_id"))
else:
results = scraper.scrap()
return results | [
"def",
"scrap_place",
"(",
"arguments",
")",
":",
"driver_location",
"=",
"arguments",
".",
"get",
"(",
"\"driver_location\"",
")",
"url",
"=",
"arguments",
".",
"get",
"(",
"\"url\"",
")",
"place_address",
"=",
"arguments",
".",
"get",
"(",
"\"place_address\"",
")",
"place_name",
"=",
"arguments",
".",
"get",
"(",
"\"place_name\"",
")",
"num_reviews",
"=",
"arguments",
".",
"get",
"(",
"\"num_reviews\"",
")",
"output_config",
"=",
"arguments",
".",
"get",
"(",
"\"output_config\"",
")",
"postal_code",
"=",
"arguments",
".",
"get",
"(",
"\"postal_code\"",
")",
"extraction_date",
"=",
"arguments",
".",
"get",
"(",
"\"extraction_date\"",
")",
"places_types",
"=",
"arguments",
".",
"get",
"(",
"\"places_types\"",
")",
"scraper",
"=",
"PlacesExtractor",
"(",
"driver_location",
"=",
"driver_location",
",",
"url",
"=",
"url",
",",
"place_name",
"=",
"place_name",
",",
"place_address",
"=",
"place_address",
",",
"num_reviews",
"=",
"num_reviews",
",",
"output_config",
"=",
"output_config",
",",
"postal_code",
"=",
"postal_code",
",",
"places_types",
"=",
"places_types",
",",
"extraction_date",
"=",
"extraction_date",
")",
"results",
"=",
"False",
"if",
"arguments",
".",
"get",
"(",
"\"is_recovery\"",
")",
"and",
"arguments",
".",
"get",
"(",
"\"place_id\"",
")",
":",
"results",
"=",
"scraper",
".",
"recover",
"(",
"place_id",
"=",
"arguments",
".",
"get",
"(",
"\"place_id\"",
")",
")",
"else",
":",
"results",
"=",
"scraper",
".",
"scrap",
"(",
")",
"return",
"results"
] | [
153,
0
] | [
191,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
apply_homography_object | (object_: Object, h: np.ndarray) | return object_ | Aplica la homografía a una detección de un objeto.
:param object_: detección del objeto.
:param h: matriz de homografía.
:return: detección del objeto con la homografía aplicada a sus puntos.
| Aplica la homografía a una detección de un objeto. | def apply_homography_object(object_: Object, h: np.ndarray) -> Object:
"""Aplica la homografía a una detección de un objeto.
:param object_: detección del objeto.
:param h: matriz de homografía.
:return: detección del objeto con la homografía aplicada a sus puntos.
"""
# Copiar el objeto para no editar el original.
object_ = copy.deepcopy(object_)
# Homografía al centro.
object_.center = apply_homography_point2d(object_.center, h)
# Homografía a la bounding box.
bounding_box_h = tuple(apply_homography_point2d(p, h) for p in object_.bounding_box)
object_.bounding_box = BoundingBox(*bounding_box_h)
return object_ | [
"def",
"apply_homography_object",
"(",
"object_",
":",
"Object",
",",
"h",
":",
"np",
".",
"ndarray",
")",
"->",
"Object",
":",
"# Copiar el objeto para no editar el original.",
"object_",
"=",
"copy",
".",
"deepcopy",
"(",
"object_",
")",
"# Homografía al centro.",
"object_",
".",
"center",
"=",
"apply_homography_point2d",
"(",
"object_",
".",
"center",
",",
"h",
")",
"# Homografía a la bounding box.",
"bounding_box_h",
"=",
"tuple",
"(",
"apply_homography_point2d",
"(",
"p",
",",
"h",
")",
"for",
"p",
"in",
"object_",
".",
"bounding_box",
")",
"object_",
".",
"bounding_box",
"=",
"BoundingBox",
"(",
"*",
"bounding_box_h",
")",
"return",
"object_"
] | [
37,
0
] | [
51,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
planilla.llamar | (self) | return [self.Participaron_ , self.llamar_a , self.Participantes_] | Crea una lista con participantes, elije al ganador y \
devuelve una lista de participantes sin el ganador | Crea una lista con participantes, elije al ganador y \
devuelve una lista de participantes sin el ganador | def llamar(self):
"Crea una lista con participantes, elije al ganador y \
devuelve una lista de participantes sin el ganador"
self.llamar_a=ra.sample(self.Participantes_,1)[0]
self.Participaron_=list(self.Participantes_)
self.Participantes_.remove(self.llamar_a)
return [self.Participaron_ , self.llamar_a , self.Participantes_] | [
"def",
"llamar",
"(",
"self",
")",
":",
"self",
".",
"llamar_a",
"=",
"ra",
".",
"sample",
"(",
"self",
".",
"Participantes_",
",",
"1",
")",
"[",
"0",
"]",
"self",
".",
"Participaron_",
"=",
"list",
"(",
"self",
".",
"Participantes_",
")",
"self",
".",
"Participantes_",
".",
"remove",
"(",
"self",
".",
"llamar_a",
")",
"return",
"[",
"self",
".",
"Participaron_",
",",
"self",
".",
"llamar_a",
",",
"self",
".",
"Participantes_",
"]"
] | [
94,
4
] | [
100,
73
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_con_drop | (p) | con_drop : column identificador
| constraint identificador | con_drop : column identificador
| constraint identificador | def p_con_drop(p):
'''con_drop : column identificador
| constraint identificador ''' | [
"def",
"p_con_drop",
"(",
"p",
")",
":"
] | [
127,
0
] | [
129,
35
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones53 | (p) | funciones : SIGN PABRE tipo_numero PCIERRA | funciones : SIGN PABRE tipo_numero PCIERRA | def p_funciones53(p):
'funciones : SIGN PABRE tipo_numero PCIERRA' | [
"def",
"p_funciones53",
"(",
"p",
")",
":"
] | [
457,
0
] | [
458,
48
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
CambiosDominio.registrantes_en_cambio | (self) | return registrante_anterior, registrante_nuevo | Si cambio el registrante devuelve el nuevo y el anterior | Si cambio el registrante devuelve el nuevo y el anterior | def registrantes_en_cambio(self):
""" Si cambio el registrante devuelve el nuevo y el anterior """
registrante_anterior = None
registrante_nuevo = None
for campo in self.campos.all():
if campo.campo == 'registrant_legal_uid':
if campo.anterior != '':
registrante_anterior = Registrante.objects.filter(legal_uid=campo.anterior).first()
if campo.nuevo != '':
registrante_nuevo = Registrante.objects.filter(legal_uid=campo.nuevo).first()
return registrante_anterior, registrante_nuevo | [
"def",
"registrantes_en_cambio",
"(",
"self",
")",
":",
"registrante_anterior",
"=",
"None",
"registrante_nuevo",
"=",
"None",
"for",
"campo",
"in",
"self",
".",
"campos",
".",
"all",
"(",
")",
":",
"if",
"campo",
".",
"campo",
"==",
"'registrant_legal_uid'",
":",
"if",
"campo",
".",
"anterior",
"!=",
"''",
":",
"registrante_anterior",
"=",
"Registrante",
".",
"objects",
".",
"filter",
"(",
"legal_uid",
"=",
"campo",
".",
"anterior",
")",
".",
"first",
"(",
")",
"if",
"campo",
".",
"nuevo",
"!=",
"''",
":",
"registrante_nuevo",
"=",
"Registrante",
".",
"objects",
".",
"filter",
"(",
"legal_uid",
"=",
"campo",
".",
"nuevo",
")",
".",
"first",
"(",
")",
"return",
"registrante_anterior",
",",
"registrante_nuevo"
] | [
14,
4
] | [
28,
54
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ingresar_numero | (indicacion: str) | Pide un número al usuario y lo devuelve.
:param indicacion: Indicación a mostrar al usuario.
:indicacion: str
:return: número ingresado por el usuario.
| Pide un número al usuario y lo devuelve. | def ingresar_numero(indicacion: str):
"""Pide un número al usuario y lo devuelve.
:param indicacion: Indicación a mostrar al usuario.
:indicacion: str
:return: número ingresado por el usuario.
"""
while True:
try:
numero = input(indicacion)
return float(numero)
except ValueError:
print(f"{numero} es un tipo de dato no válido.") | [
"def",
"ingresar_numero",
"(",
"indicacion",
":",
"str",
")",
":",
"while",
"True",
":",
"try",
":",
"numero",
"=",
"input",
"(",
"indicacion",
")",
"return",
"float",
"(",
"numero",
")",
"except",
"ValueError",
":",
"print",
"(",
"f\"{numero} es un tipo de dato no válido.\")",
""
] | [
4,
0
] | [
16,
61
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ObjectTracker.frame_objects | (self, fid: int) | return objects_in_frame | Método para obtener los objetos detectados en un frame.
Además, se aplican los filtros pasados a la instancia con el parámetro ``objects_filters``.
:param fid: índice del frame del que se quieren extraer los objetos.
:return: lista de los objetos detectados en ese frame.
| Método para obtener los objetos detectados en un frame. | def frame_objects(self, fid: int) -> List[Object]:
"""Método para obtener los objetos detectados en un frame.
Además, se aplican los filtros pasados a la instancia con el parámetro ``objects_filters``.
:param fid: índice del frame del que se quieren extraer los objetos.
:return: lista de los objetos detectados en ese frame.
"""
# Obtener los objetos del detector si no hay detecciones precargadas.
objects_in_frame = self.objects_detections[fid]
# Aplicar los filtros a los objetos.
for filter_function in self.objects_filters:
objects_in_frame = filter_function(objects_in_frame)
return objects_in_frame | [
"def",
"frame_objects",
"(",
"self",
",",
"fid",
":",
"int",
")",
"->",
"List",
"[",
"Object",
"]",
":",
"# Obtener los objetos del detector si no hay detecciones precargadas.",
"objects_in_frame",
"=",
"self",
".",
"objects_detections",
"[",
"fid",
"]",
"# Aplicar los filtros a los objetos.",
"for",
"filter_function",
"in",
"self",
".",
"objects_filters",
":",
"objects_in_frame",
"=",
"filter_function",
"(",
"objects_in_frame",
")",
"return",
"objects_in_frame"
] | [
45,
4
] | [
58,
31
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
HeapSort | (A) | Metodo de ordenamiento HeapSort | Metodo de ordenamiento HeapSort | def HeapSort(A):
"""Metodo de ordenamiento HeapSort"""
def heapify(A):
start = (len(A) - 2) / 2
while start >= 0:
siftDown(A, start, len(A) - 1)
start -= 1
def siftDown(A, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and A[child] < A[child + 1]:
child += 1
if child <= end and A[root] < A[child]:
A[root], A[child] = A[child], A[root]
root = child
else:
return
heapify(A)
end = len(A) - 1
while end > 0:
A[end], A[0] = A[0], A[end]
siftDown(A, 0, end - 1)
end -= 1 | [
"def",
"HeapSort",
"(",
"A",
")",
":",
"def",
"heapify",
"(",
"A",
")",
":",
"start",
"=",
"(",
"len",
"(",
"A",
")",
"-",
"2",
")",
"/",
"2",
"while",
"start",
">=",
"0",
":",
"siftDown",
"(",
"A",
",",
"start",
",",
"len",
"(",
"A",
")",
"-",
"1",
")",
"start",
"-=",
"1",
"def",
"siftDown",
"(",
"A",
",",
"start",
",",
"end",
")",
":",
"root",
"=",
"start",
"while",
"root",
"*",
"2",
"+",
"1",
"<=",
"end",
":",
"child",
"=",
"root",
"*",
"2",
"+",
"1",
"if",
"child",
"+",
"1",
"<=",
"end",
"and",
"A",
"[",
"child",
"]",
"<",
"A",
"[",
"child",
"+",
"1",
"]",
":",
"child",
"+=",
"1",
"if",
"child",
"<=",
"end",
"and",
"A",
"[",
"root",
"]",
"<",
"A",
"[",
"child",
"]",
":",
"A",
"[",
"root",
"]",
",",
"A",
"[",
"child",
"]",
"=",
"A",
"[",
"child",
"]",
",",
"A",
"[",
"root",
"]",
"root",
"=",
"child",
"else",
":",
"return",
"heapify",
"(",
"A",
")",
"end",
"=",
"len",
"(",
"A",
")",
"-",
"1",
"while",
"end",
">",
"0",
":",
"A",
"[",
"end",
"]",
",",
"A",
"[",
"0",
"]",
"=",
"A",
"[",
"0",
"]",
",",
"A",
"[",
"end",
"]",
"siftDown",
"(",
"A",
",",
"0",
",",
"end",
"-",
"1",
")",
"end",
"-=",
"1"
] | [
79,
0
] | [
103,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
RBF.fit | (self) | return acc | Método que ajusta una red de funciones de base radial gaussianas al conjunto de datos
de entrenamiento, cacula las predicciones sobre el conjunto de test y devuelve el valor de accuracy
y matriz de confusión (si así se especifica en el atributo self.matrix) obtenidos por dicho modelo ajustado | Método que ajusta una red de funciones de base radial gaussianas al conjunto de datos
de entrenamiento, cacula las predicciones sobre el conjunto de test y devuelve el valor de accuracy
y matriz de confusión (si así se especifica en el atributo self.matrix) obtenidos por dicho modelo ajustado | def fit(self):
""" Método que ajusta una red de funciones de base radial gaussianas al conjunto de datos
de entrenamiento, cacula las predicciones sobre el conjunto de test y devuelve el valor de accuracy
y matriz de confusión (si así se especifica en el atributo self.matrix) obtenidos por dicho modelo ajustado """
#Cálculo de los centroides con el algoritmo de K-means
self.centroids = KMeans(n_clusters=self.k, random_state=24, algorithm='full').fit(self.X).cluster_centers_
#Cálculo de los parámetros de escala, r
self.coef = np.repeat(self.R / np.power(self.k,1/self.X.shape[1]), self.k)
#Calculo de la matriz Z para el ajuste lineal
RBF_X = self.rbf_list(self.X, self.centroids, self.coef)
#Cálculo de los pesos w con el algoritmo de la pseudoinversa
self.w = np.linalg.pinv(RBF_X.T @ RBF_X) @ RBF_X.T @ self.convert_to_one_hot(self.y, self.number_of_classes)
#Cálculo de las predicciones del conjunto de test
RBF_list_tst = self.rbf_list(self.tX, self.centroids, self.coef)
self.pred_ty = RBF_list_tst @ self.w
self.pred_ty = np.array([np.argmax(x) for x in self.pred_ty])
#Accuracy obtenida sobre el conjunto de test
acc=accuracy_score(self.ty, self.pred_ty)
if self.matrix:
#Cálculo de la matriz de confusión
m=confusion_matrix(self.ty, self.pred_ty, normalize='all')
return m,acc
return acc | [
"def",
"fit",
"(",
"self",
")",
":",
"#Cálculo de los centroides con el algoritmo de K-means",
"self",
".",
"centroids",
"=",
"KMeans",
"(",
"n_clusters",
"=",
"self",
".",
"k",
",",
"random_state",
"=",
"24",
",",
"algorithm",
"=",
"'full'",
")",
".",
"fit",
"(",
"self",
".",
"X",
")",
".",
"cluster_centers_",
"#Cálculo de los parámetros de escala, r",
"self",
".",
"coef",
"=",
"np",
".",
"repeat",
"(",
"self",
".",
"R",
"/",
"np",
".",
"power",
"(",
"self",
".",
"k",
",",
"1",
"/",
"self",
".",
"X",
".",
"shape",
"[",
"1",
"]",
")",
",",
"self",
".",
"k",
")",
"#Calculo de la matriz Z para el ajuste lineal ",
"RBF_X",
"=",
"self",
".",
"rbf_list",
"(",
"self",
".",
"X",
",",
"self",
".",
"centroids",
",",
"self",
".",
"coef",
")",
"#Cálculo de los pesos w con el algoritmo de la pseudoinversa",
"self",
".",
"w",
"=",
"np",
".",
"linalg",
".",
"pinv",
"(",
"RBF_X",
".",
"T",
"@",
"RBF_X",
")",
"@",
"RBF_X",
".",
"T",
"@",
"self",
".",
"convert_to_one_hot",
"(",
"self",
".",
"y",
",",
"self",
".",
"number_of_classes",
")",
"#Cálculo de las predicciones del conjunto de test",
"RBF_list_tst",
"=",
"self",
".",
"rbf_list",
"(",
"self",
".",
"tX",
",",
"self",
".",
"centroids",
",",
"self",
".",
"coef",
")",
"self",
".",
"pred_ty",
"=",
"RBF_list_tst",
"@",
"self",
".",
"w",
"self",
".",
"pred_ty",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"argmax",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"pred_ty",
"]",
")",
"#Accuracy obtenida sobre el conjunto de test",
"acc",
"=",
"accuracy_score",
"(",
"self",
".",
"ty",
",",
"self",
".",
"pred_ty",
")",
"if",
"self",
".",
"matrix",
":",
"#Cálculo de la matriz de confusión",
"m",
"=",
"confusion_matrix",
"(",
"self",
".",
"ty",
",",
"self",
".",
"pred_ty",
",",
"normalize",
"=",
"'all'",
")",
"return",
"m",
",",
"acc",
"return",
"acc"
] | [
70,
4
] | [
99,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Registros.__iter__ | (self) | Texto y metadata de cada registro en cada archivo. | Texto y metadata de cada registro en cada archivo. | def __iter__(self):
"""Texto y metadata de cada registro en cada archivo."""
self.n = 0
for archivo in iterar_rutas(
self.absoluto, recursivo=self.recursivo, exts=self.exts
):
if archivo.suffix.endswith(".csv"):
df = pd.read_csv(archivo)
else:
df = pd.read_excel(archivo, sheet_name=self.hoja)
df = df.dropna(subset=[self.textcol])
self.n += 1
yield from Datos(df, self.textcol, self.metacols, chars=self.chars) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"self",
".",
"n",
"=",
"0",
"for",
"archivo",
"in",
"iterar_rutas",
"(",
"self",
".",
"absoluto",
",",
"recursivo",
"=",
"self",
".",
"recursivo",
",",
"exts",
"=",
"self",
".",
"exts",
")",
":",
"if",
"archivo",
".",
"suffix",
".",
"endswith",
"(",
"\".csv\"",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"archivo",
")",
"else",
":",
"df",
"=",
"pd",
".",
"read_excel",
"(",
"archivo",
",",
"sheet_name",
"=",
"self",
".",
"hoja",
")",
"df",
"=",
"df",
".",
"dropna",
"(",
"subset",
"=",
"[",
"self",
".",
"textcol",
"]",
")",
"self",
".",
"n",
"+=",
"1",
"yield",
"from",
"Datos",
"(",
"df",
",",
"self",
".",
"textcol",
",",
"self",
".",
"metacols",
",",
"chars",
"=",
"self",
".",
"chars",
")"
] | [
420,
4
] | [
436,
79
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DataCleaner._validate_filters | (entity_level, filters) | return True | Verifica que los filtros sean validos con el nivel de entidad a
normalizar.
Args:
entity_level: Nivel de la unidad territorial por la cual filtrar.
filters (dict): Diccionario con filtros.
Returns:
bool: Verdadero si los filtros son válidos.
| Verifica que los filtros sean validos con el nivel de entidad a
normalizar. | def _validate_filters(entity_level, filters):
"""Verifica que los filtros sean validos con el nivel de entidad a
normalizar.
Args:
entity_level: Nivel de la unidad territorial por la cual filtrar.
filters (dict): Diccionario con filtros.
Returns:
bool: Verdadero si los filtros son válidos.
"""
field_prov = PROV + '_field'
field_dept = DEPT + '_field'
field_mun = MUN + '_field'
# Verfica que se utilicen keywords válidos por entidad
for key, value in filters.items():
if key not in [field_prov, field_dept, field_mun]:
print('"{}" no es un keyword válido.'.format(key))
return
if entity_level in key or entity_level in PROV:
print('"{}" no es un filtro válido para la entidad "{}."'
.format(key, entity_level))
return
if entity_level in DEPT and PROV not in key:
print('"{}" no es un filtro válido para la entidad "{}".'
.format(key, entity_level))
return
return True | [
"def",
"_validate_filters",
"(",
"entity_level",
",",
"filters",
")",
":",
"field_prov",
"=",
"PROV",
"+",
"'_field'",
"field_dept",
"=",
"DEPT",
"+",
"'_field'",
"field_mun",
"=",
"MUN",
"+",
"'_field'",
"# Verfica que se utilicen keywords válidos por entidad",
"for",
"key",
",",
"value",
"in",
"filters",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"field_prov",
",",
"field_dept",
",",
"field_mun",
"]",
":",
"print",
"(",
"'\"{}\" no es un keyword válido.'.",
"f",
"ormat(",
"k",
"ey)",
")",
"",
"return",
"if",
"entity_level",
"in",
"key",
"or",
"entity_level",
"in",
"PROV",
":",
"print",
"(",
"'\"{}\" no es un filtro válido para la entidad \"{}.\"'",
".",
"format",
"(",
"key",
",",
"entity_level",
")",
")",
"return",
"if",
"entity_level",
"in",
"DEPT",
"and",
"PROV",
"not",
"in",
"key",
":",
"print",
"(",
"'\"{}\" no es un filtro válido para la entidad \"{}\".'",
".",
"format",
"(",
"key",
",",
"entity_level",
")",
")",
"return",
"return",
"True"
] | [
841,
4
] | [
872,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
format_text_to_html | (text: str) | return html_txt | realiza el formato del texto pasado a un formato html | realiza el formato del texto pasado a un formato html | def format_text_to_html(text: str):
""" realiza el formato del texto pasado a un formato html"""
html_txt = text.replace("<", '<')
html_txt = html_txt.replace(">", '>').replace("\n", '<br>')
html_txt = html_txt.replace("\t", '	')
html_txt = html_txt.replace(" ", ' ')
return html_txt | [
"def",
"format_text_to_html",
"(",
"text",
":",
"str",
")",
":",
"html_txt",
"=",
"text",
".",
"replace",
"(",
"\"<\"",
",",
"'<'",
")",
"html_txt",
"=",
"html_txt",
".",
"replace",
"(",
"\">\"",
",",
"'>'",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"'<br>'",
")",
"html_txt",
"=",
"html_txt",
".",
"replace",
"(",
"\"\\t\"",
",",
"'	'",
")",
"html_txt",
"=",
"html_txt",
".",
"replace",
"(",
"\" \"",
",",
"' '",
")",
"return",
"html_txt"
] | [
5,
0
] | [
11,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
TrackedObject.__len__ | (self) | return len(self.detections) | Cantidad de veces que ha sido detectado el objeto.
:return: número de seguimientos del objeto.
| Cantidad de veces que ha sido detectado el objeto. | def __len__(self) -> int:
"""Cantidad de veces que ha sido detectado el objeto.
:return: número de seguimientos del objeto.
"""
return len(self.detections) | [
"def",
"__len__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"detections",
")"
] | [
50,
4
] | [
55,
35
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Hasar2GenComandos.getLastNumber | (self, letter) | Obtiene el último número de FC | Obtiene el último número de FC | def getLastNumber(self, letter):
"""Obtiene el último número de FC"""
pass | [
"def",
"getLastNumber",
"(",
"self",
",",
"letter",
")",
":",
"pass"
] | [
397,
1
] | [
399,
6
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ArregloDinamico._crear | (c: int) | return (c * py_object)() | Crea un arreglo dinamico de capacidad `c`
:param c: capacidad del arreglo
:c type: int
:return: arreglo dinamico
:rtype: POINTER(py_object)
| Crea un arreglo dinamico de capacidad `c` | def _crear(c: int) -> POINTER(py_object):
""" Crea un arreglo dinamico de capacidad `c`
:param c: capacidad del arreglo
:c type: int
:return: arreglo dinamico
:rtype: POINTER(py_object)
"""
return (c * py_object)() | [
"def",
"_crear",
"(",
"c",
":",
"int",
")",
"->",
"POINTER",
"(",
"py_object",
")",
":",
"return",
"(",
"c",
"*",
"py_object",
")",
"(",
")"
] | [
175,
4
] | [
183,
32
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
TokenCallback.insert_token | (
self,
userid: int,
expire: int,
services: str = "*",
token_len: int = 32, *,
cursor
) | return token.hex() | Inserta un nuevo token
Args:
userid:
El identificador de usuario
expire:
La fecha de expiración expresada en segundos
services:
Una expresión regular que indica qué servicios estarán habilitados
token_len:
La longitud del token
Returns:
El token de acceso
| Inserta un nuevo token | async def insert_token(
self,
userid: int,
expire: int,
services: str = "*",
token_len: int = 32, *,
cursor
) -> str:
"""Inserta un nuevo token
Args:
userid:
El identificador de usuario
expire:
La fecha de expiración expresada en segundos
services:
Una expresión regular que indica qué servicios estarán habilitados
token_len:
La longitud del token
Returns:
El token de acceso
"""
(token, hash_token) = self.__generate_token(token_len)
await self.__check_token(userid, cursor=cursor)
logging.debug(
_("Creando un nuevo token para el identificador de usuario: ID:%d"),
userid
)
await cursor.execute(
"INSERT INTO tokens(id_user, token, expire, services) VALUES(%s, %s, UNIX_TIMESTAMP() + %s, %s)",
(userid, hash_token, expire, services)
)
return token.hex() | [
"async",
"def",
"insert_token",
"(",
"self",
",",
"userid",
":",
"int",
",",
"expire",
":",
"int",
",",
"services",
":",
"str",
"=",
"\"*\"",
",",
"token_len",
":",
"int",
"=",
"32",
",",
"*",
",",
"cursor",
")",
"->",
"str",
":",
"(",
"token",
",",
"hash_token",
")",
"=",
"self",
".",
"__generate_token",
"(",
"token_len",
")",
"await",
"self",
".",
"__check_token",
"(",
"userid",
",",
"cursor",
"=",
"cursor",
")",
"logging",
".",
"debug",
"(",
"_",
"(",
"\"Creando un nuevo token para el identificador de usuario: ID:%d\"",
")",
",",
"userid",
")",
"await",
"cursor",
".",
"execute",
"(",
"\"INSERT INTO tokens(id_user, token, expire, services) VALUES(%s, %s, UNIX_TIMESTAMP() + %s, %s)\"",
",",
"(",
"userid",
",",
"hash_token",
",",
"expire",
",",
"services",
")",
")",
"return",
"token",
".",
"hex",
"(",
")"
] | [
367,
4
] | [
412,
26
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_inst_ifelse | (t) | instruccion : IF expre THEN instrucciones ELSE instrucciones END IF PUNTO_COMA | instruccion : IF expre THEN instrucciones ELSE instrucciones END IF PUNTO_COMA | def p_inst_ifelse(t):
''' instruccion : IF expre THEN instrucciones ELSE instrucciones END IF PUNTO_COMA'''
strGram = "<instruccion> ::= IF <expre> THEN <instrucciones> ELSE <instrucciones> END IF PUNTO_COMA "
t[0] = clase_if( t[2], Block(t[4]), Block(t[6]), strGram,t.lexer.lineno, t.lexer.lexpos) | [
"def",
"p_inst_ifelse",
"(",
"t",
")",
":",
"strGram",
"=",
"\"<instruccion> ::= IF <expre> THEN <instrucciones> ELSE <instrucciones> END IF PUNTO_COMA \"",
"t",
"[",
"0",
"]",
"=",
"clase_if",
"(",
"t",
"[",
"2",
"]",
",",
"Block",
"(",
"t",
"[",
"4",
"]",
")",
",",
"Block",
"(",
"t",
"[",
"6",
"]",
")",
",",
"strGram",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"t",
".",
"lexer",
".",
"lexpos",
")"
] | [
384,
0
] | [
387,
92
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
LLamadaFuncion.getval | (self, ent:Entorno,err=1) | ejecucion llamada funcinon | ejecucion llamada funcinon | def getval(self, ent:Entorno,err=1):
'ejecucion llamada funcinon'
sim=ent.buscarSimbolo('_f'+self.nombre)
if sim != None:
tipo=sim.tipo
defparams=sim.valor[0]
instrucciones=sim.valor[1]
newent=Entorno(ent)
if self.parametros!=None and defparams!=None:
if len(defparams)==len(self.parametros):
for i in range(0,len(defparams)):
param=defparams[i]
dec=Declaracion(param.nombre,False,param.tipo,self.parametros[i])
dec.ejecutar(newent)
for inst in instrucciones:
v= inst.ejecutar(newent)
if v!=None:
util=Tipo('',None,-1,-1)
if util.comparetipo(v.tipo,tipo):
return v
else:
reporteerrores.append(Lerrores("Error Semantico", "Error el tipo devuelto no coincide con el de la funcion", 0, 0))
variables.consola.insert(INSERT, "Error el tipo devuelto no coincide con el de la funcion\n")
else:
reporteerrores.append(Lerrores("Error Semantico","Error Los parametros no coinciden con la definicion de la funcion",0, 0))
variables.consola.insert(INSERT,"Error Los parametros no coinciden con la definicion de la funcion\n")
return
else:
for inst in instrucciones:
v = inst.ejecutar(newent)
if v != None:
util = Tipo('', None, -1, -1)
if util.comparetipo(v.tipo, tipo):
return v
else:
reporteerrores.append(
Lerrores("Error Semantico", "Error el tipo devuelto no coincide con el de la funcion",
0, 0))
variables.consola.insert(INSERT, "Error el tipo devuelto no coincide con el de la funcion\n")
else:
if err==1:
reporteerrores.append(
Lerrores("Error Semantico", "Error la funcion '"+self.nombre+"' no existe",
0, 0))
variables.consola.insert(INSERT, "Error la funcion '"+self.nombre+"' no existe\n") | [
"def",
"getval",
"(",
"self",
",",
"ent",
":",
"Entorno",
",",
"err",
"=",
"1",
")",
":",
"sim",
"=",
"ent",
".",
"buscarSimbolo",
"(",
"'_f'",
"+",
"self",
".",
"nombre",
")",
"if",
"sim",
"!=",
"None",
":",
"tipo",
"=",
"sim",
".",
"tipo",
"defparams",
"=",
"sim",
".",
"valor",
"[",
"0",
"]",
"instrucciones",
"=",
"sim",
".",
"valor",
"[",
"1",
"]",
"newent",
"=",
"Entorno",
"(",
"ent",
")",
"if",
"self",
".",
"parametros",
"!=",
"None",
"and",
"defparams",
"!=",
"None",
":",
"if",
"len",
"(",
"defparams",
")",
"==",
"len",
"(",
"self",
".",
"parametros",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"defparams",
")",
")",
":",
"param",
"=",
"defparams",
"[",
"i",
"]",
"dec",
"=",
"Declaracion",
"(",
"param",
".",
"nombre",
",",
"False",
",",
"param",
".",
"tipo",
",",
"self",
".",
"parametros",
"[",
"i",
"]",
")",
"dec",
".",
"ejecutar",
"(",
"newent",
")",
"for",
"inst",
"in",
"instrucciones",
":",
"v",
"=",
"inst",
".",
"ejecutar",
"(",
"newent",
")",
"if",
"v",
"!=",
"None",
":",
"util",
"=",
"Tipo",
"(",
"''",
",",
"None",
",",
"-",
"1",
",",
"-",
"1",
")",
"if",
"util",
".",
"comparetipo",
"(",
"v",
".",
"tipo",
",",
"tipo",
")",
":",
"return",
"v",
"else",
":",
"reporteerrores",
".",
"append",
"(",
"Lerrores",
"(",
"\"Error Semantico\"",
",",
"\"Error el tipo devuelto no coincide con el de la funcion\"",
",",
"0",
",",
"0",
")",
")",
"variables",
".",
"consola",
".",
"insert",
"(",
"INSERT",
",",
"\"Error el tipo devuelto no coincide con el de la funcion\\n\"",
")",
"else",
":",
"reporteerrores",
".",
"append",
"(",
"Lerrores",
"(",
"\"Error Semantico\"",
",",
"\"Error Los parametros no coinciden con la definicion de la funcion\"",
",",
"0",
",",
"0",
")",
")",
"variables",
".",
"consola",
".",
"insert",
"(",
"INSERT",
",",
"\"Error Los parametros no coinciden con la definicion de la funcion\\n\"",
")",
"return",
"else",
":",
"for",
"inst",
"in",
"instrucciones",
":",
"v",
"=",
"inst",
".",
"ejecutar",
"(",
"newent",
")",
"if",
"v",
"!=",
"None",
":",
"util",
"=",
"Tipo",
"(",
"''",
",",
"None",
",",
"-",
"1",
",",
"-",
"1",
")",
"if",
"util",
".",
"comparetipo",
"(",
"v",
".",
"tipo",
",",
"tipo",
")",
":",
"return",
"v",
"else",
":",
"reporteerrores",
".",
"append",
"(",
"Lerrores",
"(",
"\"Error Semantico\"",
",",
"\"Error el tipo devuelto no coincide con el de la funcion\"",
",",
"0",
",",
"0",
")",
")",
"variables",
".",
"consola",
".",
"insert",
"(",
"INSERT",
",",
"\"Error el tipo devuelto no coincide con el de la funcion\\n\"",
")",
"else",
":",
"if",
"err",
"==",
"1",
":",
"reporteerrores",
".",
"append",
"(",
"Lerrores",
"(",
"\"Error Semantico\"",
",",
"\"Error la funcion '\"",
"+",
"self",
".",
"nombre",
"+",
"\"' no existe\"",
",",
"0",
",",
"0",
")",
")",
"variables",
".",
"consola",
".",
"insert",
"(",
"INSERT",
",",
"\"Error la funcion '\"",
"+",
"self",
".",
"nombre",
"+",
"\"' no existe\\n\"",
")"
] | [
24,
4
] | [
69,
98
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
InstantaneousVelocityWithKernelRegression._get_kernel | (self, kernel: NadayaraWatsonEstimator) | return kernels[kernel] | Devuelve las funciones del kernel y su derivada respectivamente.
:param kernel: kernel.
:return: función del kernel y función del kernel derivado.
| Devuelve las funciones del kernel y su derivada respectivamente. | def _get_kernel(self, kernel: NadayaraWatsonEstimator) -> Tuple[Callable, Callable]:
"""Devuelve las funciones del kernel y su derivada respectivamente.
:param kernel: kernel.
:return: función del kernel y función del kernel derivado.
"""
kernels = {
self.NadayaraWatsonEstimator.KERNEL_GAUSS:
(self.kernel_gauss, self.kernel_gauss_derivated),
self.NadayaraWatsonEstimator.KERNEL_TRIANGULAR:
(self.kernel_triangular, self.kernel_triangular_derivated),
self.NadayaraWatsonEstimator.KERNEL_QUADRATIC:
NotImplemented,
}
return kernels[kernel] | [
"def",
"_get_kernel",
"(",
"self",
",",
"kernel",
":",
"NadayaraWatsonEstimator",
")",
"->",
"Tuple",
"[",
"Callable",
",",
"Callable",
"]",
":",
"kernels",
"=",
"{",
"self",
".",
"NadayaraWatsonEstimator",
".",
"KERNEL_GAUSS",
":",
"(",
"self",
".",
"kernel_gauss",
",",
"self",
".",
"kernel_gauss_derivated",
")",
",",
"self",
".",
"NadayaraWatsonEstimator",
".",
"KERNEL_TRIANGULAR",
":",
"(",
"self",
".",
"kernel_triangular",
",",
"self",
".",
"kernel_triangular_derivated",
")",
",",
"self",
".",
"NadayaraWatsonEstimator",
".",
"KERNEL_QUADRATIC",
":",
"NotImplemented",
",",
"}",
"return",
"kernels",
"[",
"kernel",
"]"
] | [
105,
4
] | [
119,
30
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ProcControl.getProc | (self, item, target=None) | return super().__getitem__(target)[item] | Obtener el proceso/subproceso | Obtener el proceso/subproceso | def getProc(self, item, target=None):
"""Obtener el proceso/subproceso"""
target = self._get_target_name(target)
return super().__getitem__(target)[item] | [
"def",
"getProc",
"(",
"self",
",",
"item",
",",
"target",
"=",
"None",
")",
":",
"target",
"=",
"self",
".",
"_get_target_name",
"(",
"target",
")",
"return",
"super",
"(",
")",
".",
"__getitem__",
"(",
"target",
")",
"[",
"item",
"]"
] | [
255,
4
] | [
260,
48
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_expresion | (t) | expresion : cualquiercadena
| expresionaritmetica | expresion : cualquiercadena
| expresionaritmetica | def p_expresion(t) :
'''expresion : cualquiercadena
| expresionaritmetica''' | [
"def",
"p_expresion",
"(",
"t",
")",
":"
] | [
703,
0
] | [
705,
46
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
BcraLiborScraperTestCase.test_read_valid_configuration | (self) | Validar que el formato del archivo sea Json | Validar que el formato del archivo sea Json | def test_read_valid_configuration(self):
"""Validar que el formato del archivo sea Json"""
dict_config = "{"
with mock.patch(
'builtins.open',
return_value=io.StringIO(dict_config)):
with self.assertRaises(InvalidConfigurationError):
read_config("config_general.json", "cmd") | [
"def",
"test_read_valid_configuration",
"(",
"self",
")",
":",
"dict_config",
"=",
"\"{\"",
"with",
"mock",
".",
"patch",
"(",
"'builtins.open'",
",",
"return_value",
"=",
"io",
".",
"StringIO",
"(",
"dict_config",
")",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"InvalidConfigurationError",
")",
":",
"read_config",
"(",
"\"config_general.json\"",
",",
"\"cmd\"",
")"
] | [
568,
4
] | [
577,
57
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
model | (x,param) | return y | Modelo polinomial. `param` contiene los coeficientes.
| Modelo polinomial. `param` contiene los coeficientes.
| def model(x,param):
"""Modelo polinomial. `param` contiene los coeficientes.
"""
n_param = len(param)
y = 0
for i in range(n_param):
y += param[i] * x**i
return y | [
"def",
"model",
"(",
"x",
",",
"param",
")",
":",
"n_param",
"=",
"len",
"(",
"param",
")",
"y",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"n_param",
")",
":",
"y",
"+=",
"param",
"[",
"i",
"]",
"*",
"x",
"**",
"i",
"return",
"y"
] | [
4,
0
] | [
11,
12
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_EXPT13 | (t) | EXP : interval cadena | EXP : interval cadena | def p_EXPT13(t):
'EXP : interval cadena'
t[0] = Terminal('interval', t[1]) | [
"def",
"p_EXPT13",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"Terminal",
"(",
"'interval'",
",",
"t",
"[",
"1",
"]",
")"
] | [
767,
0
] | [
769,
37
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
UserViewSet.solicitar_bancarrota | (self, request, pk=None) | Un jugador solicita bancarrota y transfiere
todo su dinero al jugador que lo provocó | Un jugador solicita bancarrota y transfiere
todo su dinero al jugador que lo provocó | def solicitar_bancarrota(self, request, pk=None):
"""Un jugador solicita bancarrota y transfiere
todo su dinero al jugador que lo provocó """
user1 = self.request.user #usuario que envía
user1.status = 'I'
user1.save()
serializer = TransactionSerializer(data=request.data)
if serializer.is_valid():
transaction = serializer.save(userTransmitter=user1, amount=user1.amount)
amount = user1.amount
user2 = transaction.userReceiver #usuario que recibe
user1.amount = 0
user2.amount +=amount
user1.save()
user2.save()
mensaje={
'info':'La transacción se ha realizado con éxito.'
}
return Response(mensaje, status=status.HTTP_200_OK)
else:
return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) | [
"def",
"solicitar_bancarrota",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"user1",
"=",
"self",
".",
"request",
".",
"user",
"#usuario que envía",
"user1",
".",
"status",
"=",
"'I'",
"user1",
".",
"save",
"(",
")",
"serializer",
"=",
"TransactionSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"transaction",
"=",
"serializer",
".",
"save",
"(",
"userTransmitter",
"=",
"user1",
",",
"amount",
"=",
"user1",
".",
"amount",
")",
"amount",
"=",
"user1",
".",
"amount",
"user2",
"=",
"transaction",
".",
"userReceiver",
"#usuario que recibe",
"user1",
".",
"amount",
"=",
"0",
"user2",
".",
"amount",
"+=",
"amount",
"user1",
".",
"save",
"(",
")",
"user2",
".",
"save",
"(",
")",
"mensaje",
"=",
"{",
"'info'",
":",
"'La transacción se ha realizado con éxito.'",
"}",
"return",
"Response",
"(",
"mensaje",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")",
"else",
":",
"return",
"Response",
"(",
"{",
"\"errors\"",
":",
"(",
"serializer",
".",
"errors",
",",
")",
"}",
",",
"status",
"=",
"status",
".",
"HTTP_400_BAD_REQUEST",
")"
] | [
107,
4
] | [
129,
97
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Shape.setY | (self, index, y) | sets y coordinate | sets y coordinate | def setY(self, index, y):
"""sets y coordinate"""
self.coords[index][1] = y | [
"def",
"setY",
"(",
"self",
",",
"index",
",",
"y",
")",
":",
"self",
".",
"coords",
"[",
"index",
"]",
"[",
"1",
"]",
"=",
"y"
] | [
438,
4
] | [
441,
33
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Estante.esarchivo | (self) | return isinstance(self.dic, shelve.DbfilenameShelf) | Retorna True si el diccionario es un archivo shelve. | Retorna True si el diccionario es un archivo shelve. | def esarchivo(self):
"""Retorna True si el diccionario es un archivo shelve."""
return isinstance(self.dic, shelve.DbfilenameShelf) | [
"def",
"esarchivo",
"(",
"self",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"dic",
",",
"shelve",
".",
"DbfilenameShelf",
")"
] | [
63,
4
] | [
65,
59
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
printHeader | (letra) | Imprime un encabezado para el ejercicio con texto: "Ejercicio L".
Args:
letra (str): Letra del o los ejercicios,
| Imprime un encabezado para el ejercicio con texto: "Ejercicio L". | def printHeader(letra):
"""Imprime un encabezado para el ejercicio con texto: "Ejercicio L".
Args:
letra (str): Letra del o los ejercicios,
"""
print() # Línea en blanco
if (len(letra) > 1):
print("Ejercicios " + letra)
else:
print("Ejercicio " + letra)
print("="*30)
print() | [
"def",
"printHeader",
"(",
"letra",
")",
":",
"print",
"(",
")",
"# Línea en blanco",
"if",
"(",
"len",
"(",
"letra",
")",
">",
"1",
")",
":",
"print",
"(",
"\"Ejercicios \"",
"+",
"letra",
")",
"else",
":",
"print",
"(",
"\"Ejercicio \"",
"+",
"letra",
")",
"print",
"(",
"\"=\"",
"*",
"30",
")",
"print",
"(",
")"
] | [
79,
0
] | [
91,
11
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_opciones_select_lista2 | (t) | opciones_select_lista : opcion_select | opciones_select_lista : opcion_select | def p_opciones_select_lista2(t):
' opciones_select_lista : opcion_select'
reporte_bnf.append("<opciones_select_lista> ::= <opcion_select>")
t[0] = [t[1]] | [
"def",
"p_opciones_select_lista2",
"(",
"t",
")",
":",
"reporte_bnf",
".",
"append",
"(",
"\"<opciones_select_lista> ::= <opcion_select>\"",
")",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]"
] | [
1759,
0
] | [
1762,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DatabaseModel.query | (self, query_string) | return return_values | Método que nos permite realizar querys directamente a la
base de datos para obtener información directa. En este caso,
para usar selecciones que nos permitan obtener información
directa antes de introducir nueva (comprobaciones atómicas).
| Método que nos permite realizar querys directamente a la
base de datos para obtener información directa. En este caso,
para usar selecciones que nos permitan obtener información
directa antes de introducir nueva (comprobaciones atómicas).
| def query(self, query_string):
"""Método que nos permite realizar querys directamente a la
base de datos para obtener información directa. En este caso,
para usar selecciones que nos permitan obtener información
directa antes de introducir nueva (comprobaciones atómicas).
"""
return_values = []
try:
self.cursor = self.database.cursor()
for row in self.cursor.execute(query_string):
return_values.append(row)
self.database.commit()
except db.Error, e:
print "query : -> %s " % e.args
return return_values | [
"def",
"query",
"(",
"self",
",",
"query_string",
")",
":",
"return_values",
"=",
"[",
"]",
"try",
":",
"self",
".",
"cursor",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"for",
"row",
"in",
"self",
".",
"cursor",
".",
"execute",
"(",
"query_string",
")",
":",
"return_values",
".",
"append",
"(",
"row",
")",
"self",
".",
"database",
".",
"commit",
"(",
")",
"except",
"db",
".",
"Error",
",",
"e",
":",
"print",
"\"query : -> %s \"",
"%",
"e",
".",
"args",
"return",
"return_values"
] | [
209,
4
] | [
226,
28
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
download | (url, tries=DEFAULT_TRIES, retry_delay=RETRY_DELAY,
try_timeout=None, proxies=None, verify=True) | Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar (default: 1).
retry_delay (int o float): Tiempo a esperar, en segundos, entre cada
intento.
try_timeout (int o float): Tiempo máximo a esperar por intento.
proxies (dict): Proxies a utilizar. El diccionario debe contener los
valores 'http' y 'https', cada uno asociados a la URL del proxy
correspondiente.
Returns:
bytes: Contenido del archivo
| Descarga un archivo a través del protocolo HTTP, en uno o más intentos. | def download(url, tries=DEFAULT_TRIES, retry_delay=RETRY_DELAY,
try_timeout=None, proxies=None, verify=True):
"""Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar (default: 1).
retry_delay (int o float): Tiempo a esperar, en segundos, entre cada
intento.
try_timeout (int o float): Tiempo máximo a esperar por intento.
proxies (dict): Proxies a utilizar. El diccionario debe contener los
valores 'http' y 'https', cada uno asociados a la URL del proxy
correspondiente.
Returns:
bytes: Contenido del archivo
"""
# TODO: remover cuando los métodos que llaman a "download()" le pasen
# la configuración de descarga correctamente.
verify = False
for i in range(tries):
try:
response = requests.get(url, timeout=try_timeout, proxies=proxies,
verify=verify)
response.raise_for_status()
return response.content
except requests.exceptions.RequestException as e:
download_exception = e
if i < tries - 1:
time.sleep(retry_delay)
# raise DownloadException() from download_exception
raise download_exception | [
"def",
"download",
"(",
"url",
",",
"tries",
"=",
"DEFAULT_TRIES",
",",
"retry_delay",
"=",
"RETRY_DELAY",
",",
"try_timeout",
"=",
"None",
",",
"proxies",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"# TODO: remover cuando los métodos que llaman a \"download()\" le pasen",
"# la configuración de descarga correctamente.",
"verify",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"tries",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"try_timeout",
",",
"proxies",
"=",
"proxies",
",",
"verify",
"=",
"verify",
")",
"response",
".",
"raise_for_status",
"(",
")",
"return",
"response",
".",
"content",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"download_exception",
"=",
"e",
"if",
"i",
"<",
"tries",
"-",
"1",
":",
"time",
".",
"sleep",
"(",
"retry_delay",
")",
"# raise DownloadException() from download_exception",
"raise",
"download_exception"
] | [
12,
0
] | [
49,
28
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_argument_funciones_de_fechas | (t) | argument : funcionesdefechas | argument : funcionesdefechas | def p_argument_funciones_de_fechas(t):
'''argument : funcionesdefechas''' | [
"def",
"p_argument_funciones_de_fechas",
"(",
"t",
")",
":"
] | [
446,
0
] | [
447,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
EstimationResult.mean_angle | (self) | return angles.mean() | Media de los ángulos calculados en base a los vectores de velocidad estimados.
:return: media de los ángulos calculados.
| Media de los ángulos calculados en base a los vectores de velocidad estimados. | def mean_angle(self) -> float:
"""Media de los ángulos calculados en base a los vectores de velocidad estimados.
:return: media de los ángulos calculados.
"""
if len(self.angles) == 0:
return 0.
angles = np.array(self.angles)
return angles.mean() | [
"def",
"mean_angle",
"(",
"self",
")",
"->",
"float",
":",
"if",
"len",
"(",
"self",
".",
"angles",
")",
"==",
"0",
":",
"return",
"0.",
"angles",
"=",
"np",
".",
"array",
"(",
"self",
".",
"angles",
")",
"return",
"angles",
".",
"mean",
"(",
")"
] | [
60,
4
] | [
68,
28
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
TipoPrestacion.importar_desde_nomenclador | (cls) | Traer todos los elementos del nomenclador
No usamos NomencladorHPGD porque la base del nomenclador es muy mala
Tratamos aqui de crear una base nueva derivada de aquella pero que se pueda
completar y mejorar.
Como no hay clave única podrían duplicarse,
solo para su uso con bases limpias | Traer todos los elementos del nomenclador
No usamos NomencladorHPGD porque la base del nomenclador es muy mala
Tratamos aqui de crear una base nueva derivada de aquella pero que se pueda
completar y mejorar.
Como no hay clave única podrían duplicarse,
solo para su uso con bases limpias | def importar_desde_nomenclador(cls):
""" Traer todos los elementos del nomenclador
No usamos NomencladorHPGD porque la base del nomenclador es muy mala
Tratamos aqui de crear una base nueva derivada de aquella pero que se pueda
completar y mejorar.
Como no hay clave única podrían duplicarse,
solo para su uso con bases limpias"""
from nhpgd.nomenclador import Nomenclador
n = Nomenclador()
# actualziar a los últimos datos
n.download_csv()
for i, nom in n.tree.items():
nombre = nom['descripcion'][:29]
arancel = 0 if nom['arancel'] == '' else nom['arancel']
cls.objects.create(tipo=cls.TIPO_DESCONOCIDO,
nombre=nombre,
codigo=nom['codigo'],
descripcion=nom['descripcion'],
observaciones=nom['observaciones'],
arancel=arancel
) | [
"def",
"importar_desde_nomenclador",
"(",
"cls",
")",
":",
"from",
"nhpgd",
".",
"nomenclador",
"import",
"Nomenclador",
"n",
"=",
"Nomenclador",
"(",
")",
"# actualziar a los últimos datos",
"n",
".",
"download_csv",
"(",
")",
"for",
"i",
",",
"nom",
"in",
"n",
".",
"tree",
".",
"items",
"(",
")",
":",
"nombre",
"=",
"nom",
"[",
"'descripcion'",
"]",
"[",
":",
"29",
"]",
"arancel",
"=",
"0",
"if",
"nom",
"[",
"'arancel'",
"]",
"==",
"''",
"else",
"nom",
"[",
"'arancel'",
"]",
"cls",
".",
"objects",
".",
"create",
"(",
"tipo",
"=",
"cls",
".",
"TIPO_DESCONOCIDO",
",",
"nombre",
"=",
"nombre",
",",
"codigo",
"=",
"nom",
"[",
"'codigo'",
"]",
",",
"descripcion",
"=",
"nom",
"[",
"'descripcion'",
"]",
",",
"observaciones",
"=",
"nom",
"[",
"'observaciones'",
"]",
",",
"arancel",
"=",
"arancel",
")"
] | [
81,
4
] | [
101,
32
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_condiciones_recursivo | (t) | condiciones : condiciones comparacionlogica condicion | condiciones : condiciones comparacionlogica condicion | def p_condiciones_recursivo(t):
'condiciones : condiciones comparacionlogica condicion'
selectID = False
if 'selectID' in t[1] or 'selectID' in t[3]:
selectID = True
text = t[1]['text'] + ' ' + t[2] + ' ' + t[3]['text']
c3 = t[1]['c3d']
c3 += t[3]['c3d']
c3 += ' ' + tempos.newTemp() + ' = ' + t[1]['tflag'] + ' ' + t[2] + ' ' + t[3]['tflag'] + '\n'
c3d = t[1]['select'] + t[3]['select']
grafo.newnode('CONDICIONES')
grafo.newchildrenF(grafo.index, t[1]['graph'])
grafo.newchildrenF(grafo.index, t[2]['graph'])
grafo.newchildrenF(grafo.index, t[3]['graph'])
reporte = "<condiciones> ::= <condiciones> <comparacionlogica> <condicion>\n" + t[1]['reporte'] + t[2]['reporte'] + t[3]['reporte']
t[0] = {'text': text, 'c3d' : c3, 'tflag' : 't'+str(tempos.index), 'select': c3d, 'graph' : grafo.index, 'reporte': reporte} | [
"def",
"p_condiciones_recursivo",
"(",
"t",
")",
":",
"selectID",
"=",
"False",
"if",
"'selectID'",
"in",
"t",
"[",
"1",
"]",
"or",
"'selectID'",
"in",
"t",
"[",
"3",
"]",
":",
"selectID",
"=",
"True",
"text",
"=",
"t",
"[",
"1",
"]",
"[",
"'text'",
"]",
"+",
"' '",
"+",
"t",
"[",
"2",
"]",
"+",
"' '",
"+",
"t",
"[",
"3",
"]",
"[",
"'text'",
"]",
"c3",
"=",
"t",
"[",
"1",
"]",
"[",
"'c3d'",
"]",
"c3",
"+=",
"t",
"[",
"3",
"]",
"[",
"'c3d'",
"]",
"c3",
"+=",
"' '",
"+",
"tempos",
".",
"newTemp",
"(",
")",
"+",
"' = '",
"+",
"t",
"[",
"1",
"]",
"[",
"'tflag'",
"]",
"+",
"' '",
"+",
"t",
"[",
"2",
"]",
"+",
"' '",
"+",
"t",
"[",
"3",
"]",
"[",
"'tflag'",
"]",
"+",
"'\\n'",
"c3d",
"=",
"t",
"[",
"1",
"]",
"[",
"'select'",
"]",
"+",
"t",
"[",
"3",
"]",
"[",
"'select'",
"]",
"grafo",
".",
"newnode",
"(",
"'CONDICIONES'",
")",
"grafo",
".",
"newchildrenF",
"(",
"grafo",
".",
"index",
",",
"t",
"[",
"1",
"]",
"[",
"'graph'",
"]",
")",
"grafo",
".",
"newchildrenF",
"(",
"grafo",
".",
"index",
",",
"t",
"[",
"2",
"]",
"[",
"'graph'",
"]",
")",
"grafo",
".",
"newchildrenF",
"(",
"grafo",
".",
"index",
",",
"t",
"[",
"3",
"]",
"[",
"'graph'",
"]",
")",
"reporte",
"=",
"\"<condiciones> ::= <condiciones> <comparacionlogica> <condicion>\\n\"",
"+",
"t",
"[",
"1",
"]",
"[",
"'reporte'",
"]",
"+",
"t",
"[",
"2",
"]",
"[",
"'reporte'",
"]",
"+",
"t",
"[",
"3",
"]",
"[",
"'reporte'",
"]",
"t",
"[",
"0",
"]",
"=",
"{",
"'text'",
":",
"text",
",",
"'c3d'",
":",
"c3",
",",
"'tflag'",
":",
"'t'",
"+",
"str",
"(",
"tempos",
".",
"index",
")",
",",
"'select'",
":",
"c3d",
",",
"'graph'",
":",
"grafo",
".",
"index",
",",
"'reporte'",
":",
"reporte",
"}"
] | [
1880,
0
] | [
1898,
129
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
parse_path | (filename: str) | return parsed | Convierte un nombre de archivo (sin extensión) en un
nombre de servicio válido.
Raises:
ValueError: En caso de que el nombre sea inválido
| Convierte un nombre de archivo (sin extensión) en un
nombre de servicio válido. | def parse_path(filename: str) -> str:
"""Convierte un nombre de archivo (sin extensión) en un
nombre de servicio válido.
Raises:
ValueError: En caso de que el nombre sea inválido
"""
filename = remove_badchars.remove(filename, "/")
parsed = filename
try:
parsed = filename.split("/", 1)[1]
except IndexError:
raise ValueError(_("Nombre inválido"))
if not (parsed):
parsed = filename
return parsed | [
"def",
"parse_path",
"(",
"filename",
":",
"str",
")",
"->",
"str",
":",
"filename",
"=",
"remove_badchars",
".",
"remove",
"(",
"filename",
",",
"\"/\"",
")",
"parsed",
"=",
"filename",
"try",
":",
"parsed",
"=",
"filename",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"[",
"1",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"\"Nombre inválido\")",
")",
"",
"if",
"not",
"(",
"parsed",
")",
":",
"parsed",
"=",
"filename",
"return",
"parsed"
] | [
69,
0
] | [
89,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
PlaceDbWriter.decompose_occupancy_data | (self, occupancy_levels) | return occupancy | Función auxiliar para la construcción del objeto de ocupación por horas para registrarlo en la base de datos.
| Función auxiliar para la construcción del objeto de ocupación por horas para registrarlo en la base de datos.
| def decompose_occupancy_data(self, occupancy_levels):
"""Función auxiliar para la construcción del objeto de ocupación por horas para registrarlo en la base de datos.
"""
occupancy = {
"lunes": {},
"martes": {},
"miercoles": {},
"jueves": {},
"viernes": {},
"sabado": {},
"domingo": {}
}
for week_day, occupancy_levels in occupancy_levels.items():
if occupancy_levels:
for occupancy_level in occupancy_levels:
if occupancy_level:
try:
base = occupancy_level.split(":")[1:]
occupancy[week_day].update({
base[1].split(")")[0].strip(): float(base[0].split("\xa0%")[0])
})
except:
pass
return occupancy | [
"def",
"decompose_occupancy_data",
"(",
"self",
",",
"occupancy_levels",
")",
":",
"occupancy",
"=",
"{",
"\"lunes\"",
":",
"{",
"}",
",",
"\"martes\"",
":",
"{",
"}",
",",
"\"miercoles\"",
":",
"{",
"}",
",",
"\"jueves\"",
":",
"{",
"}",
",",
"\"viernes\"",
":",
"{",
"}",
",",
"\"sabado\"",
":",
"{",
"}",
",",
"\"domingo\"",
":",
"{",
"}",
"}",
"for",
"week_day",
",",
"occupancy_levels",
"in",
"occupancy_levels",
".",
"items",
"(",
")",
":",
"if",
"occupancy_levels",
":",
"for",
"occupancy_level",
"in",
"occupancy_levels",
":",
"if",
"occupancy_level",
":",
"try",
":",
"base",
"=",
"occupancy_level",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"occupancy",
"[",
"week_day",
"]",
".",
"update",
"(",
"{",
"base",
"[",
"1",
"]",
".",
"split",
"(",
"\")\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
":",
"float",
"(",
"base",
"[",
"0",
"]",
".",
"split",
"(",
"\"\\xa0%\"",
")",
"[",
"0",
"]",
")",
"}",
")",
"except",
":",
"pass",
"return",
"occupancy"
] | [
149,
4
] | [
172,
24
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
AccountMove._onchange_tax_date | (self) | Si cambia la fecha o cambiamos el refund asociado tenemos que recalcular los impuestos | Si cambia la fecha o cambiamos el refund asociado tenemos que recalcular los impuestos | def _onchange_tax_date(self):
""" Si cambia la fecha o cambiamos el refund asociado tenemos que recalcular los impuestos """
self._onchange_invoice_date()
if self.invoice_line_ids.mapped('tax_ids').filtered(
lambda x: x.amount_type == 'partner_tax'):
# si no recomputamos no se guarda el cambio en las lineas
self.line_ids._onchange_price_subtotal()
self._recompute_dynamic_lines(recompute_all_taxes=True) | [
"def",
"_onchange_tax_date",
"(",
"self",
")",
":",
"self",
".",
"_onchange_invoice_date",
"(",
")",
"if",
"self",
".",
"invoice_line_ids",
".",
"mapped",
"(",
"'tax_ids'",
")",
".",
"filtered",
"(",
"lambda",
"x",
":",
"x",
".",
"amount_type",
"==",
"'partner_tax'",
")",
":",
"# si no recomputamos no se guarda el cambio en las lineas",
"self",
".",
"line_ids",
".",
"_onchange_price_subtotal",
"(",
")",
"self",
".",
"_recompute_dynamic_lines",
"(",
"recompute_all_taxes",
"=",
"True",
")"
] | [
31,
4
] | [
38,
67
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
valuesBelow | (data, limit) | return res | Obtiene una lista con los valores menores al límite.
Args:
data (list): Lista con todos los datos.
limit (same as list data type): Valor sobre el cual se buscan
los datos menores.
Returns:
list: Valores en _data_ menores a _limit_
| Obtiene una lista con los valores menores al límite. | def valuesBelow(data, limit):
"""Obtiene una lista con los valores menores al límite.
Args:
data (list): Lista con todos los datos.
limit (same as list data type): Valor sobre el cual se buscan
los datos menores.
Returns:
list: Valores en _data_ menores a _limit_
"""
res = list()
for i in data:
if i < limit:
res.append(i)
return res | [
"def",
"valuesBelow",
"(",
"data",
",",
"limit",
")",
":",
"res",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"data",
":",
"if",
"i",
"<",
"limit",
":",
"res",
".",
"append",
"(",
"i",
")",
"return",
"res"
] | [
129,
0
] | [
146,
14
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_opciones_sobrenombre | (t) | opciones_sobrenombres : opciones_sobrenombres COMA opcion_sobrenombre | opciones_sobrenombres : opciones_sobrenombres COMA opcion_sobrenombre | def p_opciones_sobrenombre(t):
'''opciones_sobrenombres : opciones_sobrenombres COMA opcion_sobrenombre '''
reporte_bnf.append("<opciones_sobrenombres> ::= <opciones_sobrenombres> COMA <opcion_sobrenombre>")
t[1].append(t[3])
t[0] = t[1] | [
"def",
"p_opciones_sobrenombre",
"(",
"t",
")",
":",
"reporte_bnf",
".",
"append",
"(",
"\"<opciones_sobrenombres> ::= <opciones_sobrenombres> COMA <opcion_sobrenombre>\"",
")",
"t",
"[",
"1",
"]",
".",
"append",
"(",
"t",
"[",
"3",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
1774,
0
] | [
1778,
15
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Chimp.content | (self, id, data) | Este método se utiliza para cargar el contenido que tendra la campaña, es decir, el HTML
recibe como parametro el id de la campaña a la que vamos a agregar el contenido y por supuesto
el contenido que se agregara(string) | Este método se utiliza para cargar el contenido que tendra la campaña, es decir, el HTML
recibe como parametro el id de la campaña a la que vamos a agregar el contenido y por supuesto
el contenido que se agregara(string) | def content(self, id, data):
"""Este método se utiliza para cargar el contenido que tendra la campaña, es decir, el HTML
recibe como parametro el id de la campaña a la que vamos a agregar el contenido y por supuesto
el contenido que se agregara(string)"""
self.client.campaigns.content.update(campaign_id=id, data=data) | [
"def",
"content",
"(",
"self",
",",
"id",
",",
"data",
")",
":",
"self",
".",
"client",
".",
"campaigns",
".",
"content",
".",
"update",
"(",
"campaign_id",
"=",
"id",
",",
"data",
"=",
"data",
")"
] | [
155,
4
] | [
159,
71
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
BioPortalService.annotation_parse | (annotation) | return {
"ontologyLabel": re.sub(r".*\/", "", ontology_link),
"prefLabel": annotated_class["prefLabel"],
"id": annotated_class["@id"],
"class": annotated_class["links"]["ui"],
"ontology": ontology_link,
"selector": annotation["annotations"],
} | realiza el parseo de las anotaciones rescatadas desde la api de bioportal a un formato comun para las aplicaciones\n
{\n\t
'ontologyLabel':str,// label de la ontologia
'prefLabel':str, // perfLabel
'id':str, // identificador de la ontologia
'class':str, //link de la clase
'ontology':str, //link de la ontologia
'selector': list, //datos del selector
\n\t}
| realiza el parseo de las anotaciones rescatadas desde la api de bioportal a un formato comun para las aplicaciones\n
{\n\t
'ontologyLabel':str,// label de la ontologia
'prefLabel':str, // perfLabel
'id':str, // identificador de la ontologia
'class':str, //link de la clase
'ontology':str, //link de la ontologia
'selector': list, //datos del selector
\n\t}
| def annotation_parse(annotation):
"""realiza el parseo de las anotaciones rescatadas desde la api de bioportal a un formato comun para las aplicaciones\n
{\n\t
'ontologyLabel':str,// label de la ontologia
'prefLabel':str, // perfLabel
'id':str, // identificador de la ontologia
'class':str, //link de la clase
'ontology':str, //link de la ontologia
'selector': list, //datos del selector
\n\t}
"""
annotated_class = annotation["annotatedClass"]
ontology_link = annotated_class["links"]["ontology"]
return {
"ontologyLabel": re.sub(r".*\/", "", ontology_link),
"prefLabel": annotated_class["prefLabel"],
"id": annotated_class["@id"],
"class": annotated_class["links"]["ui"],
"ontology": ontology_link,
"selector": annotation["annotations"],
} | [
"def",
"annotation_parse",
"(",
"annotation",
")",
":",
"annotated_class",
"=",
"annotation",
"[",
"\"annotatedClass\"",
"]",
"ontology_link",
"=",
"annotated_class",
"[",
"\"links\"",
"]",
"[",
"\"ontology\"",
"]",
"return",
"{",
"\"ontologyLabel\"",
":",
"re",
".",
"sub",
"(",
"r\".*\\/\"",
",",
"\"\"",
",",
"ontology_link",
")",
",",
"\"prefLabel\"",
":",
"annotated_class",
"[",
"\"prefLabel\"",
"]",
",",
"\"id\"",
":",
"annotated_class",
"[",
"\"@id\"",
"]",
",",
"\"class\"",
":",
"annotated_class",
"[",
"\"links\"",
"]",
"[",
"\"ui\"",
"]",
",",
"\"ontology\"",
":",
"ontology_link",
",",
"\"selector\"",
":",
"annotation",
"[",
"\"annotations\"",
"]",
",",
"}"
] | [
20,
4
] | [
40,
9
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
TrackedObjects.purge_objects | (self, ids: List[int]) | Elimina los objetos indicados y restablece los ids para que mantengan un orden
secuencial.
:param ids: identificadores de los objetos seguidos a eliminar.
:return: None.
| Elimina los objetos indicados y restablece los ids para que mantengan un orden
secuencial. | def purge_objects(self, ids: List[int]) -> None:
"""Elimina los objetos indicados y restablece los ids para que mantengan un orden
secuencial.
:param ids: identificadores de los objetos seguidos a eliminar.
:return: None.
"""
# Se elimina el objeto, porque si se hace por índice daría error en el índice + 1, ya que
# ese estaría uno por debajo.
objects_to_remove = [self._tracked_objects[id_] for id_ in ids]
for object_ in objects_to_remove:
# Eliminar el objeto de la estructura
self._tracked_objects.remove(object_)
# Reajustar los índices.
for tracked_object in self._tracked_objects[object_.id:]:
tracked_object.id -= 1 | [
"def",
"purge_objects",
"(",
"self",
",",
"ids",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"# Se elimina el objeto, porque si se hace por índice daría error en el índice + 1, ya que",
"# ese estaría uno por debajo.",
"objects_to_remove",
"=",
"[",
"self",
".",
"_tracked_objects",
"[",
"id_",
"]",
"for",
"id_",
"in",
"ids",
"]",
"for",
"object_",
"in",
"objects_to_remove",
":",
"# Eliminar el objeto de la estructura",
"self",
".",
"_tracked_objects",
".",
"remove",
"(",
"object_",
")",
"# Reajustar los índices.",
"for",
"tracked_object",
"in",
"self",
".",
"_tracked_objects",
"[",
"object_",
".",
"id",
":",
"]",
":",
"tracked_object",
".",
"id",
"-=",
"1"
] | [
320,
4
] | [
335,
38
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DataCleaner.save | (self, output_path, geometry_name='geojson',
geometry_crs='epsg:4326') | Guarda los datos en un nuevo CSV con formato estándar.
El CSV se guarda codificado en UTF-8, separado con "," y usando '"'
comillas dobles como caracter de enclosing. | Guarda los datos en un nuevo CSV con formato estándar. | def save(self, output_path, geometry_name='geojson',
geometry_crs='epsg:4326'):
"""Guarda los datos en un nuevo CSV con formato estándar.
El CSV se guarda codificado en UTF-8, separado con "," y usando '"'
comillas dobles como caracter de enclosing."""
if isinstance(self.df, gpd.GeoDataFrame):
# Convierte la proyección, si puede.
if geometry_crs:
try:
self.df.crs = self.source_crs
self.df = self.df.to_crs({'init': geometry_crs})
except Exception as e:
print(e)
print("Se procede sin re-proyectar las coordenadas.")
if output_path.endswith('.csv'):
self._set_json_geometry(geometry_name)
# Guarda el archivo en formato GeoJSON o KML.
if output_path.endswith('json'): # Acepta .json y .geojson.
self.df.to_file(output_path, driver='GeoJSON')
return
elif output_path.endswith('kml'):
self._save_to_kml(output_path)
return
self.df.set_index(self.df.columns[0]).to_csv(
output_path, encoding=self.OUTPUT_ENCODING,
sep=self.OUTPUT_SEPARATOR,
quotechar=self.OUTPUT_QUOTECHAR) | [
"def",
"save",
"(",
"self",
",",
"output_path",
",",
"geometry_name",
"=",
"'geojson'",
",",
"geometry_crs",
"=",
"'epsg:4326'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"df",
",",
"gpd",
".",
"GeoDataFrame",
")",
":",
"# Convierte la proyección, si puede.",
"if",
"geometry_crs",
":",
"try",
":",
"self",
".",
"df",
".",
"crs",
"=",
"self",
".",
"source_crs",
"self",
".",
"df",
"=",
"self",
".",
"df",
".",
"to_crs",
"(",
"{",
"'init'",
":",
"geometry_crs",
"}",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"print",
"(",
"\"Se procede sin re-proyectar las coordenadas.\"",
")",
"if",
"output_path",
".",
"endswith",
"(",
"'.csv'",
")",
":",
"self",
".",
"_set_json_geometry",
"(",
"geometry_name",
")",
"# Guarda el archivo en formato GeoJSON o KML.",
"if",
"output_path",
".",
"endswith",
"(",
"'json'",
")",
":",
"# Acepta .json y .geojson.",
"self",
".",
"df",
".",
"to_file",
"(",
"output_path",
",",
"driver",
"=",
"'GeoJSON'",
")",
"return",
"elif",
"output_path",
".",
"endswith",
"(",
"'kml'",
")",
":",
"self",
".",
"_save_to_kml",
"(",
"output_path",
")",
"return",
"self",
".",
"df",
".",
"set_index",
"(",
"self",
".",
"df",
".",
"columns",
"[",
"0",
"]",
")",
".",
"to_csv",
"(",
"output_path",
",",
"encoding",
"=",
"self",
".",
"OUTPUT_ENCODING",
",",
"sep",
"=",
"self",
".",
"OUTPUT_SEPARATOR",
",",
"quotechar",
"=",
"self",
".",
"OUTPUT_QUOTECHAR",
")"
] | [
242,
4
] | [
272,
44
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
heapsort | (lst) | Ordena usando la libreria <heapq> incluida en python | Ordena usando la libreria <heapq> incluida en python | def heapsort(lst):
"""Ordena usando la libreria <heapq> incluida en python"""
heap = list(lst)
# Hace la lista una pila
heapq.heapify(heap)
#Los elementos salen de la pila en orden ascendente
for i in xrange(len(lst)):
lst[i] = heapq.heappop(heap) | [
"def",
"heapsort",
"(",
"lst",
")",
":",
"heap",
"=",
"list",
"(",
"lst",
")",
"# Hace la lista una pila",
"heapq",
".",
"heapify",
"(",
"heap",
")",
"#Los elementos salen de la pila en orden ascendente",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"lst",
")",
")",
":",
"lst",
"[",
"i",
"]",
"=",
"heapq",
".",
"heappop",
"(",
"heap",
")"
] | [
11,
0
] | [
18,
36
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Simulador.altitud | (self) | return uniform(10666, 10670) | Altitud del avión en metros. | Altitud del avión en metros. | def altitud(self):
"""Altitud del avión en metros."""
return uniform(10666, 10670) | [
"def",
"altitud",
"(",
"self",
")",
":",
"return",
"uniform",
"(",
"10666",
",",
"10670",
")"
] | [
111,
4
] | [
113,
36
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
DominioAGTSP.mutar | (self, sol) | return super().vecino(sol) | Produce una nueva solución aplicando un ligero cambio a la solución dada por
parámetro.
Entradas:
sol (estructura de datos)
La solución a mutar.
Salidas:
(estructura de datos) Una nueva solución que refleja un ligero cambio con respecto
a la solución dada por parámetro
| Produce una nueva solución aplicando un ligero cambio a la solución dada por
parámetro.
Entradas:
sol (estructura de datos)
La solución a mutar.
Salidas:
(estructura de datos) Una nueva solución que refleja un ligero cambio con respecto
a la solución dada por parámetro
| def mutar(self, sol):
"""Produce una nueva solución aplicando un ligero cambio a la solución dada por
parámetro.
Entradas:
sol (estructura de datos)
La solución a mutar.
Salidas:
(estructura de datos) Una nueva solución que refleja un ligero cambio con respecto
a la solución dada por parámetro
"""
return super().vecino(sol) | [
"def",
"mutar",
"(",
"self",
",",
"sol",
")",
":",
"return",
"super",
"(",
")",
".",
"vecino",
"(",
"sol",
")"
] | [
117,
4
] | [
129,
34
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_lista_condicion_salida2 | (t) | condiciones : NOT condiciones | condiciones : NOT condiciones | def p_lista_condicion_salida2(t):
'condiciones : NOT condiciones'
gramatica = '<condiciones> ::= NOT <condiciones>\n'
t[0] = Nodo('OPLOG', 'NOT', [t[2]], t.lexer.lineno, 0, gramatica) | [
"def",
"p_lista_condicion_salida2",
"(",
"t",
")",
":",
"gramatica",
"=",
"'<condiciones> ::= NOT <condiciones>\\n'",
"t",
"[",
"0",
"]",
"=",
"Nodo",
"(",
"'OPLOG'",
",",
"'NOT'",
",",
"[",
"t",
"[",
"2",
"]",
"]",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"0",
",",
"gramatica",
")"
] | [
316,
0
] | [
319,
69
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
matingPool | (matrizIPOP, NPOP, NGOOD) | return matrizNGOOD | Imprimimos la informacion de la matriz generada aleatoriamente desordenada | Imprimimos la informacion de la matriz generada aleatoriamente desordenada | def matingPool(matrizIPOP, NPOP, NGOOD):
# Iniciar iteracion
# Generamos su valor en decimal
matrizIPOPDecimal = convertirMatrizBinariaAListaEntera(matrizIPOP)
# Generamos los costos para cada individuo
listaDeCostos = obtenerListaCostoDeX(matrizIPOPDecimal)
# Ordenamos los costos de menor a mayor, mas adelante utilizaremos esto para ordenar la matriz
listaDeCostosOrdenada = ordenarCostesDeMenorAMayor(obtenerListaCostoDeX(matrizIPOPDecimal))
"""Imprimimos la informacion de la matriz generada aleatoriamente desordenada"""
print("Valores Iniciales")
print("Matriz IPOP", "\t\t ", "Valores en Decimal", "Valores de coste")
for i in matrizIPOP:
print(i, "\t", convertirListaBinariaAEntero(i), "\t\t\t", funcionCoste(convertirListaBinariaAEntero(i)))
print("\n")
"""Ordenamos la matriz de menor a mayo de acuerdo a los costos"""
matrizIPOPordenada = listasOrdenadas(matrizIPOP, listaDeCostos, listaDeCostosOrdenada)
"""Imprimimos la informacion de la matriz Ordenada"""
print("Valores ordenados de menor a mayor de acuerdo al valor de coste")
print("Matriz IPOP", "\t\t ", "Valores en Decimal", "Valores de coste")
for i in matrizIPOPordenada:
print(i, "\t", convertirListaBinariaAEntero(i), "\t\t\t", funcionCoste(convertirListaBinariaAEntero(i)))
print("\n")
"""Imprimimos NPOP y obtenemos la matriz NPOP"""
print("NPOP: ", NPOP)
matrizNPOP = matrizIPOPordenada[0:NPOP]
print(matrizNPOP)
print("\n")
"""Imprimimos NGOOD y obtenemos la matriz NGOOD"""
print("NGOOD: ", NGOOD)
matrizNGOOD = matrizIPOPordenada[0:NGOOD]
print(matrizNGOOD)
print("\n")
return matrizNGOOD | [
"def",
"matingPool",
"(",
"matrizIPOP",
",",
"NPOP",
",",
"NGOOD",
")",
":",
"# Iniciar iteracion",
"# Generamos su valor en decimal",
"matrizIPOPDecimal",
"=",
"convertirMatrizBinariaAListaEntera",
"(",
"matrizIPOP",
")",
"# Generamos los costos para cada individuo",
"listaDeCostos",
"=",
"obtenerListaCostoDeX",
"(",
"matrizIPOPDecimal",
")",
"# Ordenamos los costos de menor a mayor, mas adelante utilizaremos esto para ordenar la matriz",
"listaDeCostosOrdenada",
"=",
"ordenarCostesDeMenorAMayor",
"(",
"obtenerListaCostoDeX",
"(",
"matrizIPOPDecimal",
")",
")",
"print",
"(",
"\"Valores Iniciales\"",
")",
"print",
"(",
"\"Matriz IPOP\"",
",",
"\"\\t\\t \"",
",",
"\"Valores en Decimal\"",
",",
"\"Valores de coste\"",
")",
"for",
"i",
"in",
"matrizIPOP",
":",
"print",
"(",
"i",
",",
"\"\\t\"",
",",
"convertirListaBinariaAEntero",
"(",
"i",
")",
",",
"\"\\t\\t\\t\"",
",",
"funcionCoste",
"(",
"convertirListaBinariaAEntero",
"(",
"i",
")",
")",
")",
"print",
"(",
"\"\\n\"",
")",
"\"\"\"Ordenamos la matriz de menor a mayo de acuerdo a los costos\"\"\"",
"matrizIPOPordenada",
"=",
"listasOrdenadas",
"(",
"matrizIPOP",
",",
"listaDeCostos",
",",
"listaDeCostosOrdenada",
")",
"\"\"\"Imprimimos la informacion de la matriz Ordenada\"\"\"",
"print",
"(",
"\"Valores ordenados de menor a mayor de acuerdo al valor de coste\"",
")",
"print",
"(",
"\"Matriz IPOP\"",
",",
"\"\\t\\t \"",
",",
"\"Valores en Decimal\"",
",",
"\"Valores de coste\"",
")",
"for",
"i",
"in",
"matrizIPOPordenada",
":",
"print",
"(",
"i",
",",
"\"\\t\"",
",",
"convertirListaBinariaAEntero",
"(",
"i",
")",
",",
"\"\\t\\t\\t\"",
",",
"funcionCoste",
"(",
"convertirListaBinariaAEntero",
"(",
"i",
")",
")",
")",
"print",
"(",
"\"\\n\"",
")",
"\"\"\"Imprimimos NPOP y obtenemos la matriz NPOP\"\"\"",
"print",
"(",
"\"NPOP: \"",
",",
"NPOP",
")",
"matrizNPOP",
"=",
"matrizIPOPordenada",
"[",
"0",
":",
"NPOP",
"]",
"print",
"(",
"matrizNPOP",
")",
"print",
"(",
"\"\\n\"",
")",
"\"\"\"Imprimimos NGOOD y obtenemos la matriz NGOOD\"\"\"",
"print",
"(",
"\"NGOOD: \"",
",",
"NGOOD",
")",
"matrizNGOOD",
"=",
"matrizIPOPordenada",
"[",
"0",
":",
"NGOOD",
"]",
"print",
"(",
"matrizNGOOD",
")",
"print",
"(",
"\"\\n\"",
")",
"return",
"matrizNGOOD"
] | [
34,
0
] | [
72,
22
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_valselect_9 | (t) | valselect : COUNT PARIZQ cualquieridentificador PARDER alias | valselect : COUNT PARIZQ cualquieridentificador PARDER alias | def p_valselect_9(t):
'valselect : COUNT PARIZQ cualquieridentificador PARDER alias'
t[0] = getValSelect(t, 'count_val') | [
"def",
"p_valselect_9",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getValSelect",
"(",
"t",
",",
"'count_val'",
")"
] | [
836,
0
] | [
838,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
suma_serie | (n: int) | Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n.
:param n: número de elementos de la serie
:n type: int
:return: suma de los elementos de la serie
:rtype: int
| Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n.
:param n: número de elementos de la serie
:n type: int
:return: suma de los elementos de la serie
:rtype: int
| def suma_serie(n: int) -> int:
"""Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n.
:param n: número de elementos de la serie
:n type: int
:return: suma de los elementos de la serie
:rtype: int
"""
if n == 1:
return 6
else:
return (n ** 3 + 5) + suma_serie(n - 1) | [
"def",
"suma_serie",
"(",
"n",
":",
"int",
")",
"->",
"int",
":",
"if",
"n",
"==",
"1",
":",
"return",
"6",
"else",
":",
"return",
"(",
"n",
"**",
"3",
"+",
"5",
")",
"+",
"suma_serie",
"(",
"n",
"-",
"1",
")"
] | [
24,
0
] | [
35,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Estante.__del__ | (self) | Destructor: Cierra el archivo shelve. | Destructor: Cierra el archivo shelve. | def __del__(self):
"""Destructor: Cierra el archivo shelve."""
try:
self.dic.close()
except AttributeError:
pass | [
"def",
"__del__",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"dic",
".",
"close",
"(",
")",
"except",
"AttributeError",
":",
"pass"
] | [
52,
4
] | [
57,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
eliminar_usuario | (user_id) | return redirect(url_for(request.args.get("ruta", default="home", type=str))) | Elimina un usuario por su id y redirecciona a la vista dada. | Elimina un usuario por su id y redirecciona a la vista dada. | def eliminar_usuario(user_id):
"""Elimina un usuario por su id y redirecciona a la vista dada."""
perfil_usuario = Usuario.query.filter(Usuario.usuario == user_id)
perfil_usuario.delete()
database.session.commit()
return redirect(url_for(request.args.get("ruta", default="home", type=str))) | [
"def",
"eliminar_usuario",
"(",
"user_id",
")",
":",
"perfil_usuario",
"=",
"Usuario",
".",
"query",
".",
"filter",
"(",
"Usuario",
".",
"usuario",
"==",
"user_id",
")",
"perfil_usuario",
".",
"delete",
"(",
")",
"database",
".",
"session",
".",
"commit",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"request",
".",
"args",
".",
"get",
"(",
"\"ruta\"",
",",
"default",
"=",
"\"home\"",
",",
"type",
"=",
"str",
")",
")",
")"
] | [
850,
0
] | [
855,
80
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_instrif | (t) | instrif : IF condiciones THEN instrlistabloque END IF PTCOMA | instrif : IF condiciones THEN instrlistabloque END IF PTCOMA | def p_instrif(t):
'instrif : IF condiciones THEN instrlistabloque END IF PTCOMA'
t[0] = getinstrif(t) | [
"def",
"p_instrif",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getinstrif",
"(",
"t",
")"
] | [
808,
0
] | [
810,
24
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Atajo.run_test | (self) | Correr el test con minitwill y almacenar
el resultado | Correr el test con minitwill y almacenar
el resultado | def run_test(self):
'''Correr el test con minitwill y almacenar
el resultado'''
self.status = minitwill(self.url, self.test)
self.ultimo = datetime.datetime.now()
self.save() | [
"def",
"run_test",
"(",
"self",
")",
":",
"self",
".",
"status",
"=",
"minitwill",
"(",
"self",
".",
"url",
",",
"self",
".",
"test",
")",
"self",
".",
"ultimo",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"save",
"(",
")"
] | [
181,
4
] | [
186,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_ins_1 | (t) | opcion_select_tm : varias_funciones | opcion_select_tm : varias_funciones | def p_ins_1(t):
'opcion_select_tm : varias_funciones'
reporte_bnf.append("<opcion_select_tm> ::= <varias_funciones>")
t[0] = Create_select_general(OPCIONES_SELECT.SELECT,None,None,None,None,t[1]) | [
"def",
"p_ins_1",
"(",
"t",
")",
":",
"reporte_bnf",
".",
"append",
"(",
"\"<opcion_select_tm> ::= <varias_funciones>\"",
")",
"t",
"[",
"0",
"]",
"=",
"Create_select_general",
"(",
"OPCIONES_SELECT",
".",
"SELECT",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"t",
"[",
"1",
"]",
")"
] | [
1817,
0
] | [
1820,
81
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_instruccionesPL_pl | (t) | instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_get_error
| instru_return
| operacion_logica
| asignacion | instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_get_error
| instru_return
| operacion_logica
| asignacion | def p_instruccionesPL_pl(t):
'''instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_get_error
| instru_return
| operacion_logica
| asignacion'''
instru = grammer.nodoGramatical('instruccionesPL_pl')
if t[1] == 'sentencia_if':
instru.agregarDetalle('sentencia_if')
elif t[1] == 'sentencia_case':
instru.agregarDetalle('sentencia_case')
elif t[1] == 'sentencia_loop':
instru.agregarDetalle('sentencia_loop')
elif t[1] == 'instru_exit':
instru.agregarDetalle('instru_exit')
elif t[1] == 'instru_get_error':
instru.agregarDetalle('instru_get_error')
elif t[1] == 'instru_return':
instru.agregarDetalle('instru_return')
elif t[1] == 'operacion_logica':
instru.agregarDetalle('operacion_logica')
elif t[1] == 'asignacion':
instru.agregarDetalle('asignacion')
listGrammer.insert(0,instru) | [
"def",
"p_instruccionesPL_pl",
"(",
"t",
")",
":",
"instru",
"=",
"grammer",
".",
"nodoGramatical",
"(",
"'instruccionesPL_pl'",
")",
"if",
"t",
"[",
"1",
"]",
"==",
"'sentencia_if'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'sentencia_if'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'sentencia_case'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'sentencia_case'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'sentencia_loop'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'sentencia_loop'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'instru_exit'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'instru_exit'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'instru_get_error'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'instru_get_error'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'instru_return'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'instru_return'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'operacion_logica'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'operacion_logica'",
")",
"elif",
"t",
"[",
"1",
"]",
"==",
"'asignacion'",
":",
"instru",
".",
"agregarDetalle",
"(",
"'asignacion'",
")",
"listGrammer",
".",
"insert",
"(",
"0",
",",
"instru",
")"
] | [
697,
0
] | [
724,
32
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Battery.describe_battery | (self) | Imprima una declaración que describa el tamaño de la batería. | Imprima una declaración que describa el tamaño de la batería. | def describe_battery(self):
"""Imprima una declaración que describa el tamaño de la batería."""
print("Este automóvil tiene una " + str(self.battery_size) + "-kWh battery.") | [
"def",
"describe_battery",
"(",
"self",
")",
":",
"print",
"(",
"\"Este automóvil tiene una \" ",
" ",
"tr(",
"s",
"elf.",
"b",
"attery_size)",
" ",
" ",
"-kWh battery.\")",
""
] | [
40,
4
] | [
42,
86
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
TrackingVideo.generate_video | (self, file_output: str, verbose: bool = False) | Genera la secuencia de vídeo y la guarda en un archivo.
:param file_output: archivo de salida.
:param verbose: indica si se quiere mostrar la barra de progreso o no.
:return: None.
| Genera la secuencia de vídeo y la guarda en un archivo. | def generate_video(self, file_output: str, verbose: bool = False) -> None:
"""Genera la secuencia de vídeo y la guarda en un archivo.
:param file_output: archivo de salida.
:param verbose: indica si se quiere mostrar la barra de progreso o no.
:return: None.
"""
output_stream = StreamSequenceWriter(file_output, self.input_sequence.properties())
t = tqdm(total=len(self.input_sequence), desc='Generating video', disable=not verbose)
for frame in self:
output_stream.write(frame)
t.update() | [
"def",
"generate_video",
"(",
"self",
",",
"file_output",
":",
"str",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"output_stream",
"=",
"StreamSequenceWriter",
"(",
"file_output",
",",
"self",
".",
"input_sequence",
".",
"properties",
"(",
")",
")",
"t",
"=",
"tqdm",
"(",
"total",
"=",
"len",
"(",
"self",
".",
"input_sequence",
")",
",",
"desc",
"=",
"'Generating video'",
",",
"disable",
"=",
"not",
"verbose",
")",
"for",
"frame",
"in",
"self",
":",
"output_stream",
".",
"write",
"(",
"frame",
")",
"t",
".",
"update",
"(",
")"
] | [
374,
4
] | [
385,
22
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_fun_sis | (t) | funciones_sis : funciones_sis COMA fsis aliascol | funciones_sis : funciones_sis COMA fsis aliascol | def p_fun_sis(t):
'''funciones_sis : funciones_sis COMA fsis aliascol'''
t[3].alias = t[4]
t[1].append(t[3])
t[0]=t[1] | [
"def",
"p_fun_sis",
"(",
"t",
")",
":",
"t",
"[",
"3",
"]",
".",
"alias",
"=",
"t",
"[",
"4",
"]",
"t",
"[",
"1",
"]",
".",
"append",
"(",
"t",
"[",
"3",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
1983,
0
] | [
1987,
13
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_argument_funcion | (t) | argument : funcionesLlamada | argument : funcionesLlamada | def p_argument_funcion(t):
'argument : funcionesLlamada'
grafo.newnode('ARGUMENT')
grafo.newchildrenF(grafo.index, t[1]['graph'])
reporte = "<argument> ::= <funcionesLlamada> \n" + t[1]['reporte']
t[0] = {'text' : t[1]['text'], 'c3d' : t[1]['c3d'], 'tflag':str(tempos.getcurrent()), 'select': t[1]['c3d'], 'graph' : grafo.index, 'reporte': reporte} | [
"def",
"p_argument_funcion",
"(",
"t",
")",
":",
"grafo",
".",
"newnode",
"(",
"'ARGUMENT'",
")",
"grafo",
".",
"newchildrenF",
"(",
"grafo",
".",
"index",
",",
"t",
"[",
"1",
"]",
"[",
"'graph'",
"]",
")",
"reporte",
"=",
"\"<argument> ::= <funcionesLlamada> \\n\"",
"+",
"t",
"[",
"1",
"]",
"[",
"'reporte'",
"]",
"t",
"[",
"0",
"]",
"=",
"{",
"'text'",
":",
"t",
"[",
"1",
"]",
"[",
"'text'",
"]",
",",
"'c3d'",
":",
"t",
"[",
"1",
"]",
"[",
"'c3d'",
"]",
",",
"'tflag'",
":",
"str",
"(",
"tempos",
".",
"getcurrent",
"(",
")",
")",
",",
"'select'",
":",
"t",
"[",
"1",
"]",
"[",
"'c3d'",
"]",
",",
"'graph'",
":",
"grafo",
".",
"index",
",",
"'reporte'",
":",
"reporte",
"}"
] | [
2351,
0
] | [
2356,
155
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
trim | (input) | return input.strip() | Eliminar espacios a los bordes
Elimina los espacios en blanco al inicio y final del string deseado.
Args:
input(String): palabra a recortar
Returns:
String
| Eliminar espacios a los bordes | def trim(input):
"""Eliminar espacios a los bordes
Elimina los espacios en blanco al inicio y final del string deseado.
Args:
input(String): palabra a recortar
Returns:
String
"""
return input.strip() | [
"def",
"trim",
"(",
"input",
")",
":",
"return",
"input",
".",
"strip",
"(",
")"
] | [
32,
0
] | [
43,
24
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
UnmaskingCurvePlotter.ylim | (self, ylim: Tuple[float, float]) | Set y axis limits | Set y axis limits | def ylim(self, ylim: Tuple[float, float]):
"""Set y axis limits"""
self._ylim = ylim | [
"def",
"ylim",
"(",
"self",
",",
"ylim",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
")",
":",
"self",
".",
"_ylim",
"=",
"ylim"
] | [
574,
4
] | [
576,
25
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
suma_de_cubos | (n: int) | return r | Calcula la suma de cubos de los dígitos recursivamente
:param n: Número a calcular
:n type: int
:return: Suma de cubos de los dígitos del número
:rtype: int
| Calcula la suma de cubos de los dígitos recursivamente | def suma_de_cubos(n: int) -> int:
"""Calcula la suma de cubos de los dígitos recursivamente
:param n: Número a calcular
:n type: int
:return: Suma de cubos de los dígitos del número
:rtype: int
"""
r = sum([int(x)**3 for x in str(n) if es_divisible(n, 3)])
print(f"La suma de cubos de {n} es: {r}")
if r != 153:
return suma_de_cubos(r)
print(f"La suma de cubos de {r} es: {r}")
return r | [
"def",
"suma_de_cubos",
"(",
"n",
":",
"int",
")",
"->",
"int",
":",
"r",
"=",
"sum",
"(",
"[",
"int",
"(",
"x",
")",
"**",
"3",
"for",
"x",
"in",
"str",
"(",
"n",
")",
"if",
"es_divisible",
"(",
"n",
",",
"3",
")",
"]",
")",
"print",
"(",
"f\"La suma de cubos de {n} es: {r}\"",
")",
"if",
"r",
"!=",
"153",
":",
"return",
"suma_de_cubos",
"(",
"r",
")",
"print",
"(",
"f\"La suma de cubos de {r} es: {r}\"",
")",
"return",
"r"
] | [
41,
0
] | [
54,
12
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_instruccionesPL_pl | (t) | instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_except
| instru_get_error
| instru_return
| operacion_logica
| asignacion
| instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_except
| instru_get_error
| instru_return
| operacion_logica
| asignacion
| def p_instruccionesPL_pl(t):
'''instruccionesPL_pl : sentencia_if
| sentencia_case
| sentencia_loop
| instru_exit
| instru_except
| instru_get_error
| instru_return
| operacion_logica
| asignacion
'''
t[0]= t[1] | [
"def",
"p_instruccionesPL_pl",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
594,
0
] | [
605,
14
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_init | (t) | s : instrucciones | s : instrucciones | def p_init(t):
's : instrucciones' | [
"def",
"p_init",
"(",
"t",
")",
":"
] | [
235,
0
] | [
236,
24
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.