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
Categoria.__str__
(self)
return self.nombre_categoria
retorna el nombre de la categoría
retorna el nombre de la categoría
def __str__(self): """retorna el nombre de la categoría""" return self.nombre_categoria
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "nombre_categoria" ]
[ 160, 4 ]
[ 162, 36 ]
null
python
es
['es', 'es', 'es']
True
true
null
init_default_handler
(level=None, root_dir=None, name=None, date=None)
Función para inicializar la configuración del root Logger Parameters ---------- level : str nivel de log root_dir : str directorio donde se almacenará el fichero de log para la ejecución name : str nombre de la ejecución. Se usará para generar el nombre del fichero de log. date : str fecha de ejecución. Se usará para generar el nombre del fichero de log.
Función para inicializar la configuración del root Logger
def init_default_handler(level=None, root_dir=None, name=None, date=None): """Función para inicializar la configuración del root Logger Parameters ---------- level : str nivel de log root_dir : str directorio donde se almacenará el fichero de log para la ejecución name : str nombre de la ejecución. Se usará para generar el nombre del fichero de log. date : str fecha de ejecución. Se usará para generar el nombre del fichero de log. """ date_str = date.strftime("%d_%m_%Y_%H_%M_%S") log_file_name = "{name}-{date_str}.log".format(name=name, date_str=date_str) log_dir = root_dir if root_dir else os.getcwd() log_file_path = os.path.join(log_dir, log_file_name) logging.basicConfig( level=logging.getLevelName(level), datefmt="%d-%m-%Y %H:%M:%S", format="[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)d)", handlers=[ logging.StreamHandler(sys.stdout), logging.FileHandler(log_file_path) ] )
[ "def", "init_default_handler", "(", "level", "=", "None", ",", "root_dir", "=", "None", ",", "name", "=", "None", ",", "date", "=", "None", ")", ":", "date_str", "=", "date", ".", "strftime", "(", "\"%d_%m_%Y_%H_%M_%S\"", ")", "log_file_name", "=", "\"{name}-{date_str}.log\"", ".", "format", "(", "name", "=", "name", ",", "date_str", "=", "date_str", ")", "log_dir", "=", "root_dir", "if", "root_dir", "else", "os", ".", "getcwd", "(", ")", "log_file_path", "=", "os", ".", "path", ".", "join", "(", "log_dir", ",", "log_file_name", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "getLevelName", "(", "level", ")", ",", "datefmt", "=", "\"%d-%m-%Y %H:%M:%S\"", ",", "format", "=", "\"[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)d)\"", ",", "handlers", "=", "[", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", ",", "logging", ".", "FileHandler", "(", "log_file_path", ")", "]", ")" ]
[ 10, 0 ]
[ 36, 5 ]
null
python
es
['es', 'es', 'es']
True
true
null
TraductoresHandler._removerImpresora
(self, printerName)
return { "action": "removerImpresora", "rta": "La impresora "+printerName+" fue removida con exito" }
elimina la sección del config.ini
elimina la sección del config.ini
def _removerImpresora(self, printerName): "elimina la sección del config.ini" self.config.delete_printer_from_config(printerName) return { "action": "removerImpresora", "rta": "La impresora "+printerName+" fue removida con exito" }
[ "def", "_removerImpresora", "(", "self", ",", "printerName", ")", ":", "self", ".", "config", ".", "delete_printer_from_config", "(", "printerName", ")", "return", "{", "\"action\"", ":", "\"removerImpresora\"", ",", "\"rta\"", ":", "\"La impresora \"", "+", "printerName", "+", "\" fue removida con exito\"", "}" ]
[ 292, 4 ]
[ 300, 9 ]
null
python
es
['es', 'es', 'es']
True
true
null
ArregloDinamico.__getitem__
(self, k: int)
Devuelve el elemento en la posición k :param k: posición del elemento :k type: int :return: elemento en la posición k :rtype: py_object
Devuelve el elemento en la posición k
def __getitem__(self, k: int) -> py_object: """Devuelve el elemento en la posición k :param k: posición del elemento :k type: int :return: elemento en la posición k :rtype: py_object """ if 0 <= k < self._n: return self._A[k] elif k < 0 and self._n + k >= 0: return self._A[self._n + k] raise IndexError("El indice esta fuera de rango")
[ "def", "__getitem__", "(", "self", ",", "k", ":", "int", ")", "->", "py_object", ":", "if", "0", "<=", "k", "<", "self", ".", "_n", ":", "return", "self", ".", "_A", "[", "k", "]", "elif", "k", "<", "0", "and", "self", ".", "_n", "+", "k", ">=", "0", ":", "return", "self", ".", "_A", "[", "self", ".", "_n", "+", "k", "]", "raise", "IndexError", "(", "\"El indice esta fuera de rango\"", ")" ]
[ 31, 4 ]
[ 43, 57 ]
null
python
es
['es', 'es', 'es']
True
true
null
extractFeatures
(sent)
return featurelist
Reglas que configuran las feature functions para entrenamiento :param sent: Data as `[[[[[letter, POS, BIO-label],...],words],sents]]` :type: list :return: list of words with characters as features list: [[[[[letterfeatures],POS,BIO-label],letters],words]] :rtype: list
Reglas que configuran las feature functions para entrenamiento
def extractFeatures(sent): ''' Reglas que configuran las feature functions para entrenamiento :param sent: Data as `[[[[[letter, POS, BIO-label],...],words],sents]]` :type: list :return: list of words with characters as features list: [[[[[letterfeatures],POS,BIO-label],letters],words]] :rtype: list ''' featurelist = [] senlen = len(sent) # each word in a sentence for i in range(senlen): word = sent[i] wordlen = len(word) lettersequence = '' # each letter in a word for j in range(wordlen): letter = word[j][0] # gathering previous letters lettersequence += letter # ignore digits if not letter.isdigit(): features = [ 'bias', 'letterLowercase=' + letter.lower(), ] # Position of word in sentence if i == senlen -1: features.append("EOS") else: features.append("BOS") # Pos tag sequence (Don't get pos tag if sentence is 1 word long) if i > 0 and senlen > 1: features.append('prevpostag=' + sent[i-1][0][1]) if i != senlen-1: features.append('nxtpostag=' + sent[i+1][0][1]) # Position of letter in word if j == 0: features.append('BOW') elif j == wordlen-1: features.append('EOW') else: features.append('letterposition=-%s' % str(wordlen-1-j)) # Letter sequences before letter if j >= 4: features.append('prev4letters=' + lettersequence[j-4:j].lower() + '>') if j >= 3: features.append('prev3letters=' + lettersequence[j-3:j].lower() + '>') if j >= 2: features.append('prev2letters=' + lettersequence[j-2:j].lower() + '>') if j >= 1: features.append('prevletter=' + lettersequence[j-1:j].lower() + '>') # letter sequences after letter if j <= wordlen-2: nxtlets = word[j+1][0] features.append('nxtletter=<' + nxtlets.lower()) if j <= wordlen-3: nxtlets += word[j+2][0] features.append('nxt2letters=<' + nxtlets.lower()) if j <= wordlen-4: nxtlets += word[j+3][0] features.append('nxt3letters=<' + nxtlets.lower()) if j <= wordlen-5: nxtlets += word[j+4][0] features.append('nxt4letters=<' + nxtlets.lower()) # Add encoding for pysrfsuite featurelist.append([f.encode('utf-8') for f in features]) return featurelist
[ "def", "extractFeatures", "(", "sent", ")", ":", "featurelist", "=", "[", "]", "senlen", "=", "len", "(", "sent", ")", "# each word in a sentence", "for", "i", "in", "range", "(", "senlen", ")", ":", "word", "=", "sent", "[", "i", "]", "wordlen", "=", "len", "(", "word", ")", "lettersequence", "=", "''", "# each letter in a word", "for", "j", "in", "range", "(", "wordlen", ")", ":", "letter", "=", "word", "[", "j", "]", "[", "0", "]", "# gathering previous letters", "lettersequence", "+=", "letter", "# ignore digits", "if", "not", "letter", ".", "isdigit", "(", ")", ":", "features", "=", "[", "'bias'", ",", "'letterLowercase='", "+", "letter", ".", "lower", "(", ")", ",", "]", "# Position of word in sentence", "if", "i", "==", "senlen", "-", "1", ":", "features", ".", "append", "(", "\"EOS\"", ")", "else", ":", "features", ".", "append", "(", "\"BOS\"", ")", "# Pos tag sequence (Don't get pos tag if sentence is 1 word long)", "if", "i", ">", "0", "and", "senlen", ">", "1", ":", "features", ".", "append", "(", "'prevpostag='", "+", "sent", "[", "i", "-", "1", "]", "[", "0", "]", "[", "1", "]", ")", "if", "i", "!=", "senlen", "-", "1", ":", "features", ".", "append", "(", "'nxtpostag='", "+", "sent", "[", "i", "+", "1", "]", "[", "0", "]", "[", "1", "]", ")", "# Position of letter in word", "if", "j", "==", "0", ":", "features", ".", "append", "(", "'BOW'", ")", "elif", "j", "==", "wordlen", "-", "1", ":", "features", ".", "append", "(", "'EOW'", ")", "else", ":", "features", ".", "append", "(", "'letterposition=-%s'", "%", "str", "(", "wordlen", "-", "1", "-", "j", ")", ")", "# Letter sequences before letter", "if", "j", ">=", "4", ":", "features", ".", "append", "(", "'prev4letters='", "+", "lettersequence", "[", "j", "-", "4", ":", "j", "]", ".", "lower", "(", ")", "+", "'>'", ")", "if", "j", ">=", "3", ":", "features", ".", "append", "(", "'prev3letters='", "+", "lettersequence", "[", "j", "-", "3", ":", "j", "]", ".", "lower", "(", ")", "+", "'>'", ")", "if", "j", ">=", "2", ":", "features", ".", "append", "(", "'prev2letters='", "+", "lettersequence", "[", "j", "-", "2", ":", "j", "]", ".", "lower", "(", ")", "+", "'>'", ")", "if", "j", ">=", "1", ":", "features", ".", "append", "(", "'prevletter='", "+", "lettersequence", "[", "j", "-", "1", ":", "j", "]", ".", "lower", "(", ")", "+", "'>'", ")", "# letter sequences after letter", "if", "j", "<=", "wordlen", "-", "2", ":", "nxtlets", "=", "word", "[", "j", "+", "1", "]", "[", "0", "]", "features", ".", "append", "(", "'nxtletter=<'", "+", "nxtlets", ".", "lower", "(", ")", ")", "if", "j", "<=", "wordlen", "-", "3", ":", "nxtlets", "+=", "word", "[", "j", "+", "2", "]", "[", "0", "]", "features", ".", "append", "(", "'nxt2letters=<'", "+", "nxtlets", ".", "lower", "(", ")", ")", "if", "j", "<=", "wordlen", "-", "4", ":", "nxtlets", "+=", "word", "[", "j", "+", "3", "]", "[", "0", "]", "features", ".", "append", "(", "'nxt3letters=<'", "+", "nxtlets", ".", "lower", "(", ")", ")", "if", "j", "<=", "wordlen", "-", "5", ":", "nxtlets", "+=", "word", "[", "j", "+", "4", "]", "[", "0", "]", "features", ".", "append", "(", "'nxt4letters=<'", "+", "nxtlets", ".", "lower", "(", ")", ")", "# Add encoding for pysrfsuite", "featurelist", ".", "append", "(", "[", "f", ".", "encode", "(", "'utf-8'", ")", "for", "f", "in", "features", "]", ")", "return", "featurelist" ]
[ 307, 0 ]
[ 381, 22 ]
null
python
es
['es', 'es', 'es']
True
true
null
Simulador.temperatura_interior
(self)
return uniform(23.45, 23.55)
Temperatura al interior del avión en grados Celsius.
Temperatura al interior del avión en grados Celsius.
def temperatura_interior(self): """Temperatura al interior del avión en grados Celsius. """ return uniform(23.45, 23.55)
[ "def", "temperatura_interior", "(", "self", ")", ":", "return", "uniform", "(", "23.45", ",", "23.55", ")" ]
[ 99, 4 ]
[ 103, 36 ]
null
python
es
['es', 'es', 'es']
True
true
null
Tipo.comparetipo
(self,tipocolumn,tipovalor)
comparo los tipos de la columna con el del valor
comparo los tipos de la columna con el del valor
def comparetipo(self,tipocolumn,tipovalor): 'comparo los tipos de la columna con el del valor' if tipocolumn.tipo=='int': tipocolumn.tipo='integer' if tipovalor.tipo in ('decimal','numeric','double','real','money'): tipovalor.size=tipovalor.size-1 if tipocolumn.size >= tipovalor.size or tipocolumn.size==-1: if tipocolumn.tipo == 'decimal' or tipocolumn.tipo == 'numeric': if tipovalor.tipo == 'decimal' or tipovalor.tipo == 'numeric' or tipovalor.tipo == 'bigint' or tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer' or tipovalor.tipo == 'money' or tipovalor.tipo == 'double' or tipovalor.tipo == 'real' : return True elif tipocolumn.tipo == 'double': if tipovalor.tipo == 'double' or tipovalor.tipo == 'bigint' or tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer' or tipovalor.tipo == 'money' or tipovalor.tipo == 'real': return True elif tipocolumn.tipo == 'money': if tipovalor.tipo == 'bigint' or tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer' or tipovalor.tipo == 'money' or tipovalor.tipo == 'real': return True elif tipocolumn.tipo == 'real': if tipovalor.tipo == 'bigint' or tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer' or tipovalor.tipo == 'real': return True elif tipocolumn.tipo == 'bigint': if tipovalor.tipo == 'bigint' or tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer': return True elif tipocolumn.tipo == 'integer': if tipovalor.tipo == 'smallint' or tipovalor.tipo == 'integer': return True elif tipocolumn.tipo == 'smallint': if tipovalor.tipo == 'smallint': return True elif tipocolumn.tipo in ('varchar','char','character varyng','text','character'): if tipovalor.tipo in ('varchar','char','character varyng','text','character'): return True elif tipocolumn.tipo == 'timestamp without time zone': if tipovalor.tipo in ('date','timestamp without time zone'): return True elif tipocolumn.tipo == 'date': if tipovalor.tipo in ('date','timestamp without time zone'): return True elif tipocolumn.tipo == 'time without time zone': if tipovalor.tipo in ('time without time zone','timestamp without time zone'): return True elif tipocolumn.tipo == 'boolean': if tipovalor.tipo == 'boolean': return True
[ "def", "comparetipo", "(", "self", ",", "tipocolumn", ",", "tipovalor", ")", ":", "if", "tipocolumn", ".", "tipo", "==", "'int'", ":", "tipocolumn", ".", "tipo", "=", "'integer'", "if", "tipovalor", ".", "tipo", "in", "(", "'decimal'", ",", "'numeric'", ",", "'double'", ",", "'real'", ",", "'money'", ")", ":", "tipovalor", ".", "size", "=", "tipovalor", ".", "size", "-", "1", "if", "tipocolumn", ".", "size", ">=", "tipovalor", ".", "size", "or", "tipocolumn", ".", "size", "==", "-", "1", ":", "if", "tipocolumn", ".", "tipo", "==", "'decimal'", "or", "tipocolumn", ".", "tipo", "==", "'numeric'", ":", "if", "tipovalor", ".", "tipo", "==", "'decimal'", "or", "tipovalor", ".", "tipo", "==", "'numeric'", "or", "tipovalor", ".", "tipo", "==", "'bigint'", "or", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", "or", "tipovalor", ".", "tipo", "==", "'money'", "or", "tipovalor", ".", "tipo", "==", "'double'", "or", "tipovalor", ".", "tipo", "==", "'real'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'double'", ":", "if", "tipovalor", ".", "tipo", "==", "'double'", "or", "tipovalor", ".", "tipo", "==", "'bigint'", "or", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", "or", "tipovalor", ".", "tipo", "==", "'money'", "or", "tipovalor", ".", "tipo", "==", "'real'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'money'", ":", "if", "tipovalor", ".", "tipo", "==", "'bigint'", "or", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", "or", "tipovalor", ".", "tipo", "==", "'money'", "or", "tipovalor", ".", "tipo", "==", "'real'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'real'", ":", "if", "tipovalor", ".", "tipo", "==", "'bigint'", "or", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", "or", "tipovalor", ".", "tipo", "==", "'real'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'bigint'", ":", "if", "tipovalor", ".", "tipo", "==", "'bigint'", "or", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'integer'", ":", "if", "tipovalor", ".", "tipo", "==", "'smallint'", "or", "tipovalor", ".", "tipo", "==", "'integer'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'smallint'", ":", "if", "tipovalor", ".", "tipo", "==", "'smallint'", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "in", "(", "'varchar'", ",", "'char'", ",", "'character varyng'", ",", "'text'", ",", "'character'", ")", ":", "if", "tipovalor", ".", "tipo", "in", "(", "'varchar'", ",", "'char'", ",", "'character varyng'", ",", "'text'", ",", "'character'", ")", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'timestamp without time zone'", ":", "if", "tipovalor", ".", "tipo", "in", "(", "'date'", ",", "'timestamp without time zone'", ")", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'date'", ":", "if", "tipovalor", ".", "tipo", "in", "(", "'date'", ",", "'timestamp without time zone'", ")", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'time without time zone'", ":", "if", "tipovalor", ".", "tipo", "in", "(", "'time without time zone'", ",", "'timestamp without time zone'", ")", ":", "return", "True", "elif", "tipocolumn", ".", "tipo", "==", "'boolean'", ":", "if", "tipovalor", ".", "tipo", "==", "'boolean'", ":", "return", "True" ]
[ 42, 4 ]
[ 87, 31 ]
null
python
es
['es', 'es', 'es']
True
true
null
apply_homography_frame
(frame: Image, h: np.ndarray)
return frame_h
Aplica la homografía a un frame. :param frame: imagen. :param h: matriz de homografía. :return: frame con la homografía aplicada.
Aplica la homografía a un frame.
def apply_homography_frame(frame: Image, h: np.ndarray) -> Image: """Aplica la homografía a un frame. :param frame: imagen. :param h: matriz de homografía. :return: frame con la homografía aplicada. """ height, width, _ = frame.shape # Copiar frame para no editarlo. frame = frame.copy() # Aplicar homografía y devolverlo frame_h = cv2.warpPerspective(frame, h, (width, height)) return frame_h
[ "def", "apply_homography_frame", "(", "frame", ":", "Image", ",", "h", ":", "np", ".", "ndarray", ")", "->", "Image", ":", "height", ",", "width", ",", "_", "=", "frame", ".", "shape", "# Copiar frame para no editarlo.", "frame", "=", "frame", ".", "copy", "(", ")", "# Aplicar homografía y devolverlo", "frame_h", "=", "cv2", ".", "warpPerspective", "(", "frame", ",", "h", ",", "(", "width", ",", "height", ")", ")", "return", "frame_h" ]
[ 22, 0 ]
[ 34, 18 ]
null
python
es
['es', 'es', 'es']
True
true
null
BcraSmlScraperTestCase.test_sml_configuration_has_coins
(self)
Validar la existencia de la clave coins dentro de la configuración de sml
Validar la existencia de la clave coins dentro de la configuración de sml
def test_sml_configuration_has_coins(self): """Validar la existencia de la clave coins dentro de la configuración de sml""" dict_config = {'sml': {'foo': 'bar'}} with mock.patch( 'builtins.open', return_value=io.StringIO(json.dumps(dict_config)) ): with self.assertRaises(InvalidConfigurationError): config = read_config("config_general.json", "sml") validate_coins_key_config(config)
[ "def", "test_sml_configuration_has_coins", "(", "self", ")", ":", "dict_config", "=", "{", "'sml'", ":", "{", "'foo'", ":", "'bar'", "}", "}", "with", "mock", ".", "patch", "(", "'builtins.open'", ",", "return_value", "=", "io", ".", "StringIO", "(", "json", ".", "dumps", "(", "dict_config", ")", ")", ")", ":", "with", "self", ".", "assertRaises", "(", "InvalidConfigurationError", ")", ":", "config", "=", "read_config", "(", "\"config_general.json\"", ",", "\"sml\"", ")", "validate_coins_key_config", "(", "config", ")" ]
[ 336, 4 ]
[ 348, 49 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_definicion_procedure_2
(t)
definicion_procedure : cuerpo_procedure END
definicion_procedure : cuerpo_procedure END
def p_definicion_procedure_2(t): '''definicion_procedure : cuerpo_procedure END''' t[0] = Start("DEFINICION_PROCEDURE") t[0].addChild(t[1])
[ "def", "p_definicion_procedure_2", "(", "t", ")", ":", "t", "[", "0", "]", "=", "Start", "(", "\"DEFINICION_PROCEDURE\"", ")", "t", "[", "0", "]", ".", "addChild", "(", "t", "[", "1", "]", ")" ]
[ 1790, 0 ]
[ 1793, 23 ]
null
python
es
['es', 'es', 'es']
True
true
null
EntityBase.save
(self, *args, **kwargs)
return super(EntityBase, self).save(*args, **kwargs)
Controladora de almacenamiento
Controladora de almacenamiento
def save(self, *args, **kwargs): """ Controladora de almacenamiento""" if not self.created_at: self.created_at = datetime.datetime.utcnow() self.updated_at = datetime.datetime.utcnow() return super(EntityBase, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "created_at", ":", "self", ".", "created_at", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "self", ".", "updated_at", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "return", "super", "(", "EntityBase", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 18, 4 ]
[ 23, 60 ]
null
python
es
['es', 'es', 'es']
True
true
null
ModelBase.get_img_without_default
(cls)
return cls.get_img(default="")
Igual que cls.get_img pero sin default atributo.
Igual que cls.get_img pero sin default atributo.
def get_img_without_default(cls): """Igual que cls.get_img pero sin default atributo.""" return cls.get_img(default="")
[ "def", "get_img_without_default", "(", "cls", ")", ":", "return", "cls", ".", "get_img", "(", "default", "=", "\"\"", ")" ]
[ 380, 4 ]
[ 382, 38 ]
null
python
es
['es', 'es', 'es']
True
true
null
Restaurant.increment_number_served
(self, additional_served)
Permitir que el usuario incremente la cantidad de clientes atendidos.
Permitir que el usuario incremente la cantidad de clientes atendidos.
def increment_number_served(self, additional_served): """Permitir que el usuario incremente la cantidad de clientes atendidos.""" self.number_served += additional_served
[ "def", "increment_number_served", "(", "self", ",", "additional_served", ")", ":", "self", ".", "number_served", "+=", "additional_served" ]
[ 23, 4 ]
[ 25, 47 ]
null
python
es
['es', 'es', 'es']
True
true
null
CajeroHandler.set_successor
(successor)
Establecer el siguiente controlador en la cadena
Establecer el siguiente controlador en la cadena
def set_successor(successor): """ Establecer el siguiente controlador en la cadena """
[ "def", "set_successor", "(", "successor", ")", ":" ]
[ 7, 4 ]
[ 8, 64 ]
null
python
es
['es', 'es', 'es']
True
true
null
TokenCallback.get_token
(userid: int, limit: int = 0, *, cursor)
Obtiene todos los token's de un usuario determinado
Obtiene todos los token's de un usuario determinado
async def get_token(userid: int, limit: int = 0, *, cursor) -> AsyncIterator[str]: """Obtiene todos los token's de un usuario determinado""" sql = ["SELECT token FROM tokens WHERE id_user = %s"] args = [userid] if (limit > 0): sql.append("LIMIT %s") args.append(limit) await cursor.execute( " ".join(sql), args ) while (token := await cursor.fetchone()): yield token
[ "async", "def", "get_token", "(", "userid", ":", "int", ",", "limit", ":", "int", "=", "0", ",", "*", ",", "cursor", ")", "->", "AsyncIterator", "[", "str", "]", ":", "sql", "=", "[", "\"SELECT token FROM tokens WHERE id_user = %s\"", "]", "args", "=", "[", "userid", "]", "if", "(", "limit", ">", "0", ")", ":", "sql", ".", "append", "(", "\"LIMIT %s\"", ")", "args", ".", "append", "(", "limit", ")", "await", "cursor", ".", "execute", "(", "\" \"", ".", "join", "(", "sql", ")", ",", "args", ")", "while", "(", "token", ":=", "await", "cursor", ".", "fetchone", "(", ")", ")", ":", "yield", "token" ]
[ 255, 4 ]
[ 271, 23 ]
null
python
es
['es', 'es', 'es']
True
true
null
BaseView.get_company
(self)
return company
Obtiene la instancia de la empresa actual.
Obtiene la instancia de la empresa actual.
def get_company(self): """Obtiene la instancia de la empresa actual.""" try: company = self.request.company except (AttributeError): try: company = self.get_context_data()["company"] except (AttributeError, KeyError): company = get_object_or_404(Company, pk=kwargs[self.company_in_url]) return company
[ "def", "get_company", "(", "self", ")", ":", "try", ":", "company", "=", "self", ".", "request", ".", "company", "except", "(", "AttributeError", ")", ":", "try", ":", "company", "=", "self", ".", "get_context_data", "(", ")", "[", "\"company\"", "]", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "company", "=", "get_object_or_404", "(", "Company", ",", "pk", "=", "kwargs", "[", "self", ".", "company_in_url", "]", ")", "return", "company" ]
[ 138, 4 ]
[ 147, 22 ]
null
python
es
['es', 'es', 'es']
True
true
null
get_raster_metadata
(file, con_stats=True)
return { 'driver_short_name': raster.GetDriver().ShortName, 'driver_long_name': raster.GetDriver().LongName, 'raster_count': raster.RasterCount, 'subdataset_count': len(raster.GetSubDatasets()), 'srid': srid, # puede ser None 'extent_capa': extent_capa, 'extent_capa_4326': extent_capa_4326, 'metadata_json': { 'gdalinfo': metadata_gdalinfo_json, 'variables_detectadas': variables_detectadas, 'subdatasets': subdatasets, }, 'proyeccion_proj4': proj.ExportToProj4(), 'size_height': raster.RasterYSize, 'size_width': raster.RasterXSize, }
Devuelve un json con metadatos detallados de un raster interfaseando con gdal y gdalinfo. Pensado para capturar toda la info posible del archivo y almacenarla en la IDE, en el campo Capa.gdal_metadata. El parametro optativo con_stats obliga a gdal_info a calcular los valores minimos, maximos y promedios de cada banda.
Devuelve un json con metadatos detallados de un raster interfaseando con gdal y gdalinfo.
def get_raster_metadata(file, con_stats=True): """Devuelve un json con metadatos detallados de un raster interfaseando con gdal y gdalinfo. Pensado para capturar toda la info posible del archivo y almacenarla en la IDE, en el campo Capa.gdal_metadata. El parametro optativo con_stats obliga a gdal_info a calcular los valores minimos, maximos y promedios de cada banda. """ raster = gdal.Open(file, gdal.GA_ReadOnly) if raster is None: return None # extraemos toda info de proyeccion del raster usando gdal srid, proj, extent_capa = _get_raster_proj_info(raster) # extraemos todos los metadatos del raster usando gdalinfo metadata_gdalinfo_json = _run_gdalinfo(file, con_stats) # esto no es correcto pero va a evitar que explote si faltan metadatos extent_capa_4326 = extent_capa try: extent_capa_4326 = extentConvert(extent_capa, metadata_gdalinfo_json['coordinateSystem']['wkt'], 'EPSG:4326') except: pass # print "Calculated extent: %s"%(str(extent_capa)) # extent_capa_4326 = _get_polygon_extent(metadata_gdalinfo_json['wgs84Extent']['coordinates'][0]) # print "GDAL Info: proj: %s, srid: %s, extent 4326: %s"%( # metadata_gdalinfo_json['coordinateSystem']['wkt'], # str(srid), # extentConvert(extent_capa, metadata_gdalinfo_json['coordinateSystem']['wkt'], 'EPSG:4326') # ) # if 'wgs84Extent' in metadata_gdalinfo_json: # try: # extent_capa_4326 = _get_polygon_extent(metadata_gdalinfo_json['wgs84Extent']['coordinates'][0]) # except: # pass variables_detectadas = {} subdatasets = [] # Segun el formato del raster, determinamos las bandas para armar los mapas 'layer_raster_band' (mapas de variables) if raster.GetDriver().ShortName == 'GRIB': # en el caso de GRIB nos interesan los elementos en 'bands' if 'bands' in metadata_gdalinfo_json: wind_u_band = wind_v_band = None for banda in metadata_gdalinfo_json['bands']: try: # si por algun motivo la banda no tiene la info necesaria la ignoramos nro_banda = banda['band'] grib_element = banda['metadata']['']['GRIB_ELEMENT'] grib_comment = banda['metadata']['']['GRIB_COMMENT'] minimo = banda.get('minimum') maximo = banda.get('maximum') if grib_element in ('UGRD', 'UOGRD'): wind_u_band = nro_banda elif grib_element in ('VGRD', 'VOGRD'): wind_v_band = nro_banda else: variables_detectadas[nro_banda] = { 'elemento': grib_element, 'descripcion': grib_comment, 'rango': (minimo, maximo), # almacenamos el rango de la banda por si lo necesitamos en el DATARANGE } except: pass if wind_u_band and wind_v_band: nro_banda = '{},{}'.format(wind_u_band, wind_v_band) variables_detectadas[nro_banda] = { 'elemento': 'WIND', 'descripcion': 'Wind', 'rango': (None, None), # Por el momento no necesitamos rangos para WIND, ya que la simbologia usa uv_length y uv_angle } wind_u_band = wind_v_band = None # Ahora analizamos subdatasets for subdataset in raster.GetSubDatasets(): # Ejemplo de un subdataset: ('NETCDF:"/vagrant/data/SABANCAYA_2018062806_fcst_VAG_18.res.nc":TOPOGRAPHY', '[41x65] TOPOGRAPHY (32-bit floating-point)') # Ejemplo de un subdataset: ('HDF5:"data/RMA1_0201_01_TH_20180713T164924Z.H5"://dataset1/data1/data', '[360x526] //dataset1/data1/data (64-bit floating-point)') raster_subdataset = gdal.Open(subdataset[0], gdal.GA_ReadOnly) srid, proj, extent = _get_raster_proj_info(raster_subdataset) subdataset_gdalinfo_json = _run_gdalinfo(subdataset[0], con_stats) formato, path, identificador = subdataset[0].split(':') # Creamos la siguiente estructura para guardar todala info en la IDE, independientemente del formato subdatasets.append({ 'definicion': subdataset, # Ej: ('HDF5:/path/al/archivo:identificador', [alguna descripcion]) 'identificador': identificador, # Ej: TOPOGRAPHY 'gdalinfo': subdataset_gdalinfo_json, # toda la matadata provista por gdalinfo para el subdataset actual }) # Y en el caso de netCDF y HDF5, detectamos variables para crear los mapas layer_raster_band, como hacemos con GRIBs # Tomamos la primer banda por convencion, ya que mapserver no permite trabajar especificamente una banda dentro de un subdataset (la unidad es el dataset), # y en todos los casos que vimos las bandas tienen la misma variable, solo cambia el timestamp if 'bands' in subdataset_gdalinfo_json: banda0 = subdataset_gdalinfo_json['bands'][0] if raster.GetDriver().ShortName == 'netCDF': variables_detectadas[identificador] = { 'elemento': banda0['metadata'][''].get('NETCDF_VARNAME', ''), # aparentemente todo netCDF tiene este campo y es igual para toda banda del subdataset 'descripcion': banda0['metadata'][''].get('description', ''), # algunos netCDF no tienen este campo 'rango': (banda0.get('minimum'), banda0.get('maximum')), # en principio este rango no nos interesa porque este formato se renderiza directamente, va por compatibilidad 'extent': extent # extent, necesario para cada mapa layer_raster_band } elif raster.GetDriver().ShortName == 'HDF5': variables_detectadas[identificador] = { 'elemento': subdataset_gdalinfo_json['metadata'][''].get('what_object', ''), # aparentemente los HDF5 de SMN tienen toooodo duplicado en todas bandas y son todas iguales 'descripcion': '', # no encontre nada para cargar... 'rango': (None, None), # no nos interesa este campo, solo por compatibilidad 'extent': extent # extent, necesario para cada mapa layer_raster_band } else: # Necesitamos info estructural especifica si es otro formato... pass # Lamentablemente hay inconsistencias en algunos archivos analizados con respecto al extent: # a veces el de la capa no coincide con el de los subdatasets. Tomamos el primero, que se utilizara para renderizar if len(subdatasets) > 0: extent_capa = variables_detectadas[subdatasets[0]['identificador']]['extent'] try: # los casos analizados NO incluyen informacion de la proyeccion en bandas, solo coordenadas que parecen ser 4326, como no hay garantia intento reproyectarlo extent_capa_4326 = extentConvert(extent_capa, 'EPSG:4326', 'EPSG:4326') except: pass # construimos la respuesta return { 'driver_short_name': raster.GetDriver().ShortName, 'driver_long_name': raster.GetDriver().LongName, 'raster_count': raster.RasterCount, 'subdataset_count': len(raster.GetSubDatasets()), 'srid': srid, # puede ser None 'extent_capa': extent_capa, 'extent_capa_4326': extent_capa_4326, 'metadata_json': { 'gdalinfo': metadata_gdalinfo_json, 'variables_detectadas': variables_detectadas, 'subdatasets': subdatasets, }, 'proyeccion_proj4': proj.ExportToProj4(), 'size_height': raster.RasterYSize, 'size_width': raster.RasterXSize, }
[ "def", "get_raster_metadata", "(", "file", ",", "con_stats", "=", "True", ")", ":", "raster", "=", "gdal", ".", "Open", "(", "file", ",", "gdal", ".", "GA_ReadOnly", ")", "if", "raster", "is", "None", ":", "return", "None", "# extraemos toda info de proyeccion del raster usando gdal", "srid", ",", "proj", ",", "extent_capa", "=", "_get_raster_proj_info", "(", "raster", ")", "# extraemos todos los metadatos del raster usando gdalinfo", "metadata_gdalinfo_json", "=", "_run_gdalinfo", "(", "file", ",", "con_stats", ")", "# esto no es correcto pero va a evitar que explote si faltan metadatos", "extent_capa_4326", "=", "extent_capa", "try", ":", "extent_capa_4326", "=", "extentConvert", "(", "extent_capa", ",", "metadata_gdalinfo_json", "[", "'coordinateSystem'", "]", "[", "'wkt'", "]", ",", "'EPSG:4326'", ")", "except", ":", "pass", "# print \"Calculated extent: %s\"%(str(extent_capa))", "# extent_capa_4326 = _get_polygon_extent(metadata_gdalinfo_json['wgs84Extent']['coordinates'][0])", "# print \"GDAL Info: proj: %s, srid: %s, extent 4326: %s\"%(", "# metadata_gdalinfo_json['coordinateSystem']['wkt'],", "# str(srid),", "# extentConvert(extent_capa, metadata_gdalinfo_json['coordinateSystem']['wkt'], 'EPSG:4326')", "# )", "# if 'wgs84Extent' in metadata_gdalinfo_json:", "# try:", "# extent_capa_4326 = _get_polygon_extent(metadata_gdalinfo_json['wgs84Extent']['coordinates'][0])", "# except:", "# pass", "variables_detectadas", "=", "{", "}", "subdatasets", "=", "[", "]", "# Segun el formato del raster, determinamos las bandas para armar los mapas 'layer_raster_band' (mapas de variables)", "if", "raster", ".", "GetDriver", "(", ")", ".", "ShortName", "==", "'GRIB'", ":", "# en el caso de GRIB nos interesan los elementos en 'bands'", "if", "'bands'", "in", "metadata_gdalinfo_json", ":", "wind_u_band", "=", "wind_v_band", "=", "None", "for", "banda", "in", "metadata_gdalinfo_json", "[", "'bands'", "]", ":", "try", ":", "# si por algun motivo la banda no tiene la info necesaria la ignoramos", "nro_banda", "=", "banda", "[", "'band'", "]", "grib_element", "=", "banda", "[", "'metadata'", "]", "[", "''", "]", "[", "'GRIB_ELEMENT'", "]", "grib_comment", "=", "banda", "[", "'metadata'", "]", "[", "''", "]", "[", "'GRIB_COMMENT'", "]", "minimo", "=", "banda", ".", "get", "(", "'minimum'", ")", "maximo", "=", "banda", ".", "get", "(", "'maximum'", ")", "if", "grib_element", "in", "(", "'UGRD'", ",", "'UOGRD'", ")", ":", "wind_u_band", "=", "nro_banda", "elif", "grib_element", "in", "(", "'VGRD'", ",", "'VOGRD'", ")", ":", "wind_v_band", "=", "nro_banda", "else", ":", "variables_detectadas", "[", "nro_banda", "]", "=", "{", "'elemento'", ":", "grib_element", ",", "'descripcion'", ":", "grib_comment", ",", "'rango'", ":", "(", "minimo", ",", "maximo", ")", ",", "# almacenamos el rango de la banda por si lo necesitamos en el DATARANGE", "}", "except", ":", "pass", "if", "wind_u_band", "and", "wind_v_band", ":", "nro_banda", "=", "'{},{}'", ".", "format", "(", "wind_u_band", ",", "wind_v_band", ")", "variables_detectadas", "[", "nro_banda", "]", "=", "{", "'elemento'", ":", "'WIND'", ",", "'descripcion'", ":", "'Wind'", ",", "'rango'", ":", "(", "None", ",", "None", ")", ",", "# Por el momento no necesitamos rangos para WIND, ya que la simbologia usa uv_length y uv_angle", "}", "wind_u_band", "=", "wind_v_band", "=", "None", "# Ahora analizamos subdatasets", "for", "subdataset", "in", "raster", ".", "GetSubDatasets", "(", ")", ":", "# Ejemplo de un subdataset: ('NETCDF:\"/vagrant/data/SABANCAYA_2018062806_fcst_VAG_18.res.nc\":TOPOGRAPHY', '[41x65] TOPOGRAPHY (32-bit floating-point)')", "# Ejemplo de un subdataset: ('HDF5:\"data/RMA1_0201_01_TH_20180713T164924Z.H5\"://dataset1/data1/data', '[360x526] //dataset1/data1/data (64-bit floating-point)')", "raster_subdataset", "=", "gdal", ".", "Open", "(", "subdataset", "[", "0", "]", ",", "gdal", ".", "GA_ReadOnly", ")", "srid", ",", "proj", ",", "extent", "=", "_get_raster_proj_info", "(", "raster_subdataset", ")", "subdataset_gdalinfo_json", "=", "_run_gdalinfo", "(", "subdataset", "[", "0", "]", ",", "con_stats", ")", "formato", ",", "path", ",", "identificador", "=", "subdataset", "[", "0", "]", ".", "split", "(", "':'", ")", "# Creamos la siguiente estructura para guardar todala info en la IDE, independientemente del formato", "subdatasets", ".", "append", "(", "{", "'definicion'", ":", "subdataset", ",", "# Ej: ('HDF5:/path/al/archivo:identificador', [alguna descripcion])", "'identificador'", ":", "identificador", ",", "# Ej: TOPOGRAPHY", "'gdalinfo'", ":", "subdataset_gdalinfo_json", ",", "# toda la matadata provista por gdalinfo para el subdataset actual", "}", ")", "# Y en el caso de netCDF y HDF5, detectamos variables para crear los mapas layer_raster_band, como hacemos con GRIBs", "# Tomamos la primer banda por convencion, ya que mapserver no permite trabajar especificamente una banda dentro de un subdataset (la unidad es el dataset),", "# y en todos los casos que vimos las bandas tienen la misma variable, solo cambia el timestamp", "if", "'bands'", "in", "subdataset_gdalinfo_json", ":", "banda0", "=", "subdataset_gdalinfo_json", "[", "'bands'", "]", "[", "0", "]", "if", "raster", ".", "GetDriver", "(", ")", ".", "ShortName", "==", "'netCDF'", ":", "variables_detectadas", "[", "identificador", "]", "=", "{", "'elemento'", ":", "banda0", "[", "'metadata'", "]", "[", "''", "]", ".", "get", "(", "'NETCDF_VARNAME'", ",", "''", ")", ",", "# aparentemente todo netCDF tiene este campo y es igual para toda banda del subdataset", "'descripcion'", ":", "banda0", "[", "'metadata'", "]", "[", "''", "]", ".", "get", "(", "'description'", ",", "''", ")", ",", "# algunos netCDF no tienen este campo", "'rango'", ":", "(", "banda0", ".", "get", "(", "'minimum'", ")", ",", "banda0", ".", "get", "(", "'maximum'", ")", ")", ",", "# en principio este rango no nos interesa porque este formato se renderiza directamente, va por compatibilidad", "'extent'", ":", "extent", "# extent, necesario para cada mapa layer_raster_band", "}", "elif", "raster", ".", "GetDriver", "(", ")", ".", "ShortName", "==", "'HDF5'", ":", "variables_detectadas", "[", "identificador", "]", "=", "{", "'elemento'", ":", "subdataset_gdalinfo_json", "[", "'metadata'", "]", "[", "''", "]", ".", "get", "(", "'what_object'", ",", "''", ")", ",", "# aparentemente los HDF5 de SMN tienen toooodo duplicado en todas bandas y son todas iguales", "'descripcion'", ":", "''", ",", "# no encontre nada para cargar...", "'rango'", ":", "(", "None", ",", "None", ")", ",", "# no nos interesa este campo, solo por compatibilidad", "'extent'", ":", "extent", "# extent, necesario para cada mapa layer_raster_band", "}", "else", ":", "# Necesitamos info estructural especifica si es otro formato...", "pass", "# Lamentablemente hay inconsistencias en algunos archivos analizados con respecto al extent:", "# a veces el de la capa no coincide con el de los subdatasets. Tomamos el primero, que se utilizara para renderizar", "if", "len", "(", "subdatasets", ")", ">", "0", ":", "extent_capa", "=", "variables_detectadas", "[", "subdatasets", "[", "0", "]", "[", "'identificador'", "]", "]", "[", "'extent'", "]", "try", ":", "# los casos analizados NO incluyen informacion de la proyeccion en bandas, solo coordenadas que parecen ser 4326, como no hay garantia intento reproyectarlo", "extent_capa_4326", "=", "extentConvert", "(", "extent_capa", ",", "'EPSG:4326'", ",", "'EPSG:4326'", ")", "except", ":", "pass", "# construimos la respuesta", "return", "{", "'driver_short_name'", ":", "raster", ".", "GetDriver", "(", ")", ".", "ShortName", ",", "'driver_long_name'", ":", "raster", ".", "GetDriver", "(", ")", ".", "LongName", ",", "'raster_count'", ":", "raster", ".", "RasterCount", ",", "'subdataset_count'", ":", "len", "(", "raster", ".", "GetSubDatasets", "(", ")", ")", ",", "'srid'", ":", "srid", ",", "# puede ser None", "'extent_capa'", ":", "extent_capa", ",", "'extent_capa_4326'", ":", "extent_capa_4326", ",", "'metadata_json'", ":", "{", "'gdalinfo'", ":", "metadata_gdalinfo_json", ",", "'variables_detectadas'", ":", "variables_detectadas", ",", "'subdatasets'", ":", "subdatasets", ",", "}", ",", "'proyeccion_proj4'", ":", "proj", ".", "ExportToProj4", "(", ")", ",", "'size_height'", ":", "raster", ".", "RasterYSize", ",", "'size_width'", ":", "raster", ".", "RasterXSize", ",", "}" ]
[ 320, 0 ]
[ 459, 5 ]
null
python
es
['es', 'es', 'es']
True
true
null
contar
(frase: str)
return { "vocales": vocales, "consonantes": consonantes, "digitos": digitos }
Cuenta vocales, consonantes y digitos de una frase. :param frase: La frase a contar. :frase type: str :return: Un diccionario con las cantidades de vocales, consonantes y digitos. :rtype: Dict[str, int]
Cuenta vocales, consonantes y digitos de una frase.
def contar(frase: str) -> Dict[str, int]: """Cuenta vocales, consonantes y digitos de una frase. :param frase: La frase a contar. :frase type: str :return: Un diccionario con las cantidades de vocales, consonantes y digitos. :rtype: Dict[str, int] """ frase: str = frase.lower() vocales: int = 0 consonantes: int = 0 digitos: int = 0 for caracter in frase: if caracter in "aeiou": vocales += 1 elif caracter in "bcdfghjklmnñpqrstvwxyz": consonantes += 1 elif caracter in "0123456789": digitos += 1 return { "vocales": vocales, "consonantes": consonantes, "digitos": digitos }
[ "def", "contar", "(", "frase", ":", "str", ")", "->", "Dict", "[", "str", ",", "int", "]", ":", "frase", ":", "str", "=", "frase", ".", "lower", "(", ")", "vocales", ":", "int", "=", "0", "consonantes", ":", "int", "=", "0", "digitos", ":", "int", "=", "0", "for", "caracter", "in", "frase", ":", "if", "caracter", "in", "\"aeiou\"", ":", "vocales", "+=", "1", "elif", "caracter", "in", "\"bcdfghjklmnñpqrstvwxyz\":", "", "consonantes", "+=", "1", "elif", "caracter", "in", "\"0123456789\"", ":", "digitos", "+=", "1", "return", "{", "\"vocales\"", ":", "vocales", ",", "\"consonantes\"", ":", "consonantes", ",", "\"digitos\"", ":", "digitos", "}" ]
[ 30, 0 ]
[ 52, 5 ]
null
python
es
['es', 'es', 'es']
True
true
null
TrackingVideo.set_property
(self, property_: TrackingVideoProperty, value: Any)
Establece una propiedad a la creación del vídeo de seguimiento. :param property_: propiedad para añadir. :param value: valor de la propiedad. :return: None.
Establece una propiedad a la creación del vídeo de seguimiento.
def set_property(self, property_: TrackingVideoProperty, value: Any) -> None: """Establece una propiedad a la creación del vídeo de seguimiento. :param property_: propiedad para añadir. :param value: valor de la propiedad. :return: None. """ self._properties[property_] = value
[ "def", "set_property", "(", "self", ",", "property_", ":", "TrackingVideoProperty", ",", "value", ":", "Any", ")", "->", "None", ":", "self", ".", "_properties", "[", "property_", "]", "=", "value" ]
[ 350, 4 ]
[ 357, 43 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instrucciones_funcion_floor
(t)
lista_funciones : FLOOR PARIZQ funcion_math_parametro PARDER
lista_funciones : FLOOR PARIZQ funcion_math_parametro PARDER
def p_instrucciones_funcion_floor(t) : 'lista_funciones : FLOOR PARIZQ funcion_math_parametro PARDER'
[ "def", "p_instrucciones_funcion_floor", "(", "t", ")", ":" ]
[ 906, 0 ]
[ 907, 69 ]
null
python
es
['es', 'es', 'es']
True
true
null
check_seq
(seq, pattern)
Revisa si la secuencia es valida usando un patron obtenido de una expresion regular.
Revisa si la secuencia es valida usando un patron obtenido de una expresion regular.
def check_seq(seq, pattern): """Revisa si la secuencia es valida usando un patron obtenido de una expresion regular.""" t_seq = del_gap(seq) if not match(pattern, t_seq): raise Exception(f"Secuencia no valida: '{seq}'")
[ "def", "check_seq", "(", "seq", ",", "pattern", ")", ":", "t_seq", "=", "del_gap", "(", "seq", ")", "if", "not", "match", "(", "pattern", ",", "t_seq", ")", ":", "raise", "Exception", "(", "f\"Secuencia no valida: '{seq}'\"", ")" ]
[ 78, 0 ]
[ 83, 56 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instrucciones_condiciones
(t)
lista_condiciones : condicion
lista_condiciones : condicion
def p_instrucciones_condiciones(t) : 'lista_condiciones : condicion ' t[0] = [t[1]] print("Una condicion")
[ "def", "p_instrucciones_condiciones", "(", "t", ")", ":", "t", "[", "0", "]", "=", "[", "t", "[", "1", "]", "]", "print", "(", "\"Una condicion\"", ")" ]
[ 138, 0 ]
[ 141, 26 ]
null
python
es
['es', 'es', 'es']
True
true
null
Restaurant.open_restaurant
(self)
Muestra mensaje de restaurante abierto
Muestra mensaje de restaurante abierto
def open_restaurant(self): """Muestra mensaje de restaurante abierto""" msg = self.name + " is open. Come on in!" print("\n" + msg)
[ "def", "open_restaurant", "(", "self", ")", ":", "msg", "=", "self", ".", "name", "+", "\" is open. Come on in!\"", "print", "(", "\"\\n\"", "+", "msg", ")" ]
[ 19, 4 ]
[ 22, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
BcraSmlScraperTestCase.test_html_is_not_valid
(self)
Probar que el html no sea valido
Probar que el html no sea valido
def test_html_is_not_valid(self): """Probar que el html no sea valido""" url = "" single_date = date(2019, 3, 4) coins = {} with patch.object( BCRASMLScraper, 'fetch_content', return_value=' ' ): scraper = BCRASMLScraper(url, coins, intermediate_panel_path=None, use_intermediate_panel=False) content = scraper.fetch_content(single_date) soup = BeautifulSoup(content, "html.parser") table = soup.find('table') head = table.find('thead') if table else None body = table.find('tbody') if table else None assert table is None assert head is None assert body is None
[ "def", "test_html_is_not_valid", "(", "self", ")", ":", "url", "=", "\"\"", "single_date", "=", "date", "(", "2019", ",", "3", ",", "4", ")", "coins", "=", "{", "}", "with", "patch", ".", "object", "(", "BCRASMLScraper", ",", "'fetch_content'", ",", "return_value", "=", "' '", ")", ":", "scraper", "=", "BCRASMLScraper", "(", "url", ",", "coins", ",", "intermediate_panel_path", "=", "None", ",", "use_intermediate_panel", "=", "False", ")", "content", "=", "scraper", ".", "fetch_content", "(", "single_date", ")", "soup", "=", "BeautifulSoup", "(", "content", ",", "\"html.parser\"", ")", "table", "=", "soup", ".", "find", "(", "'table'", ")", "head", "=", "table", ".", "find", "(", "'thead'", ")", "if", "table", "else", "None", "body", "=", "table", ".", "find", "(", "'tbody'", ")", "if", "table", "else", "None", "assert", "table", "is", "None", "assert", "head", "is", "None", "assert", "body", "is", "None" ]
[ 56, 4 ]
[ 78, 31 ]
null
python
es
['es', 'es', 'es']
True
true
null
cuad_pmedio_datos
(a, b, f=None, y0=None)
return aprox
Implementación de la regla del punto medio Parameters ---------- a: float Límite inferior del intervalo b: 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. Returns ------- aprox: Aproximación de la integral por la regla del punto medio Notes ----- Este código es parte del curso "Computación", Famaf
Implementación de la regla del punto medio Parameters ---------- a: float Límite inferior del intervalo b: 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. Returns ------- aprox: Aproximación de la integral por la regla del punto medio Notes ----- Este código es parte del curso "Computación", Famaf
def cuad_pmedio_datos(a, b, f=None, y0=None): """Implementación de la regla del punto medio Parameters ---------- a: float Límite inferior del intervalo b: 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. Returns ------- aprox: Aproximación de la integral por la regla del punto medio Notes ----- Este código es parte del curso "Computación", Famaf """ if a > b: raise ValueError("Oops! Debe ser a<b") x0 = (a+b)/2 if (f is None) and (y0 is not None): aprox = x0*y0 elif (f is not None) and (y0 is None): try: h = f(x0) except: print(('Error: no fue posible calcular la función' ' Si desea ingresar un dato use y0=')) aprox = h*(b-a) else: raise ValueError("Debe ingresar la función o los datos!") return aprox
[ "def", "cuad_pmedio_datos", "(", "a", ",", "b", ",", "f", "=", "None", ",", "y0", "=", "None", ")", ":", "if", "a", ">", "b", ":", "raise", "ValueError", "(", "\"Oops! Debe ser a<b\"", ")", "x0", "=", "(", "a", "+", "b", ")", "/", "2", "if", "(", "f", "is", "None", ")", "and", "(", "y0", "is", "not", "None", ")", ":", "aprox", "=", "x0", "*", "y0", "elif", "(", "f", "is", "not", "None", ")", "and", "(", "y0", "is", "None", ")", ":", "try", ":", "h", "=", "f", "(", "x0", ")", "except", ":", "print", "(", "(", "'Error: no fue posible calcular la función'", "' Si desea ingresar un dato use y0='", ")", ")", "aprox", "=", "h", "*", "(", "b", "-", "a", ")", "else", ":", "raise", "ValueError", "(", "\"Debe ingresar la función o los datos!\")", " ", "return", "aprox" ]
[ 120, 0 ]
[ 159, 16 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_cuerpo_createTable
(t)
cuerpo_createTable_lista : cuerpo_createTable
cuerpo_createTable_lista : cuerpo_createTable
def p_cuerpo_createTable(t): ' cuerpo_createTable_lista : cuerpo_createTable'
[ "def", "p_cuerpo_createTable", "(", "t", ")", ":" ]
[ 619, 0 ]
[ 620, 52 ]
null
python
es
['es', 'es', 'es']
True
true
null
DominioTSP.texto
(self, sol)
return formato_legible
Construye una representación en hilera legible por humanos de la solución con el fin de reportar resultados al usuario final. La hilera cumple con el siguiente formato: Nombre ciudad inicio -> Nombre ciudad 1 -> ... -> Nombre ciudad n -> Nombre ciudad inicio Entradas: sol (list) Solución a representar como texto legible Salidas: (str) Hilera en el formato mencionado anteriormente.
Construye una representación en hilera legible por humanos de la solución con el fin de reportar resultados al usuario final.
def texto(self, sol): """Construye una representación en hilera legible por humanos de la solución con el fin de reportar resultados al usuario final. La hilera cumple con el siguiente formato: Nombre ciudad inicio -> Nombre ciudad 1 -> ... -> Nombre ciudad n -> Nombre ciudad inicio Entradas: sol (list) Solución a representar como texto legible Salidas: (str) Hilera en el formato mencionado anteriormente. """ formato_legible = self.nombre_ciudad_inicio + " -> " for ciudad in sol: nombre_actual = self.ciudades[ciudad]['km/min'] formato_legible += nombre_actual + " -> " formato_legible += self.nombre_ciudad_inicio return formato_legible
[ "def", "texto", "(", "self", ",", "sol", ")", ":", "formato_legible", "=", "self", ".", "nombre_ciudad_inicio", "+", "\" -> \"", "for", "ciudad", "in", "sol", ":", "nombre_actual", "=", "self", ".", "ciudades", "[", "ciudad", "]", "[", "'km/min'", "]", "formato_legible", "+=", "nombre_actual", "+", "\" -> \"", "formato_legible", "+=", "self", ".", "nombre_ciudad_inicio", "return", "formato_legible" ]
[ 83, 4 ]
[ 102, 30 ]
null
python
es
['es', 'es', 'es']
True
true
null
cambiar_estatus_curso
()
return redirect(url_for("curso", course_code=request.args.get("curse")))
Actualiza el estatus de un curso.
Actualiza el estatus de un curso.
def cambiar_estatus_curso(): """Actualiza el estatus de un curso.""" cambia_estado_curso_por_id( id_curso=request.args.get("curse"), nuevo_estado=request.args.get("status"), ) return redirect(url_for("curso", course_code=request.args.get("curse")))
[ "def", "cambiar_estatus_curso", "(", ")", ":", "cambia_estado_curso_por_id", "(", "id_curso", "=", "request", ".", "args", ".", "get", "(", "\"curse\"", ")", ",", "nuevo_estado", "=", "request", ".", "args", ".", "get", "(", "\"status\"", ")", ",", ")", "return", "redirect", "(", "url_for", "(", "\"curso\"", ",", "course_code", "=", "request", ".", "args", ".", "get", "(", "\"curse\"", ")", ")", ")" ]
[ 873, 0 ]
[ 879, 76 ]
null
python
es
['es', 'es', 'es']
True
true
null
api_data_processor
(data, user_type, user_limit=0)
return data_set
**Preprocesa los datos de elasticsearch para la api** Recibe la respuesta de elasticsearch en crudo y organiza los datos para dar una respuesta más ordenada dependiendo del tipo de usuario. :param data: Respuesta en crudo de elasticsearch :type: dict :param user_type: Tipo de usuario que hacer la peticion a la api :type: str :param user_limit: Limite de resultados a mostrar en la api :type: int :return: Diccionario con los datos organizados para la respuesta de la api :rtype: dict
**Preprocesa los datos de elasticsearch para la api**
def api_data_processor(data, user_type, user_limit=0): """**Preprocesa los datos de elasticsearch para la api** Recibe la respuesta de elasticsearch en crudo y organiza los datos para dar una respuesta más ordenada dependiendo del tipo de usuario. :param data: Respuesta en crudo de elasticsearch :type: dict :param user_type: Tipo de usuario que hacer la peticion a la api :type: str :param user_limit: Limite de resultados a mostrar en la api :type: int :return: Diccionario con los datos organizados para la respuesta de la api :rtype: dict """ data_set = [] result = {} hits = data["hits"] if not user_limit else data["hits"][:user_limit] for hit in hits: fields = hit.keys() result["document_name"] = hit["_source"]["document_name"] result["pdf_file"] = hit["_source"]["pdf_file"] if "variant" in hit["_source"].keys() and user_type != "anon": result["variant"] = hit['_source']['variant'] else: if user_type != "anon": result["variant"] = "" if "highlight" in fields and user_type != "anon": result["highlight"] = hit["highlight"] else: if user_type != "anon": result["highlight"] = "" result["l1"] = hit["_source"]["l1"] result["l2"] = hit["_source"]["l2"] data_set.append(result) result = {} return data_set
[ "def", "api_data_processor", "(", "data", ",", "user_type", ",", "user_limit", "=", "0", ")", ":", "data_set", "=", "[", "]", "result", "=", "{", "}", "hits", "=", "data", "[", "\"hits\"", "]", "if", "not", "user_limit", "else", "data", "[", "\"hits\"", "]", "[", ":", "user_limit", "]", "for", "hit", "in", "hits", ":", "fields", "=", "hit", ".", "keys", "(", ")", "result", "[", "\"document_name\"", "]", "=", "hit", "[", "\"_source\"", "]", "[", "\"document_name\"", "]", "result", "[", "\"pdf_file\"", "]", "=", "hit", "[", "\"_source\"", "]", "[", "\"pdf_file\"", "]", "if", "\"variant\"", "in", "hit", "[", "\"_source\"", "]", ".", "keys", "(", ")", "and", "user_type", "!=", "\"anon\"", ":", "result", "[", "\"variant\"", "]", "=", "hit", "[", "'_source'", "]", "[", "'variant'", "]", "else", ":", "if", "user_type", "!=", "\"anon\"", ":", "result", "[", "\"variant\"", "]", "=", "\"\"", "if", "\"highlight\"", "in", "fields", "and", "user_type", "!=", "\"anon\"", ":", "result", "[", "\"highlight\"", "]", "=", "hit", "[", "\"highlight\"", "]", "else", ":", "if", "user_type", "!=", "\"anon\"", ":", "result", "[", "\"highlight\"", "]", "=", "\"\"", "result", "[", "\"l1\"", "]", "=", "hit", "[", "\"_source\"", "]", "[", "\"l1\"", "]", "result", "[", "\"l2\"", "]", "=", "hit", "[", "\"_source\"", "]", "[", "\"l2\"", "]", "data_set", ".", "append", "(", "result", ")", "result", "=", "{", "}", "return", "data_set" ]
[ 0, 0 ]
[ 37, 19 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_init
(t)
inicio : sentencias
inicio : sentencias
def p_init(t): 'inicio : sentencias' print("Lectura Finalizada") t[0] = t[1]
[ "def", "p_init", "(", "t", ")", ":", "print", "(", "\"Lectura Finalizada\"", ")", "t", "[", "0", "]", "=", "t", "[", "1", "]" ]
[ 432, 0 ]
[ 435, 15 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instrucciones_lista2
(t)
instrucciones : instruccion
instrucciones : instruccion
def p_instrucciones_lista2(t): 'instrucciones : instruccion ' t[0] = [t[1]]
[ "def", "p_instrucciones_lista2", "(", "t", ")", ":", "t", "[", "0", "]", "=", "[", "t", "[", "1", "]", "]" ]
[ 61, 0 ]
[ 63, 17 ]
null
python
es
['es', 'es', 'es']
True
true
null
CubeShell.do_mezclar_todos
(self, args)
Realiza todos los movimientos posibles dado un cubo NxN
Realiza todos los movimientos posibles dado un cubo NxN
def do_mezclar_todos(self, args): '''Realiza todos los movimientos posibles dado un cubo NxN''' movimientos = ['B', 'b', 'D', 'd', 'L', 'l', ] cubo_actual = Objeto_Cubo(utils.jsonRead(ruta_json)) for tipo in movimientos: for x in range(0, cubo_actual.getCuboSize()): cubo_actual = Objeto_Cubo(utils.jsonRead(ruta_json)) movim = (tipo, x) utils.mezclarCuboTupla(movim, cubo_actual)
[ "def", "do_mezclar_todos", "(", "self", ",", "args", ")", ":", "movimientos", "=", "[", "'B'", ",", "'b'", ",", "'D'", ",", "'d'", ",", "'L'", ",", "'l'", ",", "]", "cubo_actual", "=", "Objeto_Cubo", "(", "utils", ".", "jsonRead", "(", "ruta_json", ")", ")", "for", "tipo", "in", "movimientos", ":", "for", "x", "in", "range", "(", "0", ",", "cubo_actual", ".", "getCuboSize", "(", ")", ")", ":", "cubo_actual", "=", "Objeto_Cubo", "(", "utils", ".", "jsonRead", "(", "ruta_json", ")", ")", "movim", "=", "(", "tipo", ",", "x", ")", "utils", ".", "mezclarCuboTupla", "(", "movim", ",", "cubo_actual", ")" ]
[ 58, 4 ]
[ 66, 58 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_funciones_math1
(t)
funciones_math1 : abs | cbrt | ceil | celing | degrees | exp | factorial | floor | ln | log | radians | round | sign | sqrt
funciones_math1 : abs | cbrt | ceil | celing | degrees | exp | factorial | floor | ln | log | radians | round | sign | sqrt
def p_funciones_math1(t): '''funciones_math1 : abs | cbrt | ceil | celing | degrees | exp | factorial | floor | ln | log | radians | round | sign | sqrt''' node = grammer.nodoDireccion('funciones_math') node2 = grammer.nodoDireccion(t[1]) node.agregar(node2) t[0] = node
[ "def", "p_funciones_math1", "(", "t", ")", ":", "node", "=", "grammer", ".", "nodoDireccion", "(", "'funciones_math'", ")", "node2", "=", "grammer", ".", "nodoDireccion", "(", "t", "[", "1", "]", ")", "node", ".", "agregar", "(", "node2", ")", "t", "[", "0", "]", "=", "node" ]
[ 1988, 0 ]
[ 2006, 15 ]
null
python
es
['es', 'es', 'es']
True
true
null
informar_nombres
(lista)
return lista_sin_rep
genera una lista de nombres sin que aparezcan repeticiones en caso de que las hubiera
genera una lista de nombres sin que aparezcan repeticiones en caso de que las hubiera
def informar_nombres (lista): """genera una lista de nombres sin que aparezcan repeticiones en caso de que las hubiera""" #esta lista se podría generar de forma más sencilla aplicando la funcion set () pero #los nombres aparecerían en orden aleatorio lista_sin_rep = [] for i in lista: if i not in lista_sin_rep: lista_sin_rep.append(i) else: continue return lista_sin_rep
[ "def", "informar_nombres", "(", "lista", ")", ":", "#esta lista se podría generar de forma más sencilla aplicando la funcion set () pero ", "#los nombres aparecerían en orden aleatorio", "lista_sin_rep", "=", "[", "]", "for", "i", "in", "lista", ":", "if", "i", "not", "in", "lista_sin_rep", ":", "lista_sin_rep", ".", "append", "(", "i", ")", "else", ":", "continue", "return", "lista_sin_rep" ]
[ 62, 0 ]
[ 72, 24 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_statement
(t)
statement : LLAVE_ABRE instrucciones LLAVE_CIERRA | LLAVE_ABRE LLAVE_CIERRA
statement : LLAVE_ABRE instrucciones LLAVE_CIERRA | LLAVE_ABRE LLAVE_CIERRA
def p_statement(t): '''statement : LLAVE_ABRE instrucciones LLAVE_CIERRA | LLAVE_ABRE LLAVE_CIERRA''' if isinstance(t[2], list) : t[0] = statement_(t[2], t.lineno(1), t.lexpos(1)) else: t[0] = statement_([], t.lineno(1), t.lexpos(1))
[ "def", "p_statement", "(", "t", ")", ":", "if", "isinstance", "(", "t", "[", "2", "]", ",", "list", ")", ":", "t", "[", "0", "]", "=", "statement_", "(", "t", "[", "2", "]", ",", "t", ".", "lineno", "(", "1", ")", ",", "t", ".", "lexpos", "(", "1", ")", ")", "else", ":", "t", "[", "0", "]", "=", "statement_", "(", "[", "]", ",", "t", ".", "lineno", "(", "1", ")", ",", "t", ".", "lexpos", "(", "1", ")", ")" ]
[ 193, 0 ]
[ 197, 57 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_culquieridentificador
(t)
cualquieridentificador : ID | ID PUNTO ID
cualquieridentificador : ID | ID PUNTO ID
def p_culquieridentificador (t): '''cualquieridentificador : ID | ID PUNTO ID''' t[0] = getIdentificador(t)
[ "def", "p_culquieridentificador", "(", "t", ")", ":", "t", "[", "0", "]", "=", "getIdentificador", "(", "t", ")" ]
[ 1187, 0 ]
[ 1190, 30 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instrucciones_funcion_avg
(t)
funciones_math_esenciales : AVG PARIZQ lista_funciones_math_esenciales PARDER parametro | AVG PARIZQ lista_funciones_math_esenciales PARDER
funciones_math_esenciales : AVG PARIZQ lista_funciones_math_esenciales PARDER parametro | AVG PARIZQ lista_funciones_math_esenciales PARDER
def p_instrucciones_funcion_avg(t): '''funciones_math_esenciales : AVG PARIZQ lista_funciones_math_esenciales PARDER parametro | AVG PARIZQ lista_funciones_math_esenciales PARDER'''
[ "def", "p_instrucciones_funcion_avg", "(", "t", ")", ":" ]
[ 859, 0 ]
[ 861, 90 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_declaracion_funcion
(t)
declaraciones : declaraciones PTCOMA parametro | parametro
declaraciones : declaraciones PTCOMA parametro | parametro
def p_declaracion_funcion(t): '''declaraciones : declaraciones PTCOMA parametro | parametro''' if len(t)==4: t[1].append(t[3]) t[0] = t[1] else: t[0] = [t[1]]
[ "def", "p_declaracion_funcion", "(", "t", ")", ":", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "1", "]", ".", "append", "(", "t", "[", "3", "]", ")", "t", "[", "0", "]", "=", "t", "[", "1", "]", "else", ":", "t", "[", "0", "]", "=", "[", "t", "[", "1", "]", "]" ]
[ 1493, 0 ]
[ 1500, 23 ]
null
python
es
['es', 'es', 'es']
True
true
null
parse_notices
(link, today)
Función para parsear el html. Recibe el link de lugar y la fecha para crear la carpeta
Función para parsear el html. Recibe el link de lugar y la fecha para crear la carpeta
def parse_notices(link, today): ''' Función para parsear el html. Recibe el link de lugar y la fecha para crear la carpeta''' try: response = requests.get(link) if response.status_code == 200: # Traigo el docuemnto html de la noticia. notice = response.content.decode('utf-8') parsed = html.fromstring(notice) #Quiero traer el título, el cuerpo y el resumen, hago una validación # try -except, estoy haciendolo para los índices de la lista. # Pueden haber noticias con nodos faltantes por lo que arrojará un error try: #Traemos el primer elemento de la lista. title = parsed.xpath(XPATH_TITLE)[0] print(title) # No es deseable tener comillas en los títulos porque presentan un error en OS. # Para solucionar esto, hacemos uso de que title es un str y del metodo replace() title = title.replace('\"', '') summary = parsed.xpath(XPATH_SUMMARY)[0] body = parsed.xpath(XPATH_BODY) except IndexError: return # Guardamos en un archivo # with es un manejador contextual. Si algo sucede y el script se cierra, mantiene las cosas # de manera segura y así no se corrompe el archivo. with open(f'{today}/{title}.txt', 'w', encoding='utf-8') as f: f.write(title) f.write('\n\n') f.write(summary) f.write('\n\n') for p in body: f.write(p) f.write('\n') else: raise ValueError(f'Error: {response.status_code}') except ValueError as ve: print(ve)
[ "def", "parse_notices", "(", "link", ",", "today", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "link", ")", "if", "response", ".", "status_code", "==", "200", ":", "# Traigo el docuemnto html de la noticia.", "notice", "=", "response", ".", "content", ".", "decode", "(", "'utf-8'", ")", "parsed", "=", "html", ".", "fromstring", "(", "notice", ")", "#Quiero traer el título, el cuerpo y el resumen, hago una validación", "# try -except, estoy haciendolo para los índices de la lista.", "# Pueden haber noticias con nodos faltantes por lo que arrojará un error", "try", ":", "#Traemos el primer elemento de la lista.", "title", "=", "parsed", ".", "xpath", "(", "XPATH_TITLE", ")", "[", "0", "]", "print", "(", "title", ")", "# No es deseable tener comillas en los títulos porque presentan un error en OS.", "# Para solucionar esto, hacemos uso de que title es un str y del metodo replace()", "title", "=", "title", ".", "replace", "(", "'\\\"'", ",", "''", ")", "summary", "=", "parsed", ".", "xpath", "(", "XPATH_SUMMARY", ")", "[", "0", "]", "body", "=", "parsed", ".", "xpath", "(", "XPATH_BODY", ")", "except", "IndexError", ":", "return", "# Guardamos en un archivo", "# with es un manejador contextual. Si algo sucede y el script se cierra, mantiene las cosas", "# de manera segura y así no se corrompe el archivo.", "with", "open", "(", "f'{today}/{title}.txt'", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "title", ")", "f", ".", "write", "(", "'\\n\\n'", ")", "f", ".", "write", "(", "summary", ")", "f", ".", "write", "(", "'\\n\\n'", ")", "for", "p", "in", "body", ":", "f", ".", "write", "(", "p", ")", "f", ".", "write", "(", "'\\n'", ")", "else", ":", "raise", "ValueError", "(", "f'Error: {response.status_code}'", ")", "except", "ValueError", "as", "ve", ":", "print", "(", "ve", ")" ]
[ 16, 0 ]
[ 55, 17 ]
null
python
es
['es', 'es', 'es']
True
true
null
Funcion.ejecutar
(self, ent)
ejecucion de la definicion de la funcion
ejecucion de la definicion de la funcion
def ejecutar(self, ent): 'ejecucion de la definicion de la funcion' simbolo = Simbolo(self.tipo, '_f'+self.nombre, [self.params,self.instrucciones], -1) s = ent.nuevoSimbolo(simbolo) if s!='ok': variables.consola.insert(INSERT,'La funcion '+self.nombre+' no se pudo crear porque ya existe\n')
[ "def", "ejecutar", "(", "self", ",", "ent", ")", ":", "simbolo", "=", "Simbolo", "(", "self", ".", "tipo", ",", "'_f'", "+", "self", ".", "nombre", ",", "[", "self", ".", "params", ",", "self", ".", "instrucciones", "]", ",", "-", "1", ")", "s", "=", "ent", ".", "nuevoSimbolo", "(", "simbolo", ")", "if", "s", "!=", "'ok'", ":", "variables", ".", "consola", ".", "insert", "(", "INSERT", ",", "'La funcion '", "+", "self", ".", "nombre", "+", "' no se pudo crear porque ya existe\\n'", ")" ]
[ 15, 4 ]
[ 20, 109 ]
null
python
es
['es', 'es', 'es']
True
true
null
menor_temperatura
(dict_: Dict[str, List[int]])
return {k: min(v) for k, v in dict_.items()}
Determina el menor registro de cada región. :param dict_: Diccionario con los datos de las regiones. :dict_ type: Dict[str, List[int]] :return: Tupla con el nombre de la región y el menor registro. :rtype: Tuple[str, int]
Determina el menor registro de cada región. :param dict_: Diccionario con los datos de las regiones. :dict_ type: Dict[str, List[int]] :return: Tupla con el nombre de la región y el menor registro. :rtype: Tuple[str, int]
def menor_temperatura(dict_: Dict[str, List[int]]) -> Tuple[str, int]: """Determina el menor registro de cada región. :param dict_: Diccionario con los datos de las regiones. :dict_ type: Dict[str, List[int]] :return: Tupla con el nombre de la región y el menor registro. :rtype: Tuple[str, int] """ return {k: min(v) for k, v in dict_.items()}
[ "def", "menor_temperatura", "(", "dict_", ":", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "return", "{", "k", ":", "min", "(", "v", ")", "for", "k", ",", "v", "in", "dict_", ".", "items", "(", ")", "}" ]
[ 41, 0 ]
[ 49, 48 ]
null
python
es
['es', 'es', 'es']
True
true
null
ManejadorDePermisos.permiso_de_capa
(user, capa)
Devuelve alguno de estos casos en orden: owner|superuser|(read|write)|None
Devuelve alguno de estos casos en orden: owner|superuser|(read|write)|None
def permiso_de_capa(user, capa): """ Devuelve alguno de estos casos en orden: owner|superuser|(read|write)|None""" if type(user) in (str,unicode): try: user = User.objects.get(username=user) except: return None if type(capa) in (str,unicode): try: capa = Capa.objects.get(id_capa=capa) except: return None if capa.owner==user: return 'owner' if user.is_superuser: return 'superuser' try: p=PermisoDeCapa.objects.get(user=user, capa=capa) return p.permiso # si existe, esto devuelve read o write except: # si no existe, verificamos si hay algun grupo write, y sino, luego algun grupo read for g in user.groups.all(): if len(PermisoDeCapaPorGrupo.objects.filter(group=g, capa=capa, permiso='write')) > 0: return 'write' for g in user.groups.all(): if len(PermisoDeCapaPorGrupo.objects.filter(group=g, capa=capa, permiso='read')) > 0: return 'read' if capa.wxs_publico: return 'read' return None
[ "def", "permiso_de_capa", "(", "user", ",", "capa", ")", ":", "if", "type", "(", "user", ")", "in", "(", "str", ",", "unicode", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "user", ")", "except", ":", "return", "None", "if", "type", "(", "capa", ")", "in", "(", "str", ",", "unicode", ")", ":", "try", ":", "capa", "=", "Capa", ".", "objects", ".", "get", "(", "id_capa", "=", "capa", ")", "except", ":", "return", "None", "if", "capa", ".", "owner", "==", "user", ":", "return", "'owner'", "if", "user", ".", "is_superuser", ":", "return", "'superuser'", "try", ":", "p", "=", "PermisoDeCapa", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "capa", "=", "capa", ")", "return", "p", ".", "permiso", "# si existe, esto devuelve read o write", "except", ":", "# si no existe, verificamos si hay algun grupo write, y sino, luego algun grupo read", "for", "g", "in", "user", ".", "groups", ".", "all", "(", ")", ":", "if", "len", "(", "PermisoDeCapaPorGrupo", ".", "objects", ".", "filter", "(", "group", "=", "g", ",", "capa", "=", "capa", ",", "permiso", "=", "'write'", ")", ")", ">", "0", ":", "return", "'write'", "for", "g", "in", "user", ".", "groups", ".", "all", "(", ")", ":", "if", "len", "(", "PermisoDeCapaPorGrupo", ".", "objects", ".", "filter", "(", "group", "=", "g", ",", "capa", "=", "capa", ",", "permiso", "=", "'read'", ")", ")", ">", "0", ":", "return", "'read'", "if", "capa", ".", "wxs_publico", ":", "return", "'read'", "return", "None" ]
[ 126, 4 ]
[ 155, 23 ]
null
python
es
['es', 'es', 'es']
True
true
null
DataCleaner.reemplazar
(self, field, replacements, sufix=None, keep_original=False, inplace=False)
return series
Reemplaza listas de valores por un nuevo valor. Args: field (str): Campo a limpiar replacements (dict): {"new_value": ["old_value1", "old_value2"]} Returns: pandas.Series: Serie de strings limpios
Reemplaza listas de valores por un nuevo valor.
def reemplazar(self, field, replacements, sufix=None, keep_original=False, inplace=False): """Reemplaza listas de valores por un nuevo valor. Args: field (str): Campo a limpiar replacements (dict): {"new_value": ["old_value1", "old_value2"]} Returns: pandas.Series: Serie de strings limpios """ sufix = sufix or self.DEFAULT_SUFIX field = self._normalize_field(field) series = self.df[field] for new_value, old_values in replacements.items(): series = series.replace(old_values, new_value) if inplace: self._update_series(field=field, sufix=sufix, keep_original=keep_original, new_series=series) return series
[ "def", "reemplazar", "(", "self", ",", "field", ",", "replacements", ",", "sufix", "=", "None", ",", "keep_original", "=", "False", ",", "inplace", "=", "False", ")", ":", "sufix", "=", "sufix", "or", "self", ".", "DEFAULT_SUFIX", "field", "=", "self", ".", "_normalize_field", "(", "field", ")", "series", "=", "self", ".", "df", "[", "field", "]", "for", "new_value", ",", "old_values", "in", "replacements", ".", "items", "(", ")", ":", "series", "=", "series", ".", "replace", "(", "old_values", ",", "new_value", ")", "if", "inplace", ":", "self", ".", "_update_series", "(", "field", "=", "field", ",", "sufix", "=", "sufix", ",", "keep_original", "=", "keep_original", ",", "new_series", "=", "series", ")", "return", "series" ]
[ 444, 4 ]
[ 467, 21 ]
null
python
es
['es', 'es', 'es']
True
true
null
UserViewSet.list
(self, request)
return Response(data)
Lista los usuarios según el tipo de usuario: Banquero: se muestran los montos exactos de los jugadores Jugadores: se muestran los montos aproximados de los jugadores
Lista los usuarios según el tipo de usuario: Banquero: se muestran los montos exactos de los jugadores Jugadores: se muestran los montos aproximados de los jugadores
def list(self, request): """Lista los usuarios según el tipo de usuario: Banquero: se muestran los montos exactos de los jugadores Jugadores: se muestran los montos aproximados de los jugadores""" user = self.request.user if user.userType.name == 'Banquero': self.queryset = User.objects.all().filter(status='A',room=user.room).exclude(id=user.id).order_by('id') list_amounts = User.objects.all().filter(status='A',room=user.room).exclude(id=user.id).values_list('amount',flat=True).order_by('id') serializer = UserListSerializer(self.queryset, many=True) data={ 'users':serializer.data, 'amounts':list_amounts } else: self.queryset = User.objects.all().filter(status='A',room=user.room).exclude(userType__name='Banquero').exclude(id=user.id).order_by('id') list_amounts = User.objects.all().filter(status='A',room=user.room).exclude(userType__name='Banquero').exclude(id=user.id).values_list('amount',flat=True).order_by('id') # def round_down(x): # return int(math.floor(x / 100.0)) * 100 # new_amounts=[] # for list in list_amounts: # a = round_down(list) # new_amounts.append(a) serializer = UserListSerializer(self.queryset, many=True) data={ 'users': serializer.data, 'round_amounts': list_amounts, 'my_amount': user.amount } return Response(data)
[ "def", "list", "(", "self", ",", "request", ")", ":", "user", "=", "self", ".", "request", ".", "user", "if", "user", ".", "userType", ".", "name", "==", "'Banquero'", ":", "self", ".", "queryset", "=", "User", ".", "objects", ".", "all", "(", ")", ".", "filter", "(", "status", "=", "'A'", ",", "room", "=", "user", ".", "room", ")", ".", "exclude", "(", "id", "=", "user", ".", "id", ")", ".", "order_by", "(", "'id'", ")", "list_amounts", "=", "User", ".", "objects", ".", "all", "(", ")", ".", "filter", "(", "status", "=", "'A'", ",", "room", "=", "user", ".", "room", ")", ".", "exclude", "(", "id", "=", "user", ".", "id", ")", ".", "values_list", "(", "'amount'", ",", "flat", "=", "True", ")", ".", "order_by", "(", "'id'", ")", "serializer", "=", "UserListSerializer", "(", "self", ".", "queryset", ",", "many", "=", "True", ")", "data", "=", "{", "'users'", ":", "serializer", ".", "data", ",", "'amounts'", ":", "list_amounts", "}", "else", ":", "self", ".", "queryset", "=", "User", ".", "objects", ".", "all", "(", ")", ".", "filter", "(", "status", "=", "'A'", ",", "room", "=", "user", ".", "room", ")", ".", "exclude", "(", "userType__name", "=", "'Banquero'", ")", ".", "exclude", "(", "id", "=", "user", ".", "id", ")", ".", "order_by", "(", "'id'", ")", "list_amounts", "=", "User", ".", "objects", ".", "all", "(", ")", ".", "filter", "(", "status", "=", "'A'", ",", "room", "=", "user", ".", "room", ")", ".", "exclude", "(", "userType__name", "=", "'Banquero'", ")", ".", "exclude", "(", "id", "=", "user", ".", "id", ")", ".", "values_list", "(", "'amount'", ",", "flat", "=", "True", ")", ".", "order_by", "(", "'id'", ")", "# def round_down(x):", "# return int(math.floor(x / 100.0)) * 100", "# new_amounts=[]", "# for list in list_amounts:", "# a = round_down(list)", "# new_amounts.append(a) ", "serializer", "=", "UserListSerializer", "(", "self", ".", "queryset", ",", "many", "=", "True", ")", "data", "=", "{", "'users'", ":", "serializer", ".", "data", ",", "'round_amounts'", ":", "list_amounts", ",", "'my_amount'", ":", "user", ".", "amount", "}", "return", "Response", "(", "data", ")" ]
[ 73, 4 ]
[ 103, 29 ]
null
python
es
['es', 'es', 'es']
True
true
null
definir_orden_builtin
(a: str, b: str, c: str)
return ", ".join(sorted([a, b, c], key=str.lower))
Devuelve tres palabras en orden alfabético de izquierda a derecha. :param a: Primera palabra. :a type: str :param b: Segunda palabra. :b type: str :param c: Tercera palabra. :c type: str :return: Las tres palabras en orden alfabético de izquierda a derecha. :rtype: str
Devuelve tres palabras en orden alfabético de izquierda a derecha.
def definir_orden_builtin(a: str, b: str, c: str) -> str: """Devuelve tres palabras en orden alfabético de izquierda a derecha. :param a: Primera palabra. :a type: str :param b: Segunda palabra. :b type: str :param c: Tercera palabra. :c type: str :return: Las tres palabras en orden alfabético de izquierda a derecha. :rtype: str """ return ", ".join(sorted([a, b, c], key=str.lower))
[ "def", "definir_orden_builtin", "(", "a", ":", "str", ",", "b", ":", "str", ",", "c", ":", "str", ")", "->", "str", ":", "return", "\", \"", ".", "join", "(", "sorted", "(", "[", "a", ",", "b", ",", "c", "]", ",", "key", "=", "str", ".", "lower", ")", ")" ]
[ 96, 0 ]
[ 108, 54 ]
null
python
es
['es', 'es', 'es']
True
true
null
TimeSerie.__init__
(self, folder_path, labels:Labels=None, window_size:str="2m", step:str="30s")
El formato de `window_size` y `step` es \d+[smh]
El formato de `window_size` y `step` es \d+[smh]
def __init__(self, folder_path, labels:Labels=None, window_size:str="2m", step:str="30s"): "El formato de `window_size` y `step` es \d+[smh]" "`window_size` representa el tamaño de tiempo en que sera cortada la serie de tiempo" "`step` representa el tamaño de paso que se utiliza al cortar la serie de tiempo" "`freq` es la frecuencia en Hz que tienen las mediciones" self.window_size = self.__process_time(window_size) self.step = self.__process_time(step) self.data = self.__get_internal_data(Path(folder_path)) self.dates = self.__extract_dates(self.data) dates_tmp, data_tmp = zip(*sorted(zip(self.dates, self.data))) self.data = list(data_tmp) self.dates = list(dates_tmp) self.labels = labels if labels: self.label_files =[self.__get_label_files(label['tiempo_inicio'], label['tiempo_final']) for _, label in labels.data.iterrows()] self.windows_x_file = ((3590 - self.window_size) // self.step) + 1
[ "def", "__init__", "(", "self", ",", "folder_path", ",", "labels", ":", "Labels", "=", "None", ",", "window_size", ":", "str", "=", "\"2m\"", ",", "step", ":", "str", "=", "\"30s\"", ")", ":", "\"`window_size` representa el tamaño de tiempo en que sera cortada la serie de tiempo\"", "\"`step` representa el tamaño de paso que se utiliza al cortar la serie de tiempo\"", "\"`freq` es la frecuencia en Hz que tienen las mediciones\"", "self", ".", "window_size", "=", "self", ".", "__process_time", "(", "window_size", ")", "self", ".", "step", "=", "self", ".", "__process_time", "(", "step", ")", "self", ".", "data", "=", "self", ".", "__get_internal_data", "(", "Path", "(", "folder_path", ")", ")", "self", ".", "dates", "=", "self", ".", "__extract_dates", "(", "self", ".", "data", ")", "dates_tmp", ",", "data_tmp", "=", "zip", "(", "*", "sorted", "(", "zip", "(", "self", ".", "dates", ",", "self", ".", "data", ")", ")", ")", "self", ".", "data", "=", "list", "(", "data_tmp", ")", "self", ".", "dates", "=", "list", "(", "dates_tmp", ")", "self", ".", "labels", "=", "labels", "if", "labels", ":", "self", ".", "label_files", "=", "[", "self", ".", "__get_label_files", "(", "label", "[", "'tiempo_inicio'", "]", ",", "label", "[", "'tiempo_final'", "]", ")", "for", "_", ",", "label", "in", "labels", ".", "data", ".", "iterrows", "(", ")", "]", "self", ".", "windows_x_file", "=", "(", "(", "3590", "-", "self", ".", "window_size", ")", "//", "self", ".", "step", ")", "+", "1" ]
[ 230, 4 ]
[ 250, 74 ]
null
python
es
['es', 'es', 'es']
True
true
null
UserViewSet.create
(self, request, *args, **kwargs)
Crea un usuario jugador que solicita entrar en una sala. Devuelve el token y los datos del usuario.
Crea un usuario jugador que solicita entrar en una sala. Devuelve el token y los datos del usuario.
def create(self, request, *args, **kwargs): """Crea un usuario jugador que solicita entrar en una sala. Devuelve el token y los datos del usuario.""" self.permission_classes = [permissions.AllowAny, ] serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) idr = serializer.validated_data['room'] room = Room.objects.get(idRoom=idr) if room.limit < 5: self.perform_create(serializer) headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) data={ 'access_token':token.key, 'user': serializer.data } return Response(data, status=status.HTTP_201_CREATED, headers=headers) else: mensaje={ 'info': 'La sala ya está llena.', } return Response(mensaje)
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "permission_classes", "=", "[", "permissions", ".", "AllowAny", ",", "]", "serializer", "=", "UserSerializer", "(", "data", "=", "request", ".", "data", ")", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", "idr", "=", "serializer", ".", "validated_data", "[", "'room'", "]", "room", "=", "Room", ".", "objects", ".", "get", "(", "idRoom", "=", "idr", ")", "if", "room", ".", "limit", "<", "5", ":", "self", ".", "perform_create", "(", "serializer", ")", "headers", "=", "self", ".", "get_success_headers", "(", "serializer", ".", "data", ")", "token", ",", "created", "=", "Token", ".", "objects", ".", "get_or_create", "(", "user", "=", "serializer", ".", "instance", ")", "data", "=", "{", "'access_token'", ":", "token", ".", "key", ",", "'user'", ":", "serializer", ".", "data", "}", "return", "Response", "(", "data", ",", "status", "=", "status", ".", "HTTP_201_CREATED", ",", "headers", "=", "headers", ")", "else", ":", "mensaje", "=", "{", "'info'", ":", "'La sala ya está llena.',", "", "}", "return", "Response", "(", "mensaje", ")" ]
[ 39, 4 ]
[ 60, 36 ]
null
python
es
['es', 'es', 'es']
True
true
null
BioPortalApi.__get_json
(self, url: str)
return json.loads(opener.open(self.REST_URL + url).read())
lanza una peticion a la api insertando en esta la llave api de la instancia y parseando los resultados en jsons validos
lanza una peticion a la api insertando en esta la llave api de la instancia y parseando los resultados en jsons validos
def __get_json(self, url: str): """lanza una peticion a la api insertando en esta la llave api de la instancia y parseando los resultados en jsons validos """ opener = urllib.request.build_opener() opener.addheaders = [('Authorization', 'apikey token=' + self.API_KEY)] return json.loads(opener.open(self.REST_URL + url).read())
[ "def", "__get_json", "(", "self", ",", "url", ":", "str", ")", ":", "opener", "=", "urllib", ".", "request", ".", "build_opener", "(", ")", "opener", ".", "addheaders", "=", "[", "(", "'Authorization'", ",", "'apikey token='", "+", "self", ".", "API_KEY", ")", "]", "return", "json", ".", "loads", "(", "opener", ".", "open", "(", "self", ".", "REST_URL", "+", "url", ")", ".", "read", "(", ")", ")" ]
[ 20, 4 ]
[ 26, 66 ]
null
python
es
['es', 'es', 'es']
True
true
null
_compute_y
(x, ll)
return np.sqrt(1 - ll ** 2 * (1 - x ** 2))
Computes y.
Computes y.
def _compute_y(x, ll): """Computes y.""" return np.sqrt(1 - ll ** 2 * (1 - x ** 2))
[ "def", "_compute_y", "(", "x", ",", "ll", ")", ":", "return", "np", ".", "sqrt", "(", "1", "-", "ll", "**", "2", "*", "(", "1", "-", "x", "**", "2", ")", ")" ]
[ 280, 0 ]
[ 282, 46 ]
null
python
es
['es', 'es', 'es']
False
true
null
validar_acceso
(usuario_id, acceso)
return clave_validada
Verifica el inicio de sesión del usuario.
Verifica el inicio de sesión del usuario.
def validar_acceso(usuario_id, acceso): """Verifica el inicio de sesión del usuario.""" from bcrypt import checkpw registro = Usuario.query.filter_by(usuario=usuario_id).first() if registro is not None: clave_validada = checkpw(acceso.encode(), registro.acceso) else: clave_validada = False return clave_validada
[ "def", "validar_acceso", "(", "usuario_id", ",", "acceso", ")", ":", "from", "bcrypt", "import", "checkpw", "registro", "=", "Usuario", ".", "query", ".", "filter_by", "(", "usuario", "=", "usuario_id", ")", ".", "first", "(", ")", "if", "registro", "is", "not", "None", ":", "clave_validada", "=", "checkpw", "(", "acceso", ".", "encode", "(", ")", ",", "registro", ".", "acceso", ")", "else", ":", "clave_validada", "=", "False", "return", "clave_validada" ]
[ 293, 0 ]
[ 302, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
en_segundos
(tiempo: str)
return sum([u*t for u, t in zip(unidades, map(int, tiempo.split(":")))])
Convierte un tiempo en segundos :param tiempo: Tiempo expresado en dias:horas:minutos:segundos :tiempo type: str :return: Tiempo en segundos :rtype: int .. Nota:: u: unidad t: tiempo(int) >>> en_segundos('1:0:0:0') 86400 >>> en_segundos('1:0:10:4') 87004 >>> en_segundos('2:12:46:29') 218789
Convierte un tiempo en segundos
def en_segundos(tiempo: str) -> int: """Convierte un tiempo en segundos :param tiempo: Tiempo expresado en dias:horas:minutos:segundos :tiempo type: str :return: Tiempo en segundos :rtype: int .. Nota:: u: unidad t: tiempo(int) >>> en_segundos('1:0:0:0') 86400 >>> en_segundos('1:0:10:4') 87004 >>> en_segundos('2:12:46:29') 218789 """ unidades = [60*60*24, 60*60, 60, 1] return sum([u*t for u, t in zip(unidades, map(int, tiempo.split(":")))])
[ "def", "en_segundos", "(", "tiempo", ":", "str", ")", "->", "int", ":", "unidades", "=", "[", "60", "*", "60", "*", "24", ",", "60", "*", "60", ",", "60", ",", "1", "]", "return", "sum", "(", "[", "u", "*", "t", "for", "u", ",", "t", "in", "zip", "(", "unidades", ",", "map", "(", "int", ",", "tiempo", ".", "split", "(", "\":\"", ")", ")", ")", "]", ")" ]
[ 10, 0 ]
[ 31, 76 ]
null
python
es
['es', 'es', 'es']
True
true
null
ServiceCallback.set_priority
( identificator: int, priority: int, *, only_networks: bool = False, cursor )
Ajusta la prioridad del servicio o los servicios La prioridad es usada para organizar mejor la jerarquía de los servicios, o en pocas palabras, cuando se obtienen todos los servicios, el orden dependerá de la prioridad que tengan éstos. Por ejemplo, si el servicio '/foo' tiene prioridad '2' y '/bar' tiene prioridad '3', este último será obtenido primero, por ende se usará primero. Args: identificator: El identificador del servicio o la red priority: La prioridad del o los servicios only_network: Si es **True** se actualizará la prioridad de todos los servicios que le pertenezcan a un nodo determinado; si es **False** se actualizará solo al servicio especificado.
Ajusta la prioridad del servicio o los servicios La prioridad es usada para organizar mejor la jerarquía de los servicios, o en pocas palabras, cuando se obtienen todos los servicios, el orden dependerá de la prioridad que tengan éstos.
async def set_priority( identificator: int, priority: int, *, only_networks: bool = False, cursor ) -> None: """Ajusta la prioridad del servicio o los servicios La prioridad es usada para organizar mejor la jerarquía de los servicios, o en pocas palabras, cuando se obtienen todos los servicios, el orden dependerá de la prioridad que tengan éstos. Por ejemplo, si el servicio '/foo' tiene prioridad '2' y '/bar' tiene prioridad '3', este último será obtenido primero, por ende se usará primero. Args: identificator: El identificador del servicio o la red priority: La prioridad del o los servicios only_network: Si es **True** se actualizará la prioridad de todos los servicios que le pertenezcan a un nodo determinado; si es **False** se actualizará solo al servicio especificado. """ sql = ["UPDATE services SET priority = %s"] args = [priority] if (only_networks): sql.append("WHERE id_network = %s") else: sql.append("WHERE id_service = %s") args.append(identificator) await cursor.execute( " ".join(sql), args )
[ "async", "def", "set_priority", "(", "identificator", ":", "int", ",", "priority", ":", "int", ",", "*", ",", "only_networks", ":", "bool", "=", "False", ",", "cursor", ")", "->", "None", ":", "sql", "=", "[", "\"UPDATE services SET priority = %s\"", "]", "args", "=", "[", "priority", "]", "if", "(", "only_networks", ")", ":", "sql", ".", "append", "(", "\"WHERE id_network = %s\"", ")", "else", ":", "sql", ".", "append", "(", "\"WHERE id_service = %s\"", ")", "args", ".", "append", "(", "identificator", ")", "await", "cursor", ".", "execute", "(", "\" \"", ".", "join", "(", "sql", ")", ",", "args", ")" ]
[ 610, 4 ]
[ 653, 9 ]
null
python
es
['es', 'es', 'es']
True
true
null
edit
(apiclient: ApiClient, customer_data: Dict[str, Any])
Este servicio permite editar los datos de un cliente
Este servicio permite editar los datos de un cliente
def edit(apiclient: ApiClient, customer_data: Dict[str, Any]) -> Union[Customer, Error]: """Este servicio permite editar los datos de un cliente""" url = f"{apiclient.api_url}/customer/edit" customer = CustomerRequest.from_dict(customer_data) if customer.apiKey is None: customer.apiKey = apiclient.api_key customer.s = apiclient.make_signature(asdict(customer)) logging.debug("Before Request:" + str(customer)) response = apiclient.post(url, asdict(customer)) if response.status_code == 200: return Customer.from_dict(cast(Dict[str, Any], response.json())) if response.status_code == 400: return Error.from_dict(cast(Dict[str, Any], response.json())) if response.status_code == 401: return Error.from_dict(cast(Dict[str, Any], response.json())) else: raise Exception(response=response)
[ "def", "edit", "(", "apiclient", ":", "ApiClient", ",", "customer_data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Union", "[", "Customer", ",", "Error", "]", ":", "url", "=", "f\"{apiclient.api_url}/customer/edit\"", "customer", "=", "CustomerRequest", ".", "from_dict", "(", "customer_data", ")", "if", "customer", ".", "apiKey", "is", "None", ":", "customer", ".", "apiKey", "=", "apiclient", ".", "api_key", "customer", ".", "s", "=", "apiclient", ".", "make_signature", "(", "asdict", "(", "customer", ")", ")", "logging", ".", "debug", "(", "\"Before Request:\"", "+", "str", "(", "customer", ")", ")", "response", "=", "apiclient", ".", "post", "(", "url", ",", "asdict", "(", "customer", ")", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "Customer", ".", "from_dict", "(", "cast", "(", "Dict", "[", "str", ",", "Any", "]", ",", "response", ".", "json", "(", ")", ")", ")", "if", "response", ".", "status_code", "==", "400", ":", "return", "Error", ".", "from_dict", "(", "cast", "(", "Dict", "[", "str", ",", "Any", "]", ",", "response", ".", "json", "(", ")", ")", ")", "if", "response", ".", "status_code", "==", "401", ":", "return", "Error", ".", "from_dict", "(", "cast", "(", "Dict", "[", "str", ",", "Any", "]", ",", "response", ".", "json", "(", ")", ")", ")", "else", ":", "raise", "Exception", "(", "response", "=", "response", ")" ]
[ 53, 0 ]
[ 72, 42 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_sobre_Nombre2
(t)
opcion_sobrenombre : ID
opcion_sobrenombre : ID
def p_sobre_Nombre2(t): ' opcion_sobrenombre : ID ' reporte_bnf.append("<opcion_sobrenombre> ::= ID") t[0] = ExpresionIdentificadorDoble(TIPO_VALOR.IDENTIFICADOR,t[1],None)
[ "def", "p_sobre_Nombre2", "(", "t", ")", ":", "reporte_bnf", ".", "append", "(", "\"<opcion_sobrenombre> ::= ID\"", ")", "t", "[", "0", "]", "=", "ExpresionIdentificadorDoble", "(", "TIPO_VALOR", ".", "IDENTIFICADOR", ",", "t", "[", "1", "]", ",", "None", ")" ]
[ 1873, 0 ]
[ 1876, 74 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instrucciones_comp
(p)
instrucciones_comp : instrucciones_comp list_conditions | instrucciones_comp list_order | instrucciones_comp list_joins | instrucciones_comp group_by | list_conditions | list_order | list_joins | group_by
instrucciones_comp : instrucciones_comp list_conditions | instrucciones_comp list_order | instrucciones_comp list_joins | instrucciones_comp group_by | list_conditions | list_order | list_joins | group_by
def p_instrucciones_comp(p): '''instrucciones_comp : instrucciones_comp list_conditions | instrucciones_comp list_order | instrucciones_comp list_joins | instrucciones_comp group_by | list_conditions | list_order | list_joins | group_by'''
[ "def", "p_instrucciones_comp", "(", "p", ")", ":" ]
[ 453, 0 ]
[ 461, 39 ]
null
python
es
['es', 'es', 'es']
True
true
null
ProteinRecord.one_to_three
(self)
return t_seq
Convierte de codigo de una letra a tres letras
Convierte de codigo de una letra a tres letras
def one_to_three(self): """Convierte de codigo de una letra a tres letras""" # Obtener elementos unicos seq_len = len(self.seq) t_seq = '' # Obtener del diccionario el codigo de tres letras for pos in range(0, seq_len): t_seq += aa_three_let[self.seq[pos]] return t_seq
[ "def", "one_to_three", "(", "self", ")", ":", "# Obtener elementos unicos", "seq_len", "=", "len", "(", "self", ".", "seq", ")", "t_seq", "=", "''", "# Obtener del diccionario el codigo de tres letras", "for", "pos", "in", "range", "(", "0", ",", "seq_len", ")", ":", "t_seq", "+=", "aa_three_let", "[", "self", ".", "seq", "[", "pos", "]", "]", "return", "t_seq" ]
[ 53, 4 ]
[ 61, 20 ]
null
python
es
['es', 'es', 'es']
True
true
null
NanopubRequest.annotationsOf
(self, tag: AnnotationTag)
return filtered
retorna las annotaciones relacionada al tag pasado
retorna las annotaciones relacionada al tag pasado
def annotationsOf(self, tag: AnnotationTag) -> list: """ retorna las annotaciones relacionada al tag pasado """ filtered = list( filter((lambda annotation: self.tagInAnnotation( tag, annotation)), self.annotations) ) return filtered
[ "def", "annotationsOf", "(", "self", ",", "tag", ":", "AnnotationTag", ")", "->", "list", ":", "filtered", "=", "list", "(", "filter", "(", "(", "lambda", "annotation", ":", "self", ".", "tagInAnnotation", "(", "tag", ",", "annotation", ")", ")", ",", "self", ".", "annotations", ")", ")", "return", "filtered" ]
[ 35, 4 ]
[ 41, 23 ]
null
python
es
['es', 'es', 'es']
True
true
null
Simulador.definir_velocidad
(self, mach)
Define la velocidad de la simulación actual en un múltiplo de la velocidad del sonido.
Define la velocidad de la simulación actual en un múltiplo de la velocidad del sonido.
def definir_velocidad(self, mach): """Define la velocidad de la simulación actual en un múltiplo de la velocidad del sonido. """ velocidad = 295.0 self.velocidad = velocidad * mach
[ "def", "definir_velocidad", "(", "self", ",", "mach", ")", ":", "velocidad", "=", "295.0", "self", ".", "velocidad", "=", "velocidad", "*", "mach" ]
[ 21, 4 ]
[ 26, 41 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instruccion20
(t)
instruccion : FUNCIONES
instruccion : FUNCIONES
def p_instruccion20(t): 'instruccion : FUNCIONES' listaBNF.append("INSTRUCCION ::= FUNCIONES") t[0]=t[1]
[ "def", "p_instruccion20", "(", "t", ")", ":", "listaBNF", ".", "append", "(", "\"INSTRUCCION ::= FUNCIONES\"", ")", "t", "[", "0", "]", "=", "t", "[", "1", "]" ]
[ 459, 0 ]
[ 462, 13 ]
null
python
es
['es', 'es', 'es']
True
true
null
EstimationModel.convert_time_from_frames
(self, frames: int)
return frames
Convierte el tiempo desde frames a la unidad especificada al instanciar la clase. :param frames: cantidad de tiempo en frames. :return: cantidad de tiempo en la unidad especificada al instancia la clase.
Convierte el tiempo desde frames a la unidad especificada al instanciar la clase.
def convert_time_from_frames(self, frames: int) -> float: """Convierte el tiempo desde frames a la unidad especificada al instanciar la clase. :param frames: cantidad de tiempo en frames. :return: cantidad de tiempo en la unidad especificada al instancia la clase. """ if self.time_unit == self.TimeUnit.SECOND: return frames / self.frames_per_second elif self.time_unit == self.TimeUnit.HOUR: return frames / self.frames_per_second / 3600 return frames
[ "def", "convert_time_from_frames", "(", "self", ",", "frames", ":", "int", ")", "->", "float", ":", "if", "self", ".", "time_unit", "==", "self", ".", "TimeUnit", ".", "SECOND", ":", "return", "frames", "/", "self", ".", "frames_per_second", "elif", "self", ".", "time_unit", "==", "self", ".", "TimeUnit", ".", "HOUR", ":", "return", "frames", "/", "self", ".", "frames_per_second", "/", "3600", "return", "frames" ]
[ 201, 4 ]
[ 211, 21 ]
null
python
es
['es', 'es', 'es']
True
true
null
TokenCallback.get_token_limit
(userid: int, *, cursor)
return token_limit
Obtener el límite de token's permitidos por un usuario
Obtener el límite de token's permitidos por un usuario
async def get_token_limit(userid: int, *, cursor) -> int: """Obtener el límite de token's permitidos por un usuario""" await cursor.execute( "SELECT token_limit FROM users WHERE id = %s LIMIT 1", (userid,) ) token_limit = await cursor.fetchone() return token_limit
[ "async", "def", "get_token_limit", "(", "userid", ":", "int", ",", "*", ",", "cursor", ")", "->", "int", ":", "await", "cursor", ".", "execute", "(", "\"SELECT token_limit FROM users WHERE id = %s LIMIT 1\"", ",", "(", "userid", ",", ")", ")", "token_limit", "=", "await", "cursor", ".", "fetchone", "(", ")", "return", "token_limit" ]
[ 274, 4 ]
[ 284, 26 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_instruccion_procedimiento
(t)
instruccion : pl_procedimiento
instruccion : pl_procedimiento
def p_instruccion_procedimiento(t) : '''instruccion : pl_procedimiento''' visita = str(t[1]['visita']) reporte = "<instruccion> ::= <pl_procedimiento>\n" +t[1]['reporte'] t[0] = {'ast' : t[1]['ast'], 'graph' : grafo.index, 'reporte': reporte, 'visita': visita}
[ "def", "p_instruccion_procedimiento", "(", "t", ")", ":", "visita", "=", "str", "(", "t", "[", "1", "]", "[", "'visita'", "]", ")", "reporte", "=", "\"<instruccion> ::= <pl_procedimiento>\\n\"", "+", "t", "[", "1", "]", "[", "'reporte'", "]", "t", "[", "0", "]", "=", "{", "'ast'", ":", "t", "[", "1", "]", "[", "'ast'", "]", ",", "'graph'", ":", "grafo", ".", "index", ",", "'reporte'", ":", "reporte", ",", "'visita'", ":", "visita", "}" ]
[ 513, 0 ]
[ 517, 93 ]
null
python
es
['es', 'es', 'es']
True
true
null
create_test_data
()
Crear centros de salud con diferentes especialidades y profesionales asignados cada una. Sumar ademas usuarios con permisos en esos centros
Crear centros de salud con diferentes especialidades y profesionales asignados cada una. Sumar ademas usuarios con permisos en esos centros
def create_test_data(): """ Crear centros de salud con diferentes especialidades y profesionales asignados cada una. Sumar ademas usuarios con permisos en esos centros """ for x in range(1, 4): # crear centros de salud y especialidades cs, created = CentroDeSalud.objects.get_or_create(nombre=f"Centro de Salud {x}", codigo_hpgd=f"{x}.{x}") es, created = Especialidad.objects.get_or_create(nombre=f"Especialidad {x}") # crear un servicio en ese centro de salud para esa especialidad se, created = Servicio.objects.get_or_create(centro=cs, especialidad=es) for y in 'ABCDE': pr, created = Profesional.objects.get_or_create(nombres=f"Profesional {x}{y}", numero_documento=f"900000{x}{y}") ps, created = ProfesionalesEnServicio.objects.get_or_create(servicio=se, profesional=pr) # crear un usuario para cada uno de los profesionales group_prof = Group.objects.get(name=settings.GRUPO_PROFESIONAL) us = User.objects.filter(username=f"prof{x}{y}") if us.count() == 0: user_prof = User.objects.create_user(username=f"prof{x}{y}", email=f"prof{x}{y}@test.com", password=f"prof{x}{y}") pr.user = user_prof pr.save() else: user_prof = us[0] user_prof.groups.add(group_prof) # agregar un usuario administrativo con permisos para este centro de salud group_admin = Group.objects.get(name=settings.GRUPO_ADMIN) user_name = f"administrativo{x}" us = User.objects.filter(username=user_name) if us.count() == 0: user_admin = User.objects.create_user(username=user_name, email=f"admin{x}@test.com", password=user_name) else: user_admin = us[0] user_admin.groups.add(group_admin) UsuarioEnCentroDeSalud.objects.get_or_create(usuario=user_admin, centro_de_salud=cs)
[ "def", "create_test_data", "(", ")", ":", "for", "x", "in", "range", "(", "1", ",", "4", ")", ":", "# crear centros de salud y especialidades", "cs", ",", "created", "=", "CentroDeSalud", ".", "objects", ".", "get_or_create", "(", "nombre", "=", "f\"Centro de Salud {x}\"", ",", "codigo_hpgd", "=", "f\"{x}.{x}\"", ")", "es", ",", "created", "=", "Especialidad", ".", "objects", ".", "get_or_create", "(", "nombre", "=", "f\"Especialidad {x}\"", ")", "# crear un servicio en ese centro de salud para esa especialidad", "se", ",", "created", "=", "Servicio", ".", "objects", ".", "get_or_create", "(", "centro", "=", "cs", ",", "especialidad", "=", "es", ")", "for", "y", "in", "'ABCDE'", ":", "pr", ",", "created", "=", "Profesional", ".", "objects", ".", "get_or_create", "(", "nombres", "=", "f\"Profesional {x}{y}\"", ",", "numero_documento", "=", "f\"900000{x}{y}\"", ")", "ps", ",", "created", "=", "ProfesionalesEnServicio", ".", "objects", ".", "get_or_create", "(", "servicio", "=", "se", ",", "profesional", "=", "pr", ")", "# crear un usuario para cada uno de los profesionales", "group_prof", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "settings", ".", "GRUPO_PROFESIONAL", ")", "us", "=", "User", ".", "objects", ".", "filter", "(", "username", "=", "f\"prof{x}{y}\"", ")", "if", "us", ".", "count", "(", ")", "==", "0", ":", "user_prof", "=", "User", ".", "objects", ".", "create_user", "(", "username", "=", "f\"prof{x}{y}\"", ",", "email", "=", "f\"prof{x}{y}@test.com\"", ",", "password", "=", "f\"prof{x}{y}\"", ")", "pr", ".", "user", "=", "user_prof", "pr", ".", "save", "(", ")", "else", ":", "user_prof", "=", "us", "[", "0", "]", "user_prof", ".", "groups", ".", "add", "(", "group_prof", ")", "# agregar un usuario administrativo con permisos para este centro de salud", "group_admin", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "settings", ".", "GRUPO_ADMIN", ")", "user_name", "=", "f\"administrativo{x}\"", "us", "=", "User", ".", "objects", ".", "filter", "(", "username", "=", "user_name", ")", "if", "us", ".", "count", "(", ")", "==", "0", ":", "user_admin", "=", "User", ".", "objects", ".", "create_user", "(", "username", "=", "user_name", ",", "email", "=", "f\"admin{x}@test.com\"", ",", "password", "=", "user_name", ")", "else", ":", "user_admin", "=", "us", "[", "0", "]", "user_admin", ".", "groups", ".", "add", "(", "group_admin", ")", "UsuarioEnCentroDeSalud", ".", "objects", ".", "get_or_create", "(", "usuario", "=", "user_admin", ",", "centro_de_salud", "=", "cs", ")" ]
[ 119, 0 ]
[ 161, 72 ]
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", "]", "]" ]
[ 404, 0 ]
[ 406, 17 ]
null
python
es
['es', 'es', 'es']
True
true
null
ordenar
(arr: matrix, x: str)
return sorted(arr, key=lambda y: y[col[x]])
Ordena los datos de forma ascendente por la columna elegida. :param arr: Lista de datos. :arr type: List[List[Union[str, int]]] :param x: Columna a seleccionar. :x type: int :return: Datos ordenados de forma ascendente. :rtype: List[List[Union[str, int]]]
Ordena los datos de forma ascendente por la columna elegida.
def ordenar(arr: matrix, x: str) -> matrix: """Ordena los datos de forma ascendente por la columna elegida. :param arr: Lista de datos. :arr type: List[List[Union[str, int]]] :param x: Columna a seleccionar. :x type: int :return: Datos ordenados de forma ascendente. :rtype: List[List[Union[str, int]]] """ col = {"nombre": 0, "curso1": 1, "curso2": 2} return sorted(arr, key=lambda y: y[col[x]])
[ "def", "ordenar", "(", "arr", ":", "matrix", ",", "x", ":", "str", ")", "->", "matrix", ":", "col", "=", "{", "\"nombre\"", ":", "0", ",", "\"curso1\"", ":", "1", ",", "\"curso2\"", ":", "2", "}", "return", "sorted", "(", "arr", ",", "key", "=", "lambda", "y", ":", "y", "[", "col", "[", "x", "]", "]", ")" ]
[ 64, 0 ]
[ 75, 47 ]
null
python
es
['es', 'es', 'es']
True
true
null
Libro.cambiarLeido
(self)
Toma un libro sin leer y lo transforma a leido
Toma un libro sin leer y lo transforma a leido
def cambiarLeido(self): '''Toma un libro sin leer y lo transforma a leido''' self.leido = True
[ "def", "cambiarLeido", "(", "self", ")", ":", "self", ".", "leido", "=", "True" ]
[ 16, 4 ]
[ 18, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
s3_logout
(bot: DeltaBot, message: Message, replies: Replies)
Darte baja del bot y olvidar tu cuenta.
Darte baja del bot y olvidar tu cuenta.
def s3_logout(bot: DeltaBot, message: Message, replies: Replies) -> None: """Darte baja del bot y olvidar tu cuenta.""" addr = message.get_sender_contact().addr if addr in petitions: replies.add( text="❌ Tienes una petición pendiente en cola, espera a que tu descarga termine para darte baja.", quote=message, ) return acc = db.get_account(addr) if acc: db.delete_account(addr) replies.add( text="🗑️ Tu cuenta ha sido desvinculada.\n\n**⚠️ATENCIÓN:** No se estén dando de baja y logueando otra vez constantemente si no quieren que ToDus bloquee su cuenta. No pueden la misma cuenta de ToDus en varios dispositivos por eso la app del ToDus les dejará de funcionar, tienen que o dejar de usar la apk o usar alguna que les deje establecer el password (el token que les envía el bot cuando inician sesión)" ) else: replies.add(text="No estás registrado")
[ "def", "s3_logout", "(", "bot", ":", "DeltaBot", ",", "message", ":", "Message", ",", "replies", ":", "Replies", ")", "->", "None", ":", "addr", "=", "message", ".", "get_sender_contact", "(", ")", ".", "addr", "if", "addr", "in", "petitions", ":", "replies", ".", "add", "(", "text", "=", "\"❌ Tienes una petición pendiente en cola, espera a que tu descarga termine para darte baja.\",", "", "quote", "=", "message", ",", ")", "return", "acc", "=", "db", ".", "get_account", "(", "addr", ")", "if", "acc", ":", "db", ".", "delete_account", "(", "addr", ")", "replies", ".", "add", "(", "text", "=", "\"🗑️ Tu cuenta ha sido desvinculada.\\n\\n**⚠️ATENCIÓN:** No se estén dando de baja y logueando otra vez constantemente si no quieren que ToDus bloquee su cuenta. No pueden la misma cuenta de ToDus en varios dispositivos por eso la app del ToDus les dejará de funcionar, tienen que o dejar de usar la apk o usar alguna que les deje establecer el password (el token que les envía el bot cuando inician sesión)\"", ")", "else", ":", "replies", ".", "add", "(", "text", "=", "\"No estás registrado\")", "" ]
[ 156, 0 ]
[ 172, 48 ]
null
python
es
['es', 'es', 'es']
True
true
null
create_err_dict
(status,index)
Aqui agrego el código de error a uno diccionario con valor igual número de veces que ha aparecido
Aqui agrego el código de error a uno diccionario con valor igual número de veces que ha aparecido
def create_err_dict(status,index): '''Aqui agrego el código de error a uno diccionario con valor igual número de veces que ha aparecido''' dic=errors[index] #dic es el dicionario correspondiente al usuario en la posicion if status in dic: #index de la lista de usuarios 'users' dic[status]+=1 else: dic[status]=1
[ "def", "create_err_dict", "(", "status", ",", "index", ")", ":", "dic", "=", "errors", "[", "index", "]", "#dic es el dicionario correspondiente al usuario en la posicion", "if", "status", "in", "dic", ":", "#index de la lista de usuarios 'users'", "dic", "[", "status", "]", "+=", "1", "else", ":", "dic", "[", "status", "]", "=", "1" ]
[ 114, 0 ]
[ 121, 21 ]
null
python
es
['es', 'es', 'es']
True
true
null
Matrix.__add__
(self, other)
Metodo para la suma de matrices.
Metodo para la suma de matrices.
def __add__(self, other): """ Metodo para la suma de matrices. """ if self.check("add", other): new = [map(lambda r, s: r + s, i, j) for i, j in zip(self, other)] return Matrix(new) else: raise TypeError("Matrix: Dimensions do not match.")
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "self", ".", "check", "(", "\"add\"", ",", "other", ")", ":", "new", "=", "[", "map", "(", "lambda", "r", ",", "s", ":", "r", "+", "s", ",", "i", ",", "j", ")", "for", "i", ",", "j", "in", "zip", "(", "self", ",", "other", ")", "]", "return", "Matrix", "(", "new", ")", "else", ":", "raise", "TypeError", "(", "\"Matrix: Dimensions do not match.\"", ")" ]
[ 16, 4 ]
[ 22, 63 ]
null
python
es
['es', 'es', 'es']
True
true
null
IIterator.get_next
(self, iterable)
Regresa el siguiente elemento del iterable
Regresa el siguiente elemento del iterable
def get_next(self, iterable): """ Regresa el siguiente elemento del iterable """ pass
[ "def", "get_next", "(", "self", ",", "iterable", ")", ":", "pass" ]
[ 7, 4 ]
[ 9, 12 ]
null
python
es
['es', 'es', 'es']
True
true
null
Text.is_possible_full_name
(cls, text: str)
return cls.is_possible_name(text)
Comprueba si el texto indicado puede ser un nombre completo.
Comprueba si el texto indicado puede ser un nombre completo.
def is_possible_full_name(cls, text: str) -> bool: """Comprueba si el texto indicado puede ser un nombre completo.""" if len(text.split(" ")) < 2: return False return cls.is_possible_name(text)
[ "def", "is_possible_full_name", "(", "cls", ",", "text", ":", "str", ")", "->", "bool", ":", "if", "len", "(", "text", ".", "split", "(", "\" \"", ")", ")", "<", "2", ":", "return", "False", "return", "cls", ".", "is_possible_name", "(", "text", ")" ]
[ 308, 4 ]
[ 312, 41 ]
null
python
es
['es', 'es', 'es']
True
true
null
NetworkCallback.extract_networkid
(network: str, *, cursor)
return networkid
Extraer el identificador de la red
Extraer el identificador de la red
async def extract_networkid(network: str, *, cursor) -> Tuple[int]: """Extraer el identificador de la red""" await cursor.execute( "SELECT id_network FROM networks WHERE network = %s LIMIT 1", (network,) ) networkid = await cursor.fetchone() return networkid
[ "async", "def", "extract_networkid", "(", "network", ":", "str", ",", "*", ",", "cursor", ")", "->", "Tuple", "[", "int", "]", ":", "await", "cursor", ".", "execute", "(", "\"SELECT id_network FROM networks WHERE network = %s LIMIT 1\"", ",", "(", "network", ",", ")", ")", "networkid", "=", "await", "cursor", ".", "fetchone", "(", ")", "return", "networkid" ]
[ 501, 4 ]
[ 511, 24 ]
null
python
es
['es', 'es', 'es']
True
true
null
replace_by_key
(replacements, raw_strs)
return [replacements.get(fingerprint_keyer(s), s) for s in raw_strs]
Reemplaza strings por sus mejores equivalentes.
Reemplaza strings por sus mejores equivalentes.
def replace_by_key(replacements, raw_strs): """Reemplaza strings por sus mejores equivalentes.""" return [replacements.get(fingerprint_keyer(s), s) for s in raw_strs]
[ "def", "replace_by_key", "(", "replacements", ",", "raw_strs", ")", ":", "return", "[", "replacements", ".", "get", "(", "fingerprint_keyer", "(", "s", ")", ",", "s", ")", "for", "s", "in", "raw_strs", "]" ]
[ 108, 0 ]
[ 110, 72 ]
null
python
es
['es', 'es', 'es']
True
true
null
get_parser
()
return parser
Función para obtener el parseador de argumentos que se le pasa al programa por línea de comando Returns ------- parser objecto del tipo `ArgumentParser`
Función para obtener el parseador de argumentos que se le pasa al programa por línea de comando
def get_parser(): """Función para obtener el parseador de argumentos que se le pasa al programa por línea de comando Returns ------- parser objecto del tipo `ArgumentParser` """ parser = argparse.ArgumentParser( prog='gmaps-db', usage='gmaps-db -c <db_operation_config> -o <operation>') parser.add_argument('-c', '--config_file', nargs="?", help=''' path to configuration file in json format that with the following schema: { "db_name":"gmaps", "host":"localhost", "user":"root", "passwd":"1234" } ''', required=True) parser.add_argument('-o', '--operation', nargs="?", help='''operation to be performed''') return parser
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'gmaps-db'", ",", "usage", "=", "'gmaps-db -c <db_operation_config> -o <operation>'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config_file'", ",", "nargs", "=", "\"?\"", ",", "help", "=", "'''\n path to configuration file in json format that with the following schema:\n {\n \"db_name\":\"gmaps\",\n \"host\":\"localhost\",\n \"user\":\"root\",\n \"passwd\":\"1234\"\n } \n '''", ",", "required", "=", "True", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--operation'", ",", "nargs", "=", "\"?\"", ",", "help", "=", "'''operation to be performed'''", ")", "return", "parser" ]
[ 256, 0 ]
[ 278, 17 ]
null
python
es
['es', 'es', 'es']
True
true
null
DataCleaner._get_file_encoding
(self, file_path)
return (info['encoding'] if info['confidence'] > 0.75 else self.INPUT_DEFAULT_ENCODING)
Detecta la codificación de un archivo con cierto nivel de confianza y devuelve esta codificación o el valor por defecto. Args: file_path (str): Ruta del archivo. Returns: str: Codificación del archivo.
Detecta la codificación de un archivo con cierto nivel de confianza y devuelve esta codificación o el valor por defecto.
def _get_file_encoding(self, file_path): """Detecta la codificación de un archivo con cierto nivel de confianza y devuelve esta codificación o el valor por defecto. Args: file_path (str): Ruta del archivo. Returns: str: Codificación del archivo. """ with open(file_path, 'rb') as f: info = cchardet.detect(f.read()) return (info['encoding'] if info['confidence'] > 0.75 else self.INPUT_DEFAULT_ENCODING)
[ "def", "_get_file_encoding", "(", "self", ",", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "info", "=", "cchardet", ".", "detect", "(", "f", ".", "read", "(", ")", ")", "return", "(", "info", "[", "'encoding'", "]", "if", "info", "[", "'confidence'", "]", ">", "0.75", "else", "self", ".", "INPUT_DEFAULT_ENCODING", ")" ]
[ 134, 4 ]
[ 147, 49 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_ini
(t)
inicio : sentencias
inicio : sentencias
def p_ini(t): 'inicio : sentencias'
[ "def", "p_ini", "(", "t", ")", ":" ]
[ 120, 0 ]
[ 121, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
NetworkCallback.is_network_exists_for_id
(networkid: int, *, cursor)
return bool(*exists)
Verifica si una red existe a partir de su identificador
Verifica si una red existe a partir de su identificador
async def is_network_exists_for_id(networkid: int, *, cursor) -> bool: """Verifica si una red existe a partir de su identificador""" await cursor.execute( "SELECT COUNT(id_network) FROM networks WHERE id_network = %s", (networkid,) ) exists = await cursor.fetchone() return bool(*exists)
[ "async", "def", "is_network_exists_for_id", "(", "networkid", ":", "int", ",", "*", ",", "cursor", ")", "->", "bool", ":", "await", "cursor", ".", "execute", "(", "\"SELECT COUNT(id_network) FROM networks WHERE id_network = %s\"", ",", "(", "networkid", ",", ")", ")", "exists", "=", "await", "cursor", ".", "fetchone", "(", ")", "return", "bool", "(", "*", "exists", ")" ]
[ 463, 4 ]
[ 474, 28 ]
null
python
es
['es', 'es', 'es']
True
true
null
CubeShell.do_resolver_all
(self, args)
Ejecuta todos los algoritmos de busqueda implementados hasta ahora, sin imprimir la solucion como tal pero si el tiempo
Ejecuta todos los algoritmos de busqueda implementados hasta ahora, sin imprimir la solucion como tal pero si el tiempo
def do_resolver_all(self, args): '''Ejecuta todos los algoritmos de busqueda implementados hasta ahora, sin imprimir la solucion como tal pero si el tiempo''' problema = Problema(cubo_actual) utils.resolverAll(problema)
[ "def", "do_resolver_all", "(", "self", ",", "args", ")", ":", "problema", "=", "Problema", "(", "cubo_actual", ")", "utils", ".", "resolverAll", "(", "problema", ")" ]
[ 32, 4 ]
[ 36, 35 ]
null
python
es
['es', 'es', 'es']
True
true
null
index
()
return render_template("index.html")
Por defecto va directamente a la carpeta templates a buscar el archivo html
Por defecto va directamente a la carpeta templates a buscar el archivo html
def index(): """Por defecto va directamente a la carpeta templates a buscar el archivo html""" return render_template("index.html")
[ "def", "index", "(", ")", ":", "return", "render_template", "(", "\"index.html\"", ")" ]
[ 8, 0 ]
[ 10, 40 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_funciones_time2
(p)
funciones : TIMESTAMP CADENA_NOW
funciones : TIMESTAMP CADENA_NOW
def p_funciones_time2(p): 'funciones : TIMESTAMP CADENA_NOW' bnf.addProduccion(f'\<timestamp> ::= "{p[1].upper()}" "CADENA_NOW"') p[0] = FuncionTime(funcion="TIMESTAMP" , parametro1=p[2],linea=p.slice[1].lineno)
[ "def", "p_funciones_time2", "(", "p", ")", ":", "bnf", ".", "addProduccion", "(", "f'\\<timestamp> ::= \"{p[1].upper()}\" \"CADENA_NOW\"'", ")", "p", "[", "0", "]", "=", "FuncionTime", "(", "funcion", "=", "\"TIMESTAMP\"", ",", "parametro1", "=", "p", "[", "2", "]", ",", "linea", "=", "p", ".", "slice", "[", "1", "]", ".", "lineno", ")" ]
[ 785, 0 ]
[ 788, 85 ]
null
python
es
['es', 'es', 'es']
True
true
null
jsonWrite
(name, json_data)
Escribe un archivo JSON en la carpeta json_files. Argumentos: name (str): Nombre del archivo, json_data (Any): Datos del archivo JSON. Returns: Nothing.
Escribe un archivo JSON en la carpeta json_files.
def jsonWrite(name, json_data): """Escribe un archivo JSON en la carpeta json_files. Argumentos: name (str): Nombre del archivo, json_data (Any): Datos del archivo JSON. Returns: Nothing. """ with open(PATHS.get('json_folder') + getTimestampedName(name) + '.json', 'w') as salida: salida.write(getJSONConFormato(json_data))
[ "def", "jsonWrite", "(", "name", ",", "json_data", ")", ":", "with", "open", "(", "PATHS", ".", "get", "(", "'json_folder'", ")", "+", "getTimestampedName", "(", "name", ")", "+", "'.json'", ",", "'w'", ")", "as", "salida", ":", "salida", ".", "write", "(", "getJSONConFormato", "(", "json_data", ")", ")" ]
[ 172, 0 ]
[ 182, 50 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_createTable_constraint
(t)
cuerpo_createTable : CONSTRAINT ID constraint_esp
cuerpo_createTable : CONSTRAINT ID constraint_esp
def p_createTable_constraint(t): ' cuerpo_createTable : CONSTRAINT ID constraint_esp ' reporte_bnf.append("<cuerpo_createTable> ::= CONSTRAINT ID <constraint_esp>") if t[3][0] == 'CHECK': t[0] = definicion_constraint(t[2], t[3][0], None, None ,t[3][1]) elif t[3][0] == 'UNIQUE': t[0] = definicion_constraint(t[2], t[3][0], None, None ,t[3][1]) elif t[3][0] == 'FOREIGN': t[0] = definicion_constraint(t[2], t[3][0], t[3][2], t[3][1] ,t[3][3])
[ "def", "p_createTable_constraint", "(", "t", ")", ":", "reporte_bnf", ".", "append", "(", "\"<cuerpo_createTable> ::= CONSTRAINT ID <constraint_esp>\"", ")", "if", "t", "[", "3", "]", "[", "0", "]", "==", "'CHECK'", ":", "t", "[", "0", "]", "=", "definicion_constraint", "(", "t", "[", "2", "]", ",", "t", "[", "3", "]", "[", "0", "]", ",", "None", ",", "None", ",", "t", "[", "3", "]", "[", "1", "]", ")", "elif", "t", "[", "3", "]", "[", "0", "]", "==", "'UNIQUE'", ":", "t", "[", "0", "]", "=", "definicion_constraint", "(", "t", "[", "2", "]", ",", "t", "[", "3", "]", "[", "0", "]", ",", "None", ",", "None", ",", "t", "[", "3", "]", "[", "1", "]", ")", "elif", "t", "[", "3", "]", "[", "0", "]", "==", "'FOREIGN'", ":", "t", "[", "0", "]", "=", "definicion_constraint", "(", "t", "[", "2", "]", ",", "t", "[", "3", "]", "[", "0", "]", ",", "t", "[", "3", "]", "[", "2", "]", ",", "t", "[", "3", "]", "[", "1", "]", ",", "t", "[", "3", "]", "[", "3", "]", ")" ]
[ 1349, 0 ]
[ 1357, 78 ]
null
python
es
['es', 'es', 'es']
True
true
null
TraductorFiscal.getLastNumber
(self, tipo_cbte)
return ret
Devuelve el último número de comprobante
Devuelve el último número de comprobante
def getLastNumber(self, tipo_cbte): "Devuelve el último número de comprobante" self.comando.start() letra_cbte = tipo_cbte[-1] if len(tipo_cbte) > 1 else None ret = self.comando.getLastNumber(letra_cbte) self.comando.close() return ret
[ "def", "getLastNumber", "(", "self", ",", "tipo_cbte", ")", ":", "self", ".", "comando", ".", "start", "(", ")", "letra_cbte", "=", "tipo_cbte", "[", "-", "1", "]", "if", "len", "(", "tipo_cbte", ")", ">", "1", "else", "None", "ret", "=", "self", ".", "comando", ".", "getLastNumber", "(", "letra_cbte", ")", "self", ".", "comando", ".", "close", "(", ")", "return", "ret" ]
[ 55, 4 ]
[ 61, 18 ]
null
python
es
['es', 'es', 'es']
True
true
null
Comparator
()
Compara entre las dos fechas si la actual es más reciente o no
Compara entre las dos fechas si la actual es más reciente o no
def Comparator(): """Compara entre las dos fechas si la actual es más reciente o no""" if second_date[2] < first_date[2]: return Alarm() elif second_date[2] == first_date[2]: if second_date[1] < first_date[1]: return Alarm() elif second_date[1] == first_date[1]: if second_date[0] < first_date[0]: return Alarm() elif second_date[0] == first_date[0]: return "SameDate" else: return "NoBetter" else: return "NoBetter" else: return "NoBetter"
[ "def", "Comparator", "(", ")", ":", "if", "second_date", "[", "2", "]", "<", "first_date", "[", "2", "]", ":", "return", "Alarm", "(", ")", "elif", "second_date", "[", "2", "]", "==", "first_date", "[", "2", "]", ":", "if", "second_date", "[", "1", "]", "<", "first_date", "[", "1", "]", ":", "return", "Alarm", "(", ")", "elif", "second_date", "[", "1", "]", "==", "first_date", "[", "1", "]", ":", "if", "second_date", "[", "0", "]", "<", "first_date", "[", "0", "]", ":", "return", "Alarm", "(", ")", "elif", "second_date", "[", "0", "]", "==", "first_date", "[", "0", "]", ":", "return", "\"SameDate\"", "else", ":", "return", "\"NoBetter\"", "else", ":", "return", "\"NoBetter\"", "else", ":", "return", "\"NoBetter\"" ]
[ 113, 0 ]
[ 130, 19 ]
null
python
es
['es', 'es', 'es']
True
true
null
Vehiculo.__str__
(self)
return "Velocidad: {} km/h \nTengo {} km recorridos\ny Capacidad: {} pasajeros\n".format(self.velocidad_maxima, self.kilometraje, self.capacidad)
Devuelve una cadena representativa del vehículo
Devuelve una cadena representativa del vehículo
def __str__(self): """Devuelve una cadena representativa del vehículo""" return "Velocidad: {} km/h \nTengo {} km recorridos\ny Capacidad: {} pasajeros\n".format(self.velocidad_maxima, self.kilometraje, self.capacidad)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"Velocidad: {} km/h \\nTengo {} km recorridos\\ny Capacidad: {} pasajeros\\n\"", ".", "format", "(", "self", ".", "velocidad_maxima", ",", "self", ".", "kilometraje", ",", "self", ".", "capacidad", ")" ]
[ 7, 4 ]
[ 9, 153 ]
null
python
es
['es', 'es', 'es']
True
true
null
Molecule.__init__
(self)
Constructor para crear una nueva molecula.
Constructor para crear una nueva molecula.
def __init__(self): """ Constructor para crear una nueva molecula. """ self.atoms = [] self.bonds = [] self.mol_weight = 0.0 self.charge = 0.0
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "atoms", "=", "[", "]", "self", ".", "bonds", "=", "[", "]", "self", ".", "mol_weight", "=", "0.0", "self", ".", "charge", "=", "0.0" ]
[ 75, 4 ]
[ 80, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
TransactionViewSet.list
(self, request)
return Response(serializer.data)
Lista todas las transacciones que han hecho los usuarios de la sala
Lista todas las transacciones que han hecho los usuarios de la sala
def list(self, request): """ Lista todas las transacciones que han hecho los usuarios de la sala""" banquero = self.request.user room = Room.objects.get(userBanker=banquero.id) self.queryset = Transaction.objects.filter(userTransmitter__room__idRoom__exact=room.idRoom).order_by('-creationTime') serializer = TransactionSerializer(self.queryset, many=True) return Response(serializer.data)
[ "def", "list", "(", "self", ",", "request", ")", ":", "banquero", "=", "self", ".", "request", ".", "user", "room", "=", "Room", ".", "objects", ".", "get", "(", "userBanker", "=", "banquero", ".", "id", ")", "self", ".", "queryset", "=", "Transaction", ".", "objects", ".", "filter", "(", "userTransmitter__room__idRoom__exact", "=", "room", ".", "idRoom", ")", ".", "order_by", "(", "'-creationTime'", ")", "serializer", "=", "TransactionSerializer", "(", "self", ".", "queryset", ",", "many", "=", "True", ")", "return", "Response", "(", "serializer", ".", "data", ")" ]
[ 78, 4 ]
[ 84, 40 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_definicion_10
(p)
definicion : CREATE TABLE ID PABRE columnas PCIERRA
definicion : CREATE TABLE ID PABRE columnas PCIERRA
def p_definicion_10(p): 'definicion : CREATE TABLE ID PABRE columnas PCIERRA'
[ "def", "p_definicion_10", "(", "p", ")", ":" ]
[ 98, 0 ]
[ 99, 57 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_update2
(t)
instruccion : UPDATE ID SET asignaciones WHERE andOr PTCOMA
instruccion : UPDATE ID SET asignaciones WHERE andOr PTCOMA
def p_update2(t): 'instruccion : UPDATE ID SET asignaciones WHERE andOr PTCOMA' t[0] = Update(t[2], t[4], t[6]) varGramatical.append('instruccion ::= UPDATE ID SET asignaciones WHERE andOr PTCOMA') varSemantico.append('is ')
[ "def", "p_update2", "(", "t", ")", ":", "t", "[", "0", "]", "=", "Update", "(", "t", "[", "2", "]", ",", "t", "[", "4", "]", ",", "t", "[", "6", "]", ")", "varGramatical", ".", "append", "(", "'instruccion ::= UPDATE ID SET asignaciones WHERE andOr PTCOMA'", ")", "varSemantico", ".", "append", "(", "'is '", ")" ]
[ 684, 0 ]
[ 688, 30 ]
null
python
es
['es', 'es', 'es']
True
true
null
contar_valles
(*args)
return count
r'''Contar el número de valles Esta función debe recibir como argumento una lista de -1's, 0's y 1's, y lo que representan son las subidas y las bajadas en una ruta de caminata. -1 representa un paso hacia abajo, el 0 representa un paso hacia adelante y el 1 representa un paso hacia arriba, entonces por ejemplo, para la lista [-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1] representa la siguiente ruta: /\ /\__/\/ \ _/ \/ El objetivo de esta función es devolver el número de valles que estén representados en la lista, que para el ejemplo que se acaba de mostrar es de 3 valles.
r'''Contar el número de valles
def contar_valles(*args): r'''Contar el número de valles Esta función debe recibir como argumento una lista de -1's, 0's y 1's, y lo que representan son las subidas y las bajadas en una ruta de caminata. -1 representa un paso hacia abajo, el 0 representa un paso hacia adelante y el 1 representa un paso hacia arriba, entonces por ejemplo, para la lista [-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1] representa la siguiente ruta: /\ /\__/\/ \ _/ \/ El objetivo de esta función es devolver el número de valles que estén representados en la lista, que para el ejemplo que se acaba de mostrar es de 3 valles. ''' count=0 for i in range(len(args[0])): if args[0][i] == 0: count+=1 return count
[ "def", "contar_valles", "(", "*", "args", ")", ":", "count", "=", "0", "for", "i", "in", "range", "(", "len", "(", "args", "[", "0", "]", ")", ")", ":", "if", "args", "[", "0", "]", "[", "i", "]", "==", "0", ":", "count", "+=", "1", "return", "count" ]
[ 37, 0 ]
[ 60, 14 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_tipo_relaciones
(t)
relaciones : UNION | INTERSECT | EXCEPT
relaciones : UNION | INTERSECT | EXCEPT
def p_tipo_relaciones(t): '''relaciones : UNION | INTERSECT | EXCEPT ''' if(t[1]=="UNION"): t[0] = "UNION" elif(t[1]=="INTERSECT"): t[0] = "INTERSECT" elif(t[1]=="EXCEPT"): t[0] = "EXCEPT" else: t[0] = None
[ "def", "p_tipo_relaciones", "(", "t", ")", ":", "if", "(", "t", "[", "1", "]", "==", "\"UNION\"", ")", ":", "t", "[", "0", "]", "=", "\"UNION\"", "elif", "(", "t", "[", "1", "]", "==", "\"INTERSECT\"", ")", ":", "t", "[", "0", "]", "=", "\"INTERSECT\"", "elif", "(", "t", "[", "1", "]", "==", "\"EXCEPT\"", ")", ":", "t", "[", "0", "]", "=", "\"EXCEPT\"", "else", ":", "t", "[", "0", "]", "=", "None" ]
[ 483, 0 ]
[ 495, 19 ]
null
python
es
['es', 'es', 'es']
True
true
null
Node.get_invalidated_fields
(self, invalidated, state)
return found_refs
debe devolver un conjunto de referencias a campos que deben ser invalidados, a partir de campos invalidados previamente
debe devolver un conjunto de referencias a campos que deben ser invalidados, a partir de campos invalidados previamente
def get_invalidated_fields(self, invalidated, state): ''' debe devolver un conjunto de referencias a campos que deben ser invalidados, a partir de campos invalidados previamente ''' node_state = state['state']['items'][self.id] if node_state['state'] == 'unfilled': return [] found_refs = [] for ref in invalidated: # for refs in this node's forms if self.in_state(ref, node_state): found_refs.append(ref) found_refs += self.dependent_refs(invalidated, node_state) return found_refs
[ "def", "get_invalidated_fields", "(", "self", ",", "invalidated", ",", "state", ")", ":", "node_state", "=", "state", "[", "'state'", "]", "[", "'items'", "]", "[", "self", ".", "id", "]", "if", "node_state", "[", "'state'", "]", "==", "'unfilled'", ":", "return", "[", "]", "found_refs", "=", "[", "]", "for", "ref", "in", "invalidated", ":", "# for refs in this node's forms", "if", "self", ".", "in_state", "(", "ref", ",", "node_state", ")", ":", "found_refs", ".", "append", "(", "ref", ")", "found_refs", "+=", "self", ".", "dependent_refs", "(", "invalidated", ",", "node_state", ")", "return", "found_refs" ]
[ 138, 4 ]
[ 155, 25 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_codiciones
(t)
condiciones : condicion
condiciones : condicion
def p_codiciones(t): 'condiciones : condicion' t[0] = t[1]
[ "def", "p_codiciones", "(", "t", ")", ":", "t", "[", "0", "]", "=", "t", "[", "1", "]" ]
[ 976, 0 ]
[ 978, 15 ]
null
python
es
['es', 'es', 'es']
True
true
null
Molecule.get_mol_weight
(self)
return True
Metodo para calcular el peso de la molecula.
Metodo para calcular el peso de la molecula.
def get_mol_weight(self): """ Metodo para calcular el peso de la molecula. """ self.mol_weight = 0.0 for a in self.atoms: symbol = a.element self.mol_weight += PERIODIC_TABLE[symbol]["mass"] return True
[ "def", "get_mol_weight", "(", "self", ")", ":", "self", ".", "mol_weight", "=", "0.0", "for", "a", "in", "self", ".", "atoms", ":", "symbol", "=", "a", ".", "element", "self", ".", "mol_weight", "+=", "PERIODIC_TABLE", "[", "symbol", "]", "[", "\"mass\"", "]", "return", "True" ]
[ 127, 4 ]
[ 133, 19 ]
null
python
es
['es', 'es', 'es']
True
true
null
Atom.__init__
(self, element="H", x=0.0, y=0.0, z=0.0, charge=0.0, flag=False)
Constructor para crear un atomo nuevo.
Constructor para crear un atomo nuevo.
def __init__(self, element="H", x=0.0, y=0.0, z=0.0, charge=0.0, flag=False): """ Constructor para crear un atomo nuevo. """ self.element = element self.coords = Matrix([[x, y, z]]) self.charge = charge self.flag = flag
[ "def", "__init__", "(", "self", ",", "element", "=", "\"H\"", ",", "x", "=", "0.0", ",", "y", "=", "0.0", ",", "z", "=", "0.0", ",", "charge", "=", "0.0", ",", "flag", "=", "False", ")", ":", "self", ".", "element", "=", "element", "self", ".", "coords", "=", "Matrix", "(", "[", "[", "x", ",", "y", ",", "z", "]", "]", ")", "self", ".", "charge", "=", "charge", "self", ".", "flag", "=", "flag" ]
[ 43, 4 ]
[ 49, 24 ]
null
python
es
['es', 'es', 'es']
True
true
null
AbstractGMapsExtractor.get_obj_text
(self, xpath_query, external_driver=None)
return obj.text if obj else obj
Función similar a `get_info_obj`, pero en vez de devolver la referencia al elemento, devuelve el texto contenido en el elemento encontrado 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 ------- elementText : str contenido de texto que tenga la instancia de WebElement en caso de que haya alguno encontrado con la query o None en caso de que no se haya encontrado alguna instancia de WebElement.
Función similar a `get_info_obj`, pero en vez de devolver la referencia al elemento, devuelve el texto contenido en el elemento encontrado
def get_obj_text(self, xpath_query, external_driver=None): """Función similar a `get_info_obj`, pero en vez de devolver la referencia al elemento, devuelve el texto contenido en el elemento encontrado 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 ------- elementText : str contenido de texto que tenga la instancia de WebElement en caso de que haya alguno encontrado con la query o None en caso de que no se haya encontrado alguna instancia de WebElement. """ obj = self.get_info_obj(xpath_query, external_driver) return obj.text if obj else obj
[ "def", "get_obj_text", "(", "self", ",", "xpath_query", ",", "external_driver", "=", "None", ")", ":", "obj", "=", "self", ".", "get_info_obj", "(", "xpath_query", ",", "external_driver", ")", "return", "obj", ".", "text", "if", "obj", "else", "obj" ]
[ 281, 4 ]
[ 300, 39 ]
null
python
es
['es', 'es', 'es']
True
true
null
identificador
(payload)
return None
Sirve para que una vez el usuario ya este logeado y tenga su JWT pueda realizar peticiones a una ruta protegica y esta funcion sera la encargada de identificar a dicho usuario y devolver su informacion
Sirve para que una vez el usuario ya este logeado y tenga su JWT pueda realizar peticiones a una ruta protegica y esta funcion sera la encargada de identificar a dicho usuario y devolver su informacion
def identificador(payload): """Sirve para que una vez el usuario ya este logeado y tenga su JWT pueda realizar peticiones a una ruta protegica y esta funcion sera la encargada de identificar a dicho usuario y devolver su informacion""" if(payload['identity']): usuario = db.session.query(UsuarioModel).filter_by( usuarioId=payload['identity']).first() if usuario: return usuario return None
[ "def", "identificador", "(", "payload", ")", ":", "if", "(", "payload", "[", "'identity'", "]", ")", ":", "usuario", "=", "db", ".", "session", ".", "query", "(", "UsuarioModel", ")", ".", "filter_by", "(", "usuarioId", "=", "payload", "[", "'identity'", "]", ")", ".", "first", "(", ")", "if", "usuario", ":", "return", "usuario", "return", "None" ]
[ 25, 0 ]
[ 32, 15 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_funciones46
(p)
funciones : LOG PABRE expresion PCIERRA
funciones : LOG PABRE expresion PCIERRA
def p_funciones46(p): 'funciones : LOG PABRE expresion PCIERRA'
[ "def", "p_funciones46", "(", "p", ")", ":" ]
[ 436, 0 ]
[ 437, 45 ]
null
python
es
['es', 'es', 'es']
True
true
null
p_lista_de_seleccionados_noterminal
(t)
listadeseleccionados : funcionesmatematicassimples | funcionestrigonometricas | funcionesmatematicas | funcionesdefechas | funcionesbinarias | operadoresselect
listadeseleccionados : funcionesmatematicassimples | funcionestrigonometricas | funcionesmatematicas | funcionesdefechas | funcionesbinarias | operadoresselect
def p_lista_de_seleccionados_noterminal(t): '''listadeseleccionados : funcionesmatematicassimples | funcionestrigonometricas | funcionesmatematicas | funcionesdefechas | funcionesbinarias | operadoresselect''' visita = str(t[1]['visita']) grafo.newnode('L_SELECTS') grafo.newchildrenF(grafo.index, t[1]['graph']) reporte = '''<listadeseleccionados := <funcionesmatematicassimples> |<funcionestrigonometricas> |<funcionesmatematicas |<funcionesdefechas> |<funcionesbinarias> |<operadoresselect>\n''' + t[1]['reporte'] #mm t[0] = {'ast': t[1]['ast'],'graph' : grafo.index, 'reporte': reporte, 'visita': visita}
[ "def", "p_lista_de_seleccionados_noterminal", "(", "t", ")", ":", "visita", "=", "str", "(", "t", "[", "1", "]", "[", "'visita'", "]", ")", "grafo", ".", "newnode", "(", "'L_SELECTS'", ")", "grafo", ".", "newchildrenF", "(", "grafo", ".", "index", ",", "t", "[", "1", "]", "[", "'graph'", "]", ")", "reporte", "=", "'''<listadeseleccionados := <funcionesmatematicassimples>\r\n |<funcionestrigonometricas>\r\n |<funcionesmatematicas\r\n |<funcionesdefechas>\r\n |<funcionesbinarias>\r\n |<operadoresselect>\\n'''", "+", "t", "[", "1", "]", "[", "'reporte'", "]", "#mm\r", "t", "[", "0", "]", "=", "{", "'ast'", ":", "t", "[", "1", "]", "[", "'ast'", "]", ",", "'graph'", ":", "grafo", ".", "index", ",", "'reporte'", ":", "reporte", ",", "'visita'", ":", "visita", "}" ]
[ 936, 0 ]
[ 952, 91 ]
null
python
es
['es', 'es', 'es']
True
true
null
calcular
(data: Dict[str, int])
return total, cantidad, descuento
Calcula el total, cantidad y descuento a aplicar. :param data: Cantidad de cada helado :type data: Dict[str, int] :return: Total, cantidad y descuento :rtype: Tuple[float, int, float]
Calcula el total, cantidad y descuento a aplicar.
def calcular(data: Dict[str, int]) -> Tuple[float, int, float]: """Calcula el total, cantidad y descuento a aplicar. :param data: Cantidad de cada helado :type data: Dict[str, int] :return: Total, cantidad y descuento :rtype: Tuple[float, int, float] """ total = 0 cantidad = sum(data.values()) for helado, n in data.items(): total += TIPO[helado] * n descuento = _descuento(cantidad, total) return total, cantidad, descuento
[ "def", "calcular", "(", "data", ":", "Dict", "[", "str", ",", "int", "]", ")", "->", "Tuple", "[", "float", ",", "int", ",", "float", "]", ":", "total", "=", "0", "cantidad", "=", "sum", "(", "data", ".", "values", "(", ")", ")", "for", "helado", ",", "n", "in", "data", ".", "items", "(", ")", ":", "total", "+=", "TIPO", "[", "helado", "]", "*", "n", "descuento", "=", "_descuento", "(", "cantidad", ",", "total", ")", "return", "total", ",", "cantidad", ",", "descuento" ]
[ 42, 0 ]
[ 55, 37 ]
null
python
es
['es', 'es', 'es']
True
true
null