code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def resolve_targetfile(self, args, require_sim_name=False): ttype = args.get('ttype') if is_null(ttype): sys.stderr.write('Target type must be specified') return (None, None) sim = args.get('sim') if is_null(sim): if require_sim_name: s...
Get the name of the targetfile based on the job arguments
def CheckIfCanStartClientFlow(self, username, flow_name): del username flow_cls = flow.GRRFlow.GetPlugin(flow_name) if not flow_cls.category: raise access_control.UnauthorizedAccess( "Flow %s can't be started via the API." % flow_name)
Checks whether a given user can start a given flow.
def compound_id(obj): if isinstance(obj, (Category, Session)): raise TypeError('Compound IDs are not supported for this entry type') elif isinstance(obj, Event): return unicode(obj.id) elif isinstance(obj, Contribution): return '{}.{}'.format(obj.event_id, obj.id) elif isinstance...
Generate a hierarchical compound ID, separated by dots.
def add_dup(self, pkt): log.debug("Recording a dup of %s", pkt) s = str(pkt) if s in self.dups: self.dups[s] += 1 else: self.dups[s] = 1 tftpassert(self.dups[s] < MAX_DUPS, "Max duplicates reached")
This method adds a dup for a packet to the metrics.
def __normalize_progress(self): progress = self['funding_progress'] if progress % 10 != 0: progress = round(float(progress) / 10) progress = int(progress) * 10 self['funding_progress'] = progress
Adjust the funding progress filter to be a factor of 10
def check_unique(self): errors = [] service_id = getattr(self, 'id', None) fields = [('location', views.service_location), ('name', views.service_name)] for field, view in fields: value = getattr(self, field, None) if not value: c...
Check the service's name and location are unique
def _convert_type(self, data_type): if (data_type == 1) or (data_type == 41): dt_string = 'b' elif data_type == 2: dt_string = 'h' elif data_type == 4: dt_string = 'i' elif (data_type == 8) or (data_type == 33): dt_string = 'q' elif...
CDF data types to python struct data types
def _create_body(self, name, description=None, volume=None, force=False): body = {"snapshot": { "display_name": name, "display_description": description, "volume_id": volume.id, "force": str(force).lower(), }} return body
Used to create the dict required to create a new snapshot
def init_app(application): for code in werkzeug.exceptions.default_exceptions: application.register_error_handler(code, handle_http_exception)
Associates the error handler
def param(name, help=""): def decorator(func): params = getattr(func, "params", []) _param = Param(name, help) params.insert(0, _param) func.params = params return func return decorator
Decorator that add a parameter to the wrapped command or function.
def load_cash_balances_with_children(self, root_account_fullname: str): assert isinstance(root_account_fullname, str) svc = AccountsAggregate(self.book) root_account = svc.get_by_fullname(root_account_fullname) if not root_account: raise ValueError("Account not found", root_a...
loads data for cash balances
def _dissect_msg(self, match): recvfrom = match.group(1) frame = bytes.fromhex(match.group(2)) if recvfrom == 'E': _LOGGER.warning("Received erroneous message, ignoring: %s", frame) return (None, None, None, None, None) msgtype = self._get_msgtype(frame[0]) ...
Split messages into bytes and return a tuple of bytes.
def scheduler(rq, ctx, verbose, burst, queue, interval, pid): "Periodically checks for scheduled jobs." scheduler = rq.get_scheduler(interval=interval, queue=queue) if pid: with open(os.path.expanduser(pid), 'w') as fp: fp.write(str(os.getpid())) if verbose: level = 'DEBUG' ...
Periodically checks for scheduled jobs.
def _auth(self, username, password) : self.user_credentials = self.call('auth', {'username': username, 'password': password}) if 'error' in self.user_credentials: raise T411Exception('Error while fetching authentication token: %s'\ % self.user_credentials['error']) ...
Authentificate user and store token
def erank(self): r = self.r n = self.n d = self.d if d <= 1: er = 0e0 else: sz = _np.dot(n * r[0:d], r[1:]) if sz == 0: er = 0e0 else: b = r[0] * n[0] + n[d - 1] * r[d] if d is 2: ...
Effective rank of the TT-vector
def rotateCD(self,orient): _delta = self.get_orient() - orient if _delta == 0.: return _rot = fileutil.buildRotMatrix(_delta) _cd = N.array([[self.cd11,self.cd12],[self.cd21,self.cd22]],dtype=N.float64) _cdrot = N.dot(_cd,_rot) self.cd11 = _cdrot[0][0] ...
Rotates WCS CD matrix to new orientation given by 'orient'
def as_text(self, max_rows=0, sep=" | "): if not max_rows or max_rows > self.num_rows: max_rows = self.num_rows omitted = max(0, self.num_rows - max_rows) labels = self._columns.keys() fmts = self._get_column_formatters(max_rows, False) rows = [[fmt(label, label=True)...
Format table as text.
def remove_index(self, index): 'remove one or more indices' index_rm, single = convert_key_to_index(force_list(self.indices.keys()), index) if single: index_rm = [index_rm] index_new = [i for i in range(len(self.indices)) if i not in index_rm] if not index_new: ...
remove one or more indices
def fincre(oldname): x=re.search('_(?P<version>[0-9][0-9][0-9])_syn',oldname) version=x.group('version') newversion="%03d"%(int(version)+1) ans=oldname.replace(version,newversion) return ans
Increment the synphot version number from a filename
def _parse_entity(self): reset = self._head try: self._push(contexts.HTML_ENTITY) self._really_parse_entity() except BadRoute: self._head = reset self._emit_text(self._read()) else: self._emit_all(self._pop())
Parse an HTML entity at the head of the wikicode string.
def check_length_of_initial_values(self, init_values): num_nests = self.rows_to_nests.shape[1] num_index_coefs = self.design.shape[1] assumed_param_dimensions = num_index_coefs + num_nests if init_values.shape[0] != assumed_param_dimensions: msg = "The initial values are of t...
Ensures that the initial values are of the correct length.
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
Detect if table has a corresponding FTS virtual table and return it
def position_p(self): self._position_p, value = self.get_attr_int(self._position_p, 'hold_pid/Kp') return value
The proportional constant for the position PID.
def squarelim(): fig = gcf() xmin, xmax = fig.xlim ymin, ymax = fig.ylim zmin, zmax = fig.zlim width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)]) xc = (xmin + xmax) / 2 yc = (ymin + ymax) / 2 zc = (zmin + zmax) / 2 xlim(xc - width / 2, xc + width / 2) ylim(yc - w...
Set all axes with equal aspect ratio, such that the space is 'square'.
def node_detail(node_name): token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") node = nago.core.get_node(node_name) return render_template('node_detail.html', no...
View one specific node
def _api_model_patch_replace(conn, restApiId, modelName, path, value): response = conn.update_model(restApiId=restApiId, modelName=modelName, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
the replace patch operation on a Model resource
def line_break(self): for i in range(self.slide.insert_line_break): if not self._in_tag(ns("text", "p")): self.add_node(ns("text", "p")) self.add_node(ns("text", "line-break")) self.pop_node() if self.cur_node.tag == ns("text", "p"): ...
insert as many line breaks as the insert_line_break variable says
def _get_root(self): _DEFAULT_USER_DETAILS = {"level": 20, "password": "", "sshkeys": []} root = {} root_table = junos_views.junos_root_table(self.device) root_table.get() root_items = root_table.items() for user_entry in root_items: username = "root" ...
get root user password.
def Godeps(self): dict = [] for package in sorted(self._packages.keys()): dict.append({ "ImportPath": str(package), "Rev": str(self._packages[package]) }) return dict
Return the snapshot in Godeps.json form
def assets(self) -> List[Asset]: return list(filter(is_element(Asset), self.content))
Returns the assets in the transaction.
def _write(self, session, openFile, replaceParamFile): openFile.write('GRIDSTREAMFILE\n') openFile.write('STREAMCELLS %s\n' % self.streamCells) for cell in self.gridStreamCells: openFile.write('CELLIJ %s %s\n' % (cell.cellI, cell.cellJ)) openFile.write('NUMNODES %s\n...
Grid Stream File Write to File Method
def com_google_fonts_check_family_panose_familytype(ttFonts): failed = False familytype = None for ttfont in ttFonts: if familytype is None: familytype = ttfont['OS/2'].panose.bFamilyType if familytype != ttfont['OS/2'].panose.bFamilyType: failed = True if failed: yield FAIL, ("PANOSE fa...
Fonts have consistent PANOSE family type?
def WriteProtoFile(self, printer): self.Validate() extended_descriptor.WriteMessagesFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
Write the messages file to out as proto.
def flush(self): if self.__buffer.tell() > 0: self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip(), record_filter=StdErrWrapper.__filter_record) self.__buffer.truncate(0) self.__buffer.seek(0)
Flush the buffer, if applicable.
def fmt_duration(duration): try: return fmt.human_duration(float(duration), 0, 2, True) except (ValueError, TypeError): return "N/A".rjust(len(fmt.human_duration(0, 0, 2, True)))
Format a duration value in seconds to a readable form.
def value(self, units=None): if units is None: return self._value if not units.upper() in CustomPressure.legal_units: raise UnitsError("unrecognized pressure unit: '" + units + "'") units = units.upper() if units == self._units: return self._value ...
Return the pressure in the specified units.
def write_area_data(self, file): file.write("%% area data" + "\n") file.write("%\tno.\tprice_ref_bus" + "\n") file.write("areas = [" + "\n") file.write("\t1\t1;" + "\n") file.write("];" + "\n")
Writes area data to file.
def concatenate_attributes(attributes): tpl = attributes[0] attr = InstanceAttribute(tpl.name, tpl.shape, tpl.dtype, tpl.dim, alias=None) if all(a.size == 0 for a in attributes): return attr else: attr.value = np.concatenate([a.value for a in attributes if ...
Concatenate InstanceAttribute to return a bigger one.
def shell_join(delim, it): 'Joins an iterable of ShellQuoted with a delimiter between each two' return ShellQuoted(delim.join(raw_shell(s) for s in it))
Joins an iterable of ShellQuoted with a delimiter between each two
def override(self, value): if self._value is not value: return _ScopedValueOverrideContext(self, value) else: return empty_context
Temporarily overrides the old value with the new one.
def copy(self): data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
Copy to the clipboard
def encode(self): return '{:.6f} {:.6f} {:.6f} {:.6f} {:.6f} {:.6f}'.format( self.a, self.b, self.c, self.d, self.e, self.f ).encode()
Encode this matrix in binary suitable for including in a PDF
def _autobounds(self): bounds = {} def check(prop, compare, extreme, val): opp = min if compare is max else max bounds.setdefault(prop, val) bounds[prop] = opp(compare(bounds[prop], val), extreme) def bound_check(lat_lon): lat, lon = lat_lon ...
Simple calculation for bounds.
def nvrtcCreateProgram(self, src, name, headers, include_names): res = c_void_p() headers_array = (c_char_p * len(headers))() headers_array[:] = encode_str_list(headers) include_names_array = (c_char_p * len(include_names))() include_names_array[:] = encode_str_list(include_names...
Creates and returns a new NVRTC program object.
def _extract_file(zip_fp, info, path): zip_fp.extract(info.filename, path=path) out_path = os.path.join(path, info.filename) perm = info.external_attr >> 16 perm |= stat.S_IREAD os.chmod(out_path, perm)
Extract files while explicitly setting the proper permissions
def _generate_standard_transitions(cls): allowed_transitions = cls.context.get_config('transitions', {}) for key, transitions in allowed_transitions.items(): key = cls.context.new_meta['translator'].translate(key) new_transitions = set() for trans in transitions: ...
Generate methods used for transitions.
def setOverlayDualAnalogTransform(self, ulOverlay, eWhich, fRadius): fn = self.function_table.setOverlayDualAnalogTransform pvCenter = HmdVector2_t() result = fn(ulOverlay, eWhich, byref(pvCenter), fRadius) return result, pvCenter
Sets the analog input to Dual Analog coordinate scale for the specified overlay.
def _job_statistics(self): statistics = self._properties.get("statistics", {}) return statistics.get(self._JOB_TYPE, {})
Helper for job-type specific statistics-based properties.
def prune_missing(table): try: for item in table.select(): if not os.path.isfile(item.file_path): logger.info("File disappeared: %s", item.file_path) item.delete() except: logger.exception("Error pruning %s", table)
Prune any files which are missing from the specified table
def list_themes_user(): themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes/dark/")), *os.scandir(os.path.join(CONF_DIR, "colorschemes/light/"))] return [t for t in themes if os.path.isfile(t.path)]
List user theme files.
def degrees_of_freedom(self): if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None r = self.studentized_residuals() if r == None: return N = 0.0 for i in range(len(r)): N += len(r[i]) return N-len(self._pnames)
Returns the number of degrees of freedom.
def description(self): result = self.query.result() return [field for field in result.schema]
Get the fields of the result set's schema.
def add_image_info_cb(self, gshell, channel, iminfo): timestamp = iminfo.time_modified if timestamp is None: return self.add_entry(channel.name, iminfo)
Add entries related to an added image.
def spell_check_no_pipeline(self, sources, options, personal_dict): for source in sources: if source._has_error(): yield Results([], source.context, source.category, source.error) cmd = self.setup_command(source.encoding, options, personal_dict, source.context) ...
Spell check without the pipeline.
def add_method(obj, func, name=None): if name is None: name = func.__name__ if sys.version_info < (3,): method = types.MethodType(func, obj, obj.__class__) else: method = types.MethodType(func, obj) setattr(obj, name, method)
Adds an instance method to an object.
def people(self): people_response = self.get_request('people/') return [Person(self, pjson['user']) for pjson in people_response]
Generates a list of all People.
def enter_unlink_mode(self): self.logger.info("enter_unlink_mode Group %s", self.group_id) self.scene_command('0A') status = self.hub.get_buffer_status() return status
Enter unlinking mode for a group
def disable_radio_button(self): checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_in...
Disable radio button group and custom value input area.
def trim(sequences, start, end): logging.info("Trimming from %d to %d", start, end) return (sequence[start:end] for sequence in sequences)
Slice the input sequences from start to end
def utc_book_close_time(self): tz = pytz.timezone(self.timezone) close_time = datetime.datetime.strptime(self.close_time, '%H:%M:%S').time() close_time = tz.localize(datetime.datetime.combine(datetime.datetime.now(tz), close_time)) return close_time.astimezone(pytz.utc).time()
The book close time in utc.
def _get_geocoding(self, key, location): url = self._location_query_base % quote_plus(key) if self.api_key: url += "&key=%s" % self.api_key data = self._read_from_url(url) response = json.loads(data) if response["status"] == "OK": formatted_address = respo...
Lookup the Google geocoding API information for `key`
def all(self, query=None, **kwargs): if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).all(query, **kwargs)
Gets all assets of a space.
def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False, minigui_mode=False): n = DualNetwork(load_file) if cgos_mode: player = CGOSPlayer(network=n, seconds_per_move=5, timed_match=True, two_player_mode=True) else: player = MCTSPlay...
Takes a path to model files and set up a GTP engine instance.
def install(path, remove=False, prefix=sys.prefix, recursing=False): if sys.platform == 'win32' and not exists(join(sys.prefix, '.nonadmin')): if isUserAdmin(): _install(path, remove, prefix, mode='system') else: from pywintypes import error try: i...
install Menu and shortcuts
def _parse_comma_list(self): if self._cur_token['type'] not in self._literals: raise Exception( "Parser failed, _parse_comma_list was called on non-literal" " {} on line {}.".format( repr(self._cur_token['value']), self._cur_token['line'] ...
Parse a comma seperated list.
def add_class2fields(self, html_class, fields=[], exclude=[], include_all_if_empty=True): self.add_attr2fields('class', html_class, fields, exclude)
add class to html widgets.
def show_filetypes(extensions): for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in item[1]) print("{0:4}: {1}".format(val, item[0]))
function to show valid file extensions
def in_cmd(argv): if len(argv) == 1: return workon_cmd(argv) parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target')) return inve(*argv)
Run a command in the given virtualenv.
def getOntology(self, id_): if id_ not in self._ontologyIdMap: raise exceptions.OntologyNotFoundException(id_) return self._ontologyIdMap[id_]
Returns the ontology with the specified ID.
def _make_matchers(self, crontab): crontab = _aliases.get(crontab, crontab) ct = crontab.split() if len(ct) == 5: ct.insert(0, '0') ct.append('*') elif len(ct) == 6: ct.insert(0, '0') _assert(len(ct) == 7, "improper number of cron e...
This constructs the full matcher struct.
def _clean_kwargs(keep_name=False, **kwargs): if 'name' in kwargs and not keep_name: kwargs['name_or_id'] = kwargs.pop('name') return __utils__['args.clean_kwargs'](**kwargs)
Sanatize the the arguments for use with shade
async def model_uuids(self): controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: response = await controller_facade.AllModels() return {um.model.name: um.model.uuid ...
Return a mapping of model names to UUIDs.
def runs_to_xml(self, runSet, runs, blockname=None): runsElem = util.copy_of_xml_element(self.xml_header) runsElem.set("options", " ".join(runSet.options)) if blockname is not None: runsElem.set("block", blockname) runsElem.set("name", ((runSet.real_name + ".") if runSet....
This function creates the XML structure for a list of runs
def soap_attribute(self, name, value): setattr(self, name, value) self._attributes.add(name)
Marks an attribute as being a part of the data defined by the soap datatype
def _validate_changeset(self, changeset_id: uuid.UUID) -> None: if not self.journal.has_changeset(changeset_id): raise ValidationError("Changeset not found in journal: {0}".format( str(changeset_id) ))
Checks to be sure the changeset is known by the journal
def process_request_thread(self, mainthread): life_time = time.time() nb_requests = 0 while not mainthread.killed(): if self.max_life_time > 0: if (time.time() - life_time) >= self.max_life_time: mainthread.add_worker(1) retur...
obtain request from queue instead of directly from server socket
def _make_sections(self, **section_hdr_params): sect_story = [] if not self.section_headings and len(self.sections): self.section_headings = self.sections.keys() for section_name in self.section_headings: section_story = self.sections[section_name] line = '-'*...
Flatten the sections into a single story list.
def getDict(self): badList = self.checkSetSaveEntries(doSave=False) if badList: self.processBadEntries(badList, self.taskName, canCancel=False) return self._taskParsObj.dict()
Retrieve the current parameter settings from the GUI.
def _get_events(self, result): events = [] for event_data in result: event = Event.factory(event_data) if event is not None: events.append(event) if isinstance(event, DeviceStateChangedEvent): if self.__devices[event.device_url]...
Internal method for being able to run unit tests.
def login(): if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None user = User.query.filter_by(username=username).first() if user is None: error = "Incorrect username." elif not user.check_passwor...
Log in a registered user by adding the user id to the session.
def _number_type_helper(national_number, metadata): if not _is_number_matching_desc(national_number, metadata.general_desc): return PhoneNumberType.UNKNOWN if _is_number_matching_desc(national_number, metadata.premium_rate): return PhoneNumberType.PREMIUM_RATE if _is_number_matching_desc(nat...
Return the type of the given number against the metadata
def _after_request(self, response): if not getattr(g, '_has_exception', False): extra = self.summary_extra() self.summary_logger.info('', extra=extra) return response
The signal handler for the request_finished signal.
def _write_recordio(f, data): length = len(data) f.write(struct.pack('I', _kmagic)) f.write(struct.pack('I', length)) pad = (((length + 3) >> 2) << 2) - length f.write(data) f.write(padding[pad])
Writes a single data point as a RecordIO record to the given file.
def formatSubclassOf(fmt, cls, ontology, visited): if URIRef(fmt) == URIRef(cls): return True if ontology is None: return False if fmt in visited: return False visited.add(fmt) uriRefFmt = URIRef(fmt) for s, p, o in ontology.triples((uriRefFmt, RDFS.subClassOf, None)): ...
Determine if `fmt` is a subclass of `cls`.
def paragraph(self, content): if not self._out.description: self._out.description = content return ' '
Turn the first paragraph of text into the summary text
def version(self): response = self.get(version="", base="/version") response.raise_for_status() data = response.json() return (data["major"], data["minor"])
Get Kubernetes API version
def _move_here(self): cu = self.scraper.current_item if self is cu: return if cu.items and self in cu.items: self.scraper.move_to(self) return if self is cu.parent: self.scraper.move_up() if self.parent and self in self.parent.items...
Move the cursor to this item.
def clear( self ): item = self.uiActionTREE.currentItem() if ( not item ): return self.uiShortcutTXT.setText('') item.setText(1, '')
Clears the current settings for the current action.
def OnContentChanged(self, event): self.main_window.grid.update_attribute_toolbar() title = self.main_window.GetTitle() if undo.stack().haschanged(): if title[:2] != "* ": new_title = "* " + title post_command_event(self.main_window, self.main_window.T...
Titlebar star adjustment event handler
def _equivalent_node_iterator_helper(self, node: BaseEntity, visited: Set[BaseEntity]) -> BaseEntity: for v in self[node]: if v in visited: continue if self._has_no_equivalent_edge(node, v): continue visited.add(v) yield v ...
Iterate over nodes and their data that are equal to the given node, starting with the original.
async def on_isupport_maxlist(self, value): self._list_limits = {} for entry in value.split(','): modes, limit = entry.split(':') self._list_limits[frozenset(modes)] = int(limit) for mode in modes: self._list_limit_groups[mode] = frozenset(modes)
Limits on channel modes involving lists.
def _update_simulation_start_cards(self): if self.simulation_start is not None: self._update_card("START_DATE", self.simulation_start.strftime("%Y %m %d")) self._update_card("START_TIME", self.simulation_start.strftime("%H %M"))
Update GSSHA cards for simulation start
def reset_state(self): super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
Will reset state of each augmentor
def gen_nop(): empty_reg = ReilEmptyOperand() return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg)
Return a NOP instruction.
def revert(self, strip=0, root=None): reverted = copy.deepcopy(self) reverted._reverse() return reverted.apply(strip, root)
apply patch in reverse order
def _urls_for_js(urls=None): if urls is None: from .urls import urlpatterns urls = [url.name for url in urlpatterns if getattr(url, 'name', None)] urls = dict(zip(urls, [get_uri_template(url) for url in urls])) urls.update(getattr(settings, 'LEAFLET_STORAGE_EXTRA_URLS', {})) return urls
Return templated URLs prepared for javascript.
async def get_json(self, url, timeout=30, astext=False, exceptions=False): try: with async_timeout.timeout(timeout): res = await self._aio_session.get(url) if res.status != 200: _LOGGER.error("QSUSB returned %s [%s]", res.status, url) ...
Get URL and parse JSON from text.
def _get_erred_shared_settings_module(self): result_module = modules.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashboard/erred_link_list.html' erred_state = structure_models.SharedServiceSettings.States.ERRED queryset = structure_models....
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
def __create_profile_from_identities(self, identities, uuid, verbose): import re EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$" NAME_REGEX = r"^\w+\s\w+" name = None email = None username = None for identity in identities: if not name ...
Create a profile using the data from the identities
def simple_prot(x, start): for i in range(start,len(x)-1): a,b,c = x[i-1], x[i], x[i+1] if b - a > 0 and b -c >= 0: return i else: return None
Find the first peak to the right of start