def camel_case(string): # this is called lower camel case and upper case by some as well """ Return a string to camelCase :param string: :return string: Examples:: >>> camel_case("Zen of Python") >>> camel_case("Zen-of-Python") >>> camel_case("Zen.of.Python") >>> camel_case("zen OF pYthon") >>> camel_case("ZEN of_PYTHON") >>> camel_case("zen.OF-python") >>> zenOfPython # for all above use cases """ is_string(string) camel_cased_regex = re.compile("[^A-Za-z]+") camel_cased_str = camel_cased_regex.split(string) return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(camel_cased_str))
def pascal_case(string): """ Return a string to PascalCase :param string: :return string: Examples:: >>> pascal_case("zen of python") >>> pascal_case("zen-of-python") >>> pascal_case("ZEN-OF-PYTHON") >>> pascal_case("ZEN_OF_PYTHON") >>> pascal_case("ZeN-oF.PYthon") >>> pascal_case("zen.of.python") >>> pascal_case("zen-of{python") >>> ZenOfPython # for all above use cases """ is_string(string) return "".join(a.capitalize() for a in re.split('([^a-zA-Z0-9])', string) if a.isalnum())
def insert_alumno(alumno): try: if not alumno.username: raise NameError("Error en el nombre del alumno") else: res = Alumno.objects.filter(username=alumno.username) if res.count() != 0: raise NameError("El alumno ya existe") if not alumno.first_name or not utils.is_string(alumno.first_name): raise NameError("Nombre incorrecto") if not alumno.last_name or not utils.is_string(alumno.last_name): raise NameError("Apellidos incorrectos") # exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es) if not re.match(r'^[a-z][_a-z0-9]+(@correo\.ugr\.es)$', alumno.username): raise NameError("El correo no es correcto") grupo_alumnos = Group.objects.get(name='Alumnos') alumno.save() grupo_alumnos.user_set.add(alumno) return dict(status=True, data=Alumno.objects.get(username=alumno.username)) except NameError as e: return dict(status=False, message=e.message)
def update(self, usuario, validated_data): try: # comprobando email if 'email' in validated_data.keys(): new_email = validated_data.get('email') res = Usuario.objects.filter(email=new_email) if res.count() == 0: if not utils.is_string(new_email) or not \ re.match(r'^[a-z][_a-z0-9]+(@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4}))$', new_email): raise NameError("El email no es correcto") else: usuario.email = new_email else: raise NameError("El usuario indicado ya existe") # comprobando dni if 'dni' in validated_data.keys() and not validated_data.get('creado'): new_dni = validated_data.get('dni') res = Usuario.objects.filter(dni=new_dni) if res.count() == 0: if not utils.is_string(new_dni) or not \ re.match(r'(\d{8})([-]?)([A-Z]{1})', new_dni): raise NameError("El dni no es correcto") else: usuario.email = new_dni else: raise NameError("El usuario indicado ya existe") # comprobando nombre if 'first_name' in validated_data.keys(): new_first_name = validated_data.get('first_name') if new_first_name == '' or not utils.is_string(new_first_name): raise NameError("Nombre incorrecto") else: usuario.first_name = new_first_name # comprobando apellidos if 'last_name' in validated_data.keys(): new_last_name = validated_data.get('last_name') if new_last_name == '' or not utils.is_string(new_last_name): raise NameError("Nombre incorrecto") else: usuario.new_last_name = new_last_name # if 'password' in validated_data.keys() and 'confirm_password' in validated_data.keys(): # password = validated_data.get('password') # confirm_password = validated_data.get('confirm_password') # if password and confirm_password and password == confirm_password: # alumno.set_password(password) usuario.save() if validated_data.get('creado'): utils.enviar_email_reset_password(usuario.email) return dict(status=True, data=usuario) except NameError as e: return dict(status=False, message=e.message) except: return dict(status=False, message="Error en los parametros")
def popstack(stack, oq): tok = stack.pop() if tok in unary: a = oq.pop() oq.append(astnode([tok, a])) elif tok in precedence and tok != ',': a, b = oq.pop(), oq.pop() oq.append(astnode([tok, b, a])) elif tok in closers: if openers[opener_stack[-1]] != tok: raise Exception('Did not close with same kind as opened with!', tok, 'vs', openers[opener_stack[-1]]) opener_stack.pop() args = [] while not utils.is_string(oq[-1]) or oq[-1] not in openers: args.insert(0, oq.pop()) lbrack = oq.pop() if tok == ']' and args[0] != 'id': oq.append(astnode(['access'] + args)) elif tok == ']': oq.append(astnode(['array_lit'] + args[1:])) elif tok == ')' and len(args) and args[0] != 'id': if utils.is_string(args[0]): oq.append(astnode(args)) else: oq.append(astnode(args, *args[0].metadata)) else: oq.append(args[1])
def insert_profesor(profesor): try: if not profesor.username or not (re.match( r'^[a-z][_a-z0-9]+(@ugr\.es)$', profesor.username)): raise NameError("El correo no es correcto") else: res = Profesor.objects.filter(username=profesor.username) if res.count() != 0: raise NameError("El profesor ya existe") if not profesor.first_name or not utils.is_string(profesor.first_name): raise NameError("Error en el nombre del profesor") if not profesor.last_name or not utils.is_string(profesor.last_name): raise NameError("Error en los apellidos del profesor") if not profesor.departamento or not utils.is_string( profesor.departamento): raise NameError("Error en el departamento") grupo_profesores = Group.objects.get(name='Profesores') profesor.save() grupo_profesores.user_set.add(profesor) return dict(status=True, data=Profesor.objects.get(username=profesor.username)) except NameError as e: return dict(status=False, message=e.message)
def insert_profesor(profesor): try: if not profesor.username or not (re.match(r'^[a-z][_a-z0-9]+(@ugr\.es)$', profesor.username)): raise NameError("El correo no es correcto") else: res = Profesor.objects.filter(username=profesor.username) if res.count() != 0: raise NameError("El profesor ya existe") if not profesor.first_name or not utils.is_string(profesor.first_name): raise NameError("Error en el nombre del profesor") if not profesor.last_name or not utils.is_string(profesor.last_name): raise NameError("Error en los apellidos del profesor") if not profesor.departamento or not utils.is_string(profesor.departamento): raise NameError("Error en el departamento") grupo_profesores = Group.objects.get(name='Profesores') profesor.save() grupo_profesores.user_set.add(profesor) return dict(status=True, data=Profesor.objects.get(username=profesor.username)) except NameError as e: return dict(status=False, message=e.message)
def create_user(self, password=None, **kwargs): try: if kwargs.get('email'): # exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es) if not re.match(r'^[_a-z0-9]+(@correo\.ugr\.es)$', kwargs.get('email')): raise NameError("El email no es correcto o no pertenece a la UGR") res = Alumno.objects.filter(email=kwargs.get('email')) if res.count() != 0: raise NameError("El alumno ya existe") if kwargs.get('dni'): # exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es) if not re.match(r'(([X-Z]{1})([-]?)(\d{7})([-]?)([A-Z]{1}))|((\d{8})([-]?)([A-Z]{1}))', kwargs.get('dni')): raise NameError("Error en el DNI del alumno") if kwargs.get('first_name') and not utils.is_string(kwargs.get('first_name')): raise NameError("Nombre incorrecto") if kwargs.get('last_name') and not utils.is_string(kwargs.get('last_name')): raise NameError("Apellidos incorrectos") usuario = self.model.objects.create(email=kwargs.get('email'), dni=kwargs.get('dni'), first_name=kwargs.get('first_name'), last_name=kwargs.get('last_name')) grupo_alumnos = Grupos.objects.get(name='Alumnos') usuario.set_password(password) usuario.save() grupo_alumnos.user_set.add(usuario) if usuario.email: utils.enviar_email_reset_password(usuario.email) return dict(status=True, data=usuario) except NameError as e: return dict(status=False, message=e.message)
def enc(n): if utils.is_numeric(n): return ''.join(map(chr, utils.tobytearr(n, 32))) elif utils.is_string(n) and len(n) == 40: return '\x00' * 12 + n.decode('hex') elif utils.is_string(n): return '\x00' * (32 - len(n)) + n elif n is True: return 1 elif n is False or n is None: return 0
def update(self, key, value): if not utils.is_string(key): raise Exception("Key must be string") if not utils.is_string(value): raise Exception("Value must be string") self.root_node = self._update_and_delete_storage( self.root_node, bin_to_nibbles(utils.to_string(key)), utils.to_string(value)) self._update_root_hash()
def write_lll_stream(self, stream, ast, n): if is_string(ast): write_str(stream, ast) elif isinstance(ast, astnode): if is_string(ast.fun): name = ast.fun.lower() if name in self.config: # It is a special statement. c = self.config[name] if c != 'sexpr': # (Unless config tells us to use s-expressions.) return self.write_lll_special_stream(stream, ast, name, c, n) self.write_lll_list_stream(stream, ast.args, '(', ')', ' ', n) else: raise Exception('What is', ast, type(ast))
def register_new_data_type(datatype_name, datatype_example, idBenefit): """ Receives a new type of data along with it's example and a Benefit id. It adds the new type of data to the database and registers it with the Benefit. Returns <void> """ if (not is_string(datatype_name) or not is_string(datatype_example) or not benefit_exists(idBenefit)): raise TypeError datatype_check = query_data_type_id_by_name_like(datatype_name) if len(datatype_check) > 0: raise Exception("This data type is already registered") insert_data_type(datatype_name, datatype_example) new_datatype = query_data_type_id_by_name(datatype_name) if len(new_datatype) == 0: raise Exception("Registration failed") add_new_data_type_to_benefit(new_datatype[0]['id'], idBenefit)
def create_reply(reply, message=None): if isinstance(reply, WeChatReply): return reply.render() elif is_string(reply): reply = TextReply(message=message, content=reply) return reply.render() elif isinstance(reply, list) and all([len(x) == 4 for x in reply]): if len(reply) > 10: raise AttributeError("Can't add more than 10 articles" " in an ArticlesReply") r = ArticlesReply(message=message) for article in reply: article = Article(*article) r.add_article(article) return r.render() elif isinstance(reply, list) and 3 <= len(reply) <= 4: if len(reply) == 3: # 如果数组长度为3, 那么高质量音乐链接的网址和普通质量的网址相同。 reply.append(reply[-1]) title, description, url, hq_url = reply reply = MusicReply(message=message, title=title, description=description, url=url, hq_url=hq_url) return reply.render()
def __issue_parse_summary(issue, dom): ''' Parse the current comic's summary details from the DOM. ''' # grab the issue description, and do a bunch of modifications and # replaces to massage it into a nicer "summary" text # PARAGRAPH = re.compile(r'<br />') OVERVIEW = re.compile('Overview') PARAGRAPH = re.compile(r'<[bB][rR] ?/?>|<[Pp] ?>') NBSP = re.compile(' ?') MULTISPACES = re.compile(' {2,}') STRIP_TAGS = re.compile('<.*?>') LIST_OF_COVERS = re.compile('(?is)list of covers.*$') if is_string(dom.results.description): summary_s = OVERVIEW.sub('', dom.results.description) summary_s = PARAGRAPH.sub('\n', summary_s) summary_s = STRIP_TAGS.sub('', summary_s) summary_s = MULTISPACES.sub(' ', summary_s) summary_s = NBSP.sub(' ' , summary_s) summary_s = PARAGRAPH.sub('\n', summary_s) summary_s = summary_s.replace(r'&', '&') summary_s = summary_s.replace(r'"', '"') summary_s = summary_s.replace(r'<', '<') summary_s = summary_s.replace(r'>', '>') summary_s = LIST_OF_COVERS.sub('', summary_s); issue.summary_s = summary_s.strip()
def create_reply(reply, message=None): if isinstance(reply, WeChatReply): return reply.render() elif is_string(reply): reply = TextReply(message=message, content=reply) return reply.render() elif isinstance(reply, list) and all([len(x) == 4 for x in reply]): if len(reply) > 10: raise AttributeError("Can't add more than 10 articles" " in an ArticlesReply") r = ArticlesReply(message=message) for article in reply: article = Article(*article) r.add_article(article) return r.render() elif isinstance(reply, list) and 3 <= len(reply) <= 4: if len(reply) == 3: # 如果数组长度为3, 那么高质量音乐链接的网址和普通质量的网址相同。 reply.append(reply[-1]) title, description, url, hq_url = reply reply = MusicReply( message=message, title=title, description=description, url=url, hq_url=hq_url ) return reply.render()
def kebab_case(string): """ Return a string to kebab-case :param string: :return string: Examples:: >>> kebab_case("Zen of Python") """ is_string(string) return ''.join(['-' + i.lower() if i.isupper() else i for i in string]).lstrip('-')
def _declare_command (self, name, callback_function, doc, overwrite, is_pre_flight): if (not utils.is_string(name)): raise ValueError( "Invalid value for magic command name: " "Must be a string") if (not utils.is_callable(callback_function)): raise ValueError( "Invalid value for magic command callback function: " "Must be a callable") if (doc is None): doc = callback_function.__doc__ if (self.has_command(name) and (not overwrite)): raise Exception( "Invalid value for magic command name: " "Name '%s' already taken" % name) def _wrapper (doc, mc_args, *args_from_kernel): if (doc is None): kwargs = {} else: # we parse the arguments using docopt try: if (mc_args is None): mc_args = '' kwargs = docopt.docopt(doc, mc_args, help = True) except docopt.DocoptExit as exception: usage = ' '.join(map( lambda x: x.strip(), str(exception).splitlines())) raise Exception("Invalid syntax, %s" % usage) # we explicitly remove keys without values for (key, value) in kwargs.items(): if (value is None): del kwargs[key] else: # remove any surrounding quotes # and whitespaces from the value kwargs[key] = re.sub(r"^['\"\s]|['\"\s]$", '', value) _logger.debug( "executing %s-flight command '%s' " "(callback function: %s)" % ( "pre" if is_pre_flight else "post", name.lower(), callback_function)) return callback_function(*args_from_kernel, **kwargs) self._magic_commands[name.lower()] = ( functools.partial(_wrapper, doc), is_pre_flight) _logger.debug( "added %s-flight command '%s' (callback function: %s)" % ( "pre" if is_pre_flight else "post", name.lower(), callback_function))
def serialize_expr(ast, open='(', close=')', between=', ', precscore=-1): if is_string(ast): return ast elif type(ast) is list: if len(ast) > 0: ret = open + serialize_expr(ast[0]) for el in ast[1:]: ret += between + serialize_expr(el, open, close, between) return ret + close else: return open + close assert isinstance(ast, astnode) if ast.fun in precedence: between = ast.fun if (ast.fun in dont_space_it) else ' ' + ast.fun + ' ' open, close = ('', '') if precscore < precedence[ast.fun] else ('(',')') return serialize_expr(ast.args[1:], open, close, between, precedence[ast.fun]) elif ast.fun == 'access': # TODO do this fancier. return serialize_expr(ast[1]) + '[' + serialize_expr(ast[2]) + ']' elif ast.fun == 'array_lit': return serialize_expr(ast.args[1:], '[', ']') elif ast.fun == 'str': assert len(ast) == 2 return '"' + ast[1] + '"' else: return ast.fun + serialize_expr(ast.args[1:])
def analyze(ast): if utils.is_string(ast): ast = parse(ast) ast = rewrite(preprocess(ast)) data = {"varhash": {}, "inner": []} analyze_and_varify_ast(ast, data) return data
def __init__(self, name, model, update_func): self.name = name self.model = model self.update_func = update_func self.value = list() # if is_simple_model(model): # try : # v = eval(model) # except Exception: # v = model # else: # print "full schema not support yet." value = None if type(model) is dict and "initial" in model: value = model["initial"] if "format" in model: format = model["format"] if utils.is_string(value) and format in [ "number", "dict", "str", "list" ]: log().debug("eval [value:%s] in [format:%s]", value, format) if len(value) > 0: value = eval(value) else: value = None self.set_value(value)
def __issue_parse_series_details(issue, dom): ''' Parses the current comic's series details out of the DOM ''' series_id = dom.results.volume.id # if the start year and publisher_s have been cached (because we already # accessed them once this session) use the cached values. else # grab those values from comicvine, and cache em so we don't have to # hit comic vine for them again (at least not in this session) global __series_details_cache if __series_details_cache == None: raise Exception(__name__ + " module isn't initialized!") cache = __series_details_cache if series_id in cache: volume_year_n = cache[series_id][0] publisher_s = cache[series_id][1] else: # contact comicvine to extract details for this comic book series_dom = cvconnection._query_series_details_dom( __api_key, series_id) if series_dom is None: raise Exception("can't get details about series " + series_id) # start year volume_year_n = -1 if "start_year" in series_dom.results.__dict__ and \ is_string(series_dom.results.start_year): try: volume_year_n = int(series_dom.results.start_year) except: pass # bad start year format...just keep going # publisher publisher_s = '' if "publisher" in series_dom.results.__dict__ and \ "name" in series_dom.results.publisher.__dict__ and \ is_string(series_dom.results.publisher.name): publisher_s = series_dom.results.publisher.name cache[series_id] = (volume_year_n, publisher_s) # check if there's the current publisher really is the true publisher, or # if it's really an imprint of another publisher. issue.publisher_s = cvimprints.find_parent_publisher(publisher_s) if issue.publisher_s != publisher_s: issue.imprint_s = publisher_s issue.volume_year_n = volume_year_n
def __issue_parse_series_details(issue, dom): """ Parses the current comic's series details out of the DOM """ series_id = dom.results.volume.id # if the start year and publisher_s have been cached (because we already # accessed them once this session) use the cached values. else # grab those values from comicvine, and cache em so we don't have to # hit comic vine for them again (at least not in this session) global __series_details_cache if __series_details_cache == None: raise Exception(__name__ + " module isn't initialized!") cache = __series_details_cache if series_id in cache: volume_year_n = cache[series_id][0] publisher_s = cache[series_id][1] else: # contact comicvine to extract details for this comic book series_dom = cvconnection._query_series_details_dom(__api_key, series_id) if series_dom is None: raise Exception("can't get details about series " + series_id) # start year volume_year_n = -1 if "start_year" in series_dom.results.__dict__ and is_string(series_dom.results.start_year): try: volume_year_n = int(series_dom.results.start_year) except: pass # bad start year format...just keep going # publisher publisher_s = "" if ( "publisher" in series_dom.results.__dict__ and "name" in series_dom.results.publisher.__dict__ and is_string(series_dom.results.publisher.name) ): publisher_s = series_dom.results.publisher.name cache[series_id] = (volume_year_n, publisher_s) # check if there's the current publisher really is the true publisher, or # if it's really an imprint of another publisher. issue.publisher_s = cvimprints.find_parent_publisher(publisher_s) if issue.publisher_s != publisher_s: issue.imprint_s = publisher_s issue.volume_year_n = volume_year_n
def update_profesor(profesor, campos): try: # comprobando username if 'username' in campos.keys(): res = Profesor.objects.filter(username=campos['username']) if res.count() == 0: if not (re.match(r'^[a-z][_a-z0-9]+(@ugr\.es)$', campos['username'])): raise NameError("El correo no es correcto") else: profesor.username = campos['username'] else: raise NameError("No existe el profesor") # comprobando nombre if 'first_name' in campos.keys(): if campos['first_name'] == '' or not utils.is_string( campos['first_name']): raise NameError("Error en el nombre del profesor") else: profesor.first_name = campos['first_name'] # comprobando apellidos if 'last_name' in campos.keys(): if campos['last_name'] == '' or not utils.is_string( campos['last_name']): raise NameError("Error en los apellidos del profesor") else: profesor.last_name = campos['last_name'] # comprobando departamento if 'departamento' in campos.keys(): if campos['departamento'] == '' or not utils.is_string( campos['departamento']): raise NameError("Error en el departamento") else: profesor.departamento = campos['departamento'] profesor.save() return dict(status=True, data=Profesor.objects.get(username=profesor.username)) except NameError as e: return dict(status=False, message=e.message) except: return dict(status=False, message="El correo no es correcto")
def uppercase(string): """ Return a string in uppercase :param string: :return string: Examples:: >>> uppercase("zenofpython") >>> ZENOFPYTHON """ is_string(string) return string.upper()
def lowercase(string): """ Return a string in lowercase :param string: :return string: Examples:: >>> lowercase("ZENOFPYTHON") >>> zenofpython """ is_string(string) return string.lower()
def notify(title, description, icon): if icon and not is_string(icon): icon = growl_raw_image(icon) growler.notify(noteType="Now Playing", title=title, description=description, icon=icon)
def __init__(self, contract_interface): if is_string(contract_interface): contract_interface = json_decode(contract_interface) self.constructor_data = None self.function_data = {} self.event_data = {} for description in contract_interface: encode_types = [ element['type'] for element in description['inputs'] ] signature = [(element['type'], element['name']) for element in description['inputs']] # type can be omitted, defaulting to function if description.get('type', 'function') == 'function': normalized_name = _normalize_name(description['name']) decode_types = [ element['type'] for element in description['outputs'] ] self.function_data[normalized_name] = { 'prefix': method_id(normalized_name, encode_types), 'encode_types': encode_types, 'decode_types': decode_types, 'is_constant': description.get('constant', False), 'signature': signature, } elif description['type'] == 'event': normalized_name = _normalize_name(description['name']) indexed = [ element['indexed'] for element in description['inputs'] ] names = [element['name'] for element in description['inputs']] self.event_data[event_id(normalized_name, encode_types)] = { 'types': encode_types, 'name': normalized_name, 'names': names, 'indexed': indexed, 'anonymous': description.get('anonymous', False), } elif description['type'] == 'constructor': if self.constructor_data is not None: raise ValueError('Only one constructor is supported.') self.constructor_data = { 'encode_types': encode_types, 'signature': signature, } else: raise ValueError('Unknown type {}'.format(description['type']))
def encode(self, first_text, second_text=None, max_length=None, first_length=None, second_length=None): """输出文本对应token id和segment id 如果传入first_length,则强行padding第一个句子到指定长度; 同理,如果传入second_length,则强行padding第二个句子到指定长度。 """ if is_string(first_text): first_tokens = self.tokenize(first_text) else: first_tokens = first_text if second_text is None: second_tokens = None elif is_string(second_text): second_tokens = self.tokenize(second_text, add_cls=False) else: second_tokens = second_text if max_length is not None: self.truncate_sequence(max_length, first_tokens, second_tokens, -2) first_token_ids = self.tokens_to_ids(first_tokens) if first_length is not None: first_token_ids = first_token_ids[:first_length] first_token_ids.extend([self._token_pad_id] * (first_length - len(first_token_ids))) first_segment_ids = [0] * len(first_token_ids) if second_text is not None: second_token_ids = self.tokens_to_ids(second_tokens) if second_length is not None: second_token_ids = second_token_ids[:second_length] second_token_ids.extend( [self._token_pad_id] * (second_length - len(second_token_ids))) second_segment_ids = [1] * len(second_token_ids) first_token_ids.extend(second_token_ids) first_segment_ids.extend(second_segment_ids) return first_token_ids, first_segment_ids
def __parse_image_url(dom): """ Grab the image for this issue out of the given DOM fragment. """ imgurl_s = None if "image" in dom.__dict__: if "small_url" in dom.image.__dict__ and is_string(dom.image.small_url): imgurl_s = dom.image.small_url elif "medium_url" in dom.image.__dict__ and is_string(dom.image.medium_url): imgurl_s = dom.image.medium_url elif "large_url" in dom.image.__dict__ and is_string(dom.image.large_url): imgurl_s = dom.image.large_url elif "super_url" in dom.image.__dict__ and is_string(dom.image.super_url): imgurl_s = dom.image.super_url elif "thumb_url" in dom.image.__dict__ and is_string(dom.image.thumb_url): imgurl_s = dom.image.thumb_url return imgurl_s
def set_root_hash(self, root_hash): assert utils.is_string(root_hash) assert len(root_hash) in [0, 32] if root_hash == BLANK_ROOT: self.root_node = BLANK_NODE self._root_hash = BLANK_ROOT return self.root_node = self._decode_to_node(root_hash) self._root_hash = root_hash
def trimmed_case(string): """ Return a trimmed string :param string: :return string: Examples:: >>> trimmed_case("Zen Of Python ") >>> trimmed_case(" Zen Of Python") >>> Zen Of Python # for both use cases """ is_string(string) return string.strip()
def update_profesor(profesor, campos): try: # comprobando username if 'username' in campos.keys(): res = Profesor.objects.filter(username=campos['username']) if res.count() == 0: if not (re.match(r'^[a-z][_a-z0-9]+(@ugr\.es)$', campos['username'])): raise NameError("El correo no es correcto") else: profesor.username = campos['username'] else: raise NameError("No existe el profesor") # comprobando nombre if 'first_name' in campos.keys(): if campos['first_name'] == '' or not utils.is_string(campos['first_name']): raise NameError("Error en el nombre del profesor") else: profesor.first_name = campos['first_name'] # comprobando apellidos if 'last_name' in campos.keys(): if campos['last_name'] == '' or not utils.is_string(campos['last_name']): raise NameError("Error en los apellidos del profesor") else: profesor.last_name = campos['last_name'] # comprobando departamento if 'departamento' in campos.keys(): if campos['departamento'] == '' or not utils.is_string(campos['departamento']): raise NameError("Error en el departamento") else: profesor.departamento = campos['departamento'] profesor.save() return dict(status=True, data=Profesor.objects.get(username=profesor.username)) except NameError as e: return dict(status=False, message=e.message) except: return dict(status=False, message="El correo no es correcto")
def delete(self, key): if not utils.is_string(key): raise Exception("Key must be string") if len(key) > 32: raise Exception("Max key length is 32") self.root_node = self._delete_and_delete_storage( self.root_node, bin_to_nibbles(utils.to_string(key))) self._update_root_hash()
def get_value(value, v): if utils.is_callable(value): return value() elif value == "$self": return v elif value == "$clock": return Clock.get() elif utils.is_string(value) and value.startswith("$"): return res_manager.get(value[1:]) else: return value
def create_user(self, password=None, **kwargs): try: if kwargs.get('email'): if not (kwargs.get('email') or not (re.match(r'^[a-z][_a-z0-9]+(@ugr\.es)$', kwargs.get('email')))): raise NameError("El correo no es correcto") res = Profesor.objects.filter(email=kwargs.get('email')) if res.count() != 0: raise NameError("El profesor ya existe") if kwargs.get('dni') and kwargs.get('dni') is not '': # exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es) if not re.match(r'(\d{8})([-]?)([A-Z]{1})', kwargs.get('dni')): raise NameError("Error en el DNI del profesor") if not kwargs.get('first_name') or not utils.is_string(kwargs.get('first_name')): raise NameError("Error en el nombre del profesor") if not kwargs.get('last_name') or not utils.is_string(kwargs.get('last_name')): raise NameError("Error en los apellidos del profesor") if not kwargs.get('departamento') or not isinstance(kwargs.get('departamento'), Departamento): raise NameError("Error en el departamento") usuario = self.model.objects.create(email=kwargs.get('email'), dni=kwargs.get('dni'), first_name=kwargs.get('first_name'), last_name=kwargs.get('last_name'), departamento=kwargs.get('departamento')) # comprobando si es Jefe de departamento if kwargs.get('jefe_departamento'): grupo_jefe_departamento = Grupos.objects.get(name='Jefe de Departamento') grupo_jefe_departamento.user_set.add(usuario) grupo_profesores = Grupos.objects.get(name='Profesores') usuario.set_password(password) usuario.save() grupo_profesores.user_set.add(usuario) if usuario.email: utils.enviar_email_reset_password(usuario.email) return dict(status=True, data=Profesor.objects.get(email=usuario.email)) except NameError as e: return dict(status=False, message=e.message)
def pascal_to_snake_case(string): """ Return a CamelCase to snake_case :param string: :return string: Examples:: >>> camel_to_snake_case("ZenOfPython") >>> camel_to_snake_case("ZenOfJavascript") >>> zen_of_python >>> zen_of_javascript """ is_string(string) snake_case_str = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', snake_case_str).lower()
def update_alumno(alumno, campos): try: # comprobando username if 'username' in campos.keys(): res = Alumno.objects.filter(username=campos['username']) if res.count() == 0: if not utils.is_string(campos['username']) or not re.match( r'^[a-z][_a-z0-9]+(@correo\.ugr\.es)$', campos['username']): raise NameError("El correo no es correcto") else: alumno.username = campos['username'] else: raise NameError("El alumno indicado no existe") # comprobando nombre if 'first_name' in campos.keys(): if campos['first_name'] == '' or not utils.is_string( campos['first_name']): raise NameError("Nombre incorrecto") else: alumno.first_name = campos['first_name'] # comprobando apellidos if 'last_name' in campos.keys(): if campos['last_name'] == '' or not utils.is_string( campos['last_name']): raise NameError("Apellidos incorrectos") else: alumno.last_name = campos['last_name'] alumno.save() return dict(status=True, data=Alumno.objects.get(username=alumno.username)) except NameError as e: return dict(status=False, message=e.message) except: return dict(status=False, message="El correo no es correcto")
def css_camelcase_case(string): """ Return a string to .cssCase - :param string: :return string: Examples:: >>> css_camecase_case("Zen of Python") >>> css_camecase_case("Zen-of-Python") >>> css_camecase_case("Zen.of.Python") >>> css_camecase_case("zen OF pYthon") >>> css_camecase_case("ZEN of_PYTHON") >>> css_camecase_case("zen.OF-python") >>> .zenOfPython # for all above use cases """ is_string(string) dot = "." return dot + camel_case(string)
def __parse_image_url(dom): ''' Grab the image for this issue out of the given DOM fragment. ''' imgurl_s = None if "image" in dom.__dict__: if "small_url" in dom.image.__dict__ and \ is_string(dom.image.small_url): imgurl_s = dom.image.small_url elif "medium_url" in dom.image.__dict__ and \ is_string(dom.image.medium_url): imgurl_s = dom.image.medium_url elif "large_url" in dom.image.__dict__ and \ is_string(dom.image.large_url): imgurl_s = dom.image.large_url elif "super_url" in dom.image.__dict__ and \ is_string(dom.image.super_url): imgurl_s = dom.image.super_url elif "thumb_url" in dom.image.__dict__ and \ is_string(dom.image.thumb_url): imgurl_s = dom.image.thumb_url return imgurl_s
def __issue_parse_simple_stuff(issue, dom): ''' Parses in the 'easy' parts of the DOM ''' if is_string(dom.results.id): issue.issue_key = dom.results.id if is_string(dom.results.volume.id): issue.series_key = dom.results.volume.id if is_string(dom.results.volume.name): issue.series_name_s = dom.results.volume.name.strip() if is_string(dom.results.issue_number): issue.issue_num_s = dom.results.issue_number.strip() if is_string(dom.results.site_detail_url) and \ dom.results.site_detail_url.startswith("http"): issue.webpage_s = dom.results.site_detail_url if is_string(dom.results.name): issue.title_s = dom.results.name.strip(); # grab the published (front cover) date if "cover_date" in dom.results.__dict__ and \ is_string(dom.results.cover_date) and \ len(dom.results.cover_date) > 1: try: parts = [int(x) for x in dom.results.cover_date.split('-')] issue.pub_year_n = parts[0] if len(parts) >= 1 else None issue.pub_month_n = parts[1] if len(parts) >=2 else None # corylow: can we ever add this back in?? #issue.pub_day_n = parts[2] if len(parts) >= 3 else None except: pass # got an unrecognized date format...? should be "YYYY-MM-DD" # grab the released (in store) date if "store_date" in dom.results.__dict__ and \ is_string(dom.results.store_date) and \ len(dom.results.store_date) > 1: try: parts = [int(x) for x in dom.results.store_date.split('-')] issue.rel_year_n = parts[0] if len(parts) >= 1 else None issue.rel_month_n = parts[1] if len(parts) >=2 else None issue.rel_day_n = parts[2] if len(parts) >= 3 else None except: pass # got an unrecognized date format...? should be "YYYY-MM-DD" # grab the image for this issue and store it as the first element # in the list of issue urls. image_url_s = __parse_image_url(dom.results) if image_url_s: issue.image_urls_sl.append(image_url_s)
def update_alumno(alumno, campos): try: # comprobando username if 'username' in campos.keys(): res = Alumno.objects.filter(username=campos['username']) if res.count() == 0: if not utils.is_string(campos['username']) or not re.match(r'^[a-z][_a-z0-9]+(@correo\.ugr\.es)$', campos['username']): raise NameError("El correo no es correcto") else: alumno.username = campos['username'] else: raise NameError("El alumno indicado no existe") # comprobando nombre if 'first_name' in campos.keys(): if campos['first_name'] == '' or not utils.is_string(campos['first_name']): raise NameError("Nombre incorrecto") else: alumno.first_name = campos['first_name'] # comprobando apellidos if 'last_name' in campos.keys(): if campos['last_name'] == '' or not utils.is_string(campos['last_name']): raise NameError("Apellidos incorrectos") else: alumno.last_name = campos['last_name'] alumno.save() return dict(status=True, data=Alumno.objects.get(username=alumno.username)) except NameError as e: return dict(status=False, message=e.message) except: return dict(status=False, message="El correo no es correcto")
def _append_token_by_type(self, value): if utils.is_string(value): self._append_string(value) elif utils.is_number(value): self._append_number(value) elif value is None: self._append_null() elif value == True: self._append_true() elif value == False: self._append_false() elif utils.is_json_array(value): self._read_json_array(value) elif utils.is_dict(value): self._read_dict(value)
def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 icon_file = "" if is_string(icon): # File path icon_file = icon elif icon: # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
def __init__(self, message=None, star=False, **kwargs): if "source" not in kwargs and isinstance(message, WeChatMessage): kwargs["source"] = message.target if "target" not in kwargs and isinstance(message, WeChatMessage): kwargs["target"] = message.source if 'time' not in kwargs: kwargs["time"] = int(time.time()) if star: kwargs["flag"] = 1 else: kwargs["flag"] = 0 args = dict() for k, v in kwargs.items(): if is_string(v): v = to_text(v) args[k] = v self._args = args
def write_serpent(ast, output='', tabs=0): if isinstance(output, (str,unicode)): stream = StringIO(unicode(output)) write_serpent(ast, stream, tabs) stream.seek(0) return stream.read() if is_string(ast): return after_tabs(output, tabs, ast + '\n') if not isinstance(ast, astnode): raise Exception('what is', ast, type(ast)) if ast.fun in ['outer', 'seq']: for el in ast.args[1:]: write_serpent(el, output, tabs) elif ast.fun == 'if': # Make it fit the paradigm. return write_serpent(astnode('cond', cond_args(ast.args[1:])), output, tabs) elif ast.fun in bodied: serialize_bodied(ast, output, tabs, ast.fun) else: after_tabs(output, tabs, serialize_expr(ast) + '\n')
def _query_image( ref, lasttry = False ): ''' ComicVine implementation of the identically named method in the db.py ''' retval = None # the Image object that we will return # 1. determine the URL image_url_s = None if isinstance(ref, SeriesRef): image_url_s = ref.thumb_url_s elif isinstance(ref, IssueRef): image_url_s = ref.thumb_url_s elif is_string(ref): image_url_s = ref # 2. attempt to load the image for the URL if image_url_s: response = None response_stream = None try: cvconnection.wait_until_ready() # throttle our request speed request = WebRequest.Create(image_url_s) request.UserAgent = "[ComicVineScraper, version " + \ Resources.SCRIPT_VERSION + "]" response = request.GetResponse() response_stream = response.GetResponseStream() retval = Image.FromStream(response_stream) except: if lasttry: log.debug_exc('ERROR retry image load failed:') retval = None else: log.debug('RETRY loading image -> ', image_url_s) retval = _query_image( ref, True ) finally: if response: response.Dispose() if response_stream: response_stream.Dispose() # if this value is stil None, it means an error occurred, or else comicvine # simply doesn't have any Image for the given ref object return retval
def _query_image(ref, lasttry=False): """ ComicVine implementation of the identically named method in the db.py """ retval = None # the Image object that we will return # 1. determine the URL image_url_s = None if isinstance(ref, SeriesRef): image_url_s = ref.thumb_url_s elif isinstance(ref, IssueRef): image_url_s = ref.thumb_url_s elif is_string(ref): image_url_s = ref # 2. attempt to load the image for the URL if image_url_s: response = None response_stream = None try: request = WebRequest.Create(image_url_s) response = request.GetResponse() response_stream = response.GetResponseStream() retval = Image.FromStream(response_stream) except: if lasttry: log.debug_exc("ERROR retry image load failed:") retval = None else: log.debug("RETRY loading image -> ", image_url_s) retval = _query_image(ref, True) finally: if response: response.Dispose() if response_stream: response_stream.Dispose() # if this value is stil None, it means an error occurred, or else comicvine # simply doesn't have any Image for the given ref object return retval
def __init__(self, id, search_terms_s=""): ''' Creates a new SearchFormResult object with the given ID. id -> the result ID. Must be one of "SEARCH" (proceed with search), "CANCEL" (cancel entire scrape operation), "SKIP" (skip this book) or "PERMSKIP" (permanently skip this book) search_terms_s -> the search terms to search on when our ID is "SEARCH". This value should be empty for all other IDs. ''' if id != "SEARCH" and id != "CANCEL" and \ id != "SKIP" and id != "PERMSKIP": raise Exception() search_terms_s = search_terms_s.strip() if id=="SEARCH" and not search_terms_s: raise Exception() self.__id = id self.__search_terms_s = search_terms_s \ if id=="SEARCH" and utils.is_string(search_terms_s) else ""
def __init__(self, issue_num_s, issue_key, title_s, thumb_url_s): ''' Initializes a newly created IssueRef, checking the given parameters to make sure they are legal, and then storing them as read-only properties. issue_key --> a database specific object (i.e. the 'memento' design pattern) that can be used by the database at a later date to unambiguously identify this comic book issue. This cannot be None, and it should have a useful __str__ method. It should also be unique for each comic book issue. issue_num_s --> a string describing this comic's issue number (which may not be a number at all, it can be '' or '1A' or 'A', etc. It cannot be None.) title_s --> a string describing the title of this comic book issue. if no title is available, pass in "" here. thumb_url_s --> the (http) url of an appropriate thumbnail image for this comic book issue (usually the cover.) if no image is available, pass in None here. ''' if not issue_key or len(sstr(issue_key).strip()) == 0 \ or issue_num_s is None: raise Exception() self.__issue_key = issue_key self.__issue_num_s = sstr(issue_num_s).strip() self.__title_s = title_s if utils.is_string(title_s) else "" # make sure thumb_url_s is either valid, or none (but not ''). self.__thumb_url_s =None if not thumb_url_s else sstr(thumb_url_s).strip() if self.__thumb_url_s == '': self.__thumb_url_s = None # used only for comparisons self._cmpkey_s = sstr(self.issue_key)
def __issue_parse_summary(issue, dom): """ Parse the current comic's summary details from the DOM. """ # grab the issue description, and do a bunch of modifications and # replaces to massage it into a nicer "summary" text # PARAGRAPH = re.compile(r'<br />') OVERVIEW = re.compile("Overview") PARAGRAPH = re.compile(r"<[bB][rR] ?/?>|<[Pp] ?>") NBSP = re.compile(" ?") MULTISPACES = re.compile(" {2,}") STRIP_TAGS = re.compile("<.*?>") if is_string(dom.results.description): summary_s = OVERVIEW.sub("", dom.results.description) summary_s = PARAGRAPH.sub("\n", summary_s) summary_s = STRIP_TAGS.sub("", summary_s) summary_s = MULTISPACES.sub(" ", summary_s) summary_s = NBSP.sub(" ", summary_s) summary_s = PARAGRAPH.sub("\n", summary_s) summary_s = summary_s.replace(r"&", "&") summary_s = summary_s.replace(r""", '"') summary_s = summary_s.replace(r"<", "<") summary_s = summary_s.replace(r">", ">") issue.summary_s = summary_s.strip()
def decint(n, signed=False): if isinstance(n, str): n = utils.to_string(n) if is_numeric(n): min_, max_ = (-TT255, TT255 - 1) if signed else (0, TT256 - 1) if n > max_ or n < min_: raise EncodingError("Number out of range: %r" % n) return n elif is_string(n): if len(n) == 40: n = decode_hex(n) if len(n) > 32: raise EncodingError("String too long: %r" % n) i = big_endian_to_int(n) return (i - TT256) if signed and i >= TT255 else i elif n is True: return 1 elif n is False or n is None: return 0 else: raise EncodingError("Cannot encode integer: %r" % n)