positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_instance(self, payload): """ Build an instance of AssignedAddOnExtensionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance """ return AssignedAddOnExtensionInstance( self._version, payload, account_sid=self._solution['account_sid'], resource_sid=self._solution['resource_sid'], assigned_add_on_sid=self._solution['assigned_add_on_sid'], )
Build an instance of AssignedAddOnExtensionInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance
def requested_packages(self, include_implicit=False): """Get packages in the request. Args: include_implicit (bool): If True, implicit packages are appended to the result. Returns: List of `PackageRequest` objects. """ if include_implicit: return self._package_requests + self.implicit_packages else: return self._package_requests
Get packages in the request. Args: include_implicit (bool): If True, implicit packages are appended to the result. Returns: List of `PackageRequest` objects.
async def auth(self): """Perform AirPlay device authentication.""" credentials = await self.atv.airplay.generate_credentials() await self.atv.airplay.load_credentials(credentials) try: await self.atv.airplay.start_authentication() pin = await _read_input(self.loop, 'Enter PIN on screen: ') await self.atv.airplay.finish_authentication(pin) print('You may now use these credentials:') print(credentials) return 0 except exceptions.DeviceAuthenticationError: logging.exception('Failed to authenticate - invalid PIN?') return 1
Perform AirPlay device authentication.
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=default_ts_skew_in_seconds, **auth_kw): """ Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk """ log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=content_type, # The following response attributes are # in reference to the original request, # not to the reponse header: timestamp=self.req_resource.timestamp, nonce=self.req_resource.nonce, url=self.req_resource.url, method=self.req_resource.method, app=self.req_resource.app, dlg=self.req_resource.dlg, credentials=self.credentials, seen_nonce=self.seen_nonce) self._authorize( 'response', parsed_header, resource, # Per Node lib, a responder macs the *sender's* timestamp. # It does not create its own timestamp. # I suppose a slow response could time out here. Maybe only check # mac failures, not timeouts? their_timestamp=resource.timestamp, timestamp_skew_in_seconds=timestamp_skew_in_seconds, localtime_offset_in_seconds=localtime_offset_in_seconds, accept_untrusted_content=accept_untrusted_content, **auth_kw)
Accept a response to this request. :param response_header: A `Hawk`_ ``Server-Authorization`` header such as one created by :class:`mohawk.Receiver`. :type response_header: str :param content=EmptyValue: Byte string of the response body received. :type content=EmptyValue: str :param content_type=EmptyValue: Content-Type header value of the response received. :type content_type=EmptyValue: str :param accept_untrusted_content=False: When True, allow responses that do not hash their content. Read :ref:`skipping-content-checks` to learn more. :type accept_untrusted_content=False: bool :param localtime_offset_in_seconds=0: Seconds to add to local time in case it's out of sync. :type localtime_offset_in_seconds=0: float :param timestamp_skew_in_seconds=60: Max seconds until a message expires. Upon expiry, :class:`mohawk.exc.TokenExpired` is raised. :type timestamp_skew_in_seconds=60: float .. _`Hawk`: https://github.com/hueniverse/hawk
def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity): """Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default.""" from canari.commands.generate_entities import generate_entities generate_entities( ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)
Converts Maltego entity definition files to Canari python classes. Excludes Maltego built-in entities by default.
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None): """ use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file to sep : str CSV separator bins : bool add a "bin" column for efficient spatial queries. indexes : list[str] list of columns to index """ convs = {"#chr": "chrom", "start": "txStart", "end": "txEnd", "chr": "chrom", "pos": "start", "POS": "start", "chromStart": "txStart", "chromEnd": "txEnd"} if table is None: import os.path as op table = op.basename(op.splitext(fname)[0]).replace(".", "_") print("writing to:", table, file=sys.stderr) from pandas.io import sql import pandas as pa from toolshed import nopen needs_name = False for i, chunk in enumerate(pa.read_csv(nopen(fname), iterator=True, chunksize=100000, sep=sep, encoding="latin-1")): chunk.columns = [convs.get(k, k) for k in chunk.columns] if not "name" in chunk.columns: needs_name = True chunk['name'] = chunk.get('chrom', chunk[chunk.columns[0]]) if bins: chunk['bin'] = 1 if i == 0 and not table in self.tables: flavor = self.url.split(":")[0] schema = sql.get_schema(chunk, table, flavor) print(schema) self.engine.execute(schema) elif i == 0: print >>sys.stderr,\ """adding to existing table, you may want to drop first""" tbl = getattr(self, table)._table cols = chunk.columns data = list(dict(zip(cols, x)) for x in chunk.values) if needs_name: for d in data: d['name'] = "%s:%s" % (d.get("chrom"), d.get("txStart", d.get("chromStart"))) if bins: for d in data: d['bin'] = max(Genome.bins(int(d["txStart"]), int(d["txEnd"]))) self.engine.execute(tbl.insert(), data) self.session.commit() if i > 0: print >>sys.stderr, "writing row:", i * 100000 if "txStart" in chunk.columns: if "chrom" in chunk.columns: ssql = """CREATE INDEX "%s.chrom_txStart" ON "%s" (chrom, txStart)""" % (table, table) else: ssql = """CREATE INDEX "%s.txStart" ON "%s" (txStart)""" % (table, table) self.engine.execute(ssql) for index in (indexes or []): ssql = """CREATE INDEX "%s.%s" ON "%s" (%s)""" % (table, index, table, index) self.engine.execute(ssql) if bins: ssql = """CREATE INDEX "%s.chrom_bin" ON "%s" (chrom, bin)""" % (table, table) self.engine.execute(ssql) self.session.commit()
use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file to sep : str CSV separator bins : bool add a "bin" column for efficient spatial queries. indexes : list[str] list of columns to index
def find_course_by_crn(self, crn): """Searches all courses by CRNs. Not particularly efficient. Returns None if not found. """ for name, course in self.courses.iteritems(): if crn in course: return course return None
Searches all courses by CRNs. Not particularly efficient. Returns None if not found.
def __make_client(self): "Make this node a client" notice('Making client, getting server connection', self.color) self.mode = 'c' addr = utils.get_existing_server_addr() sock = utils.get_client_sock(addr) self.__s = sock with self.__client_list_lock: self.clients = deque() self.threads = deque()
Make this node a client
def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the password prompt. global global_status st = global_status global_status = None email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) # Put status back. global_status = st return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies)
Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made.
def parse_doc(doc): """ Parse docstrings to dict, it should look like: key: value """ if not doc: return {} out = {} for s in doc.split('\n'): s = s.strip().split(':', maxsplit=1) if len(s) == 2: out[s[0]] = s[1] return out
Parse docstrings to dict, it should look like: key: value
def karbasa(self, result): """ Finding if class probabilities are close to eachother Ratio of the distance between 1st and 2nd class, to the distance between 1st and last class. :param result: The dict returned by LM.calculate() """ probs = result['all_probs'] probs.sort() return float(probs[1] - probs[0]) / float(probs[-1] - probs[0])
Finding if class probabilities are close to eachother Ratio of the distance between 1st and 2nd class, to the distance between 1st and last class. :param result: The dict returned by LM.calculate()
def createEditor(self, delegate, parent, option): """ Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ChoiceCtiEditor(self, delegate, parent=parent)
Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation.
def symlink_to_bytes(symlink_target): # type: (str) -> bytes ''' A function to generate UDF symlink data from a Unix-like path. Parameters: symlink_target - The Unix-like path that is the symlink. Returns: The UDF data corresponding to the symlink. ''' symlink_data = bytearray() for comp in symlink_target.split('/'): if comp == '': # If comp is empty, then we know this is the leading slash # and we should make an absolute entry (double slashes and # such are weeded out by the earlier utils.normpath). symlink_data.extend(b'\x02\x00\x00\x00') elif comp == '.': symlink_data.extend(b'\x04\x00\x00\x00') elif comp == '..': symlink_data.extend(b'\x03\x00\x00\x00') else: symlink_data.extend(b'\x05') ostaname = _ostaunicode(comp) symlink_data.append(len(ostaname)) symlink_data.extend(b'\x00\x00') symlink_data.extend(ostaname) return symlink_data
A function to generate UDF symlink data from a Unix-like path. Parameters: symlink_target - The Unix-like path that is the symlink. Returns: The UDF data corresponding to the symlink.
def set_bandwidth(self, bandwidth): """ Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s) """ yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth)) self._bandwidth = bandwidth
Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s)
def visitParam_def(self, ctx:SystemRDLParser.Param_defContext): """ Parameter Definition block """ self.compiler.namespace.enter_scope() param_defs = [] for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext): param_def = self.visit(elem) param_defs.append(param_def) self.compiler.namespace.exit_scope() return param_defs
Parameter Definition block
def _draw_calendar(self, canvas, redraw=False): """Draws calendar.""" options = self.__options # Update labels: name = self._cal.formatmonthname(self._date.year, self._date.month, 0, withyear=False) self._lmonth.configure(text=name.title()) self._lyear.configure(text=str(self._date.year)) # Update calendar ch = canvas.winfo_height() cw = canvas.winfo_width() rowh = ch / 7.0 colw = cw / 7.0 # Header background if self._rheader is None: self._rheader = canvas.create_rectangle(0, 0, cw, rowh, width=0, fill=options['headerbg']) else: canvas.itemconfigure(self._rheader, fill=options['headerbg']) canvas.coords(self._rheader, 0, 0, cw, rowh) # Header text ox = 0 oy = rowh / 2.0 coffset = colw / 2.0 cols = self._cal.formatweekheader(3).split() for i in range(0, 7): x = ox + i * colw + coffset if redraw: item = self._theader[i] canvas.coords(item, x, oy) canvas.itemconfigure(item, text=cols[i], fill=options['headerfg']) else: self._theader[i] = canvas.create_text(x, oy, text=cols[i], fill=options['headerbg']) # background matrix oy = rowh ox = 0 for i, x, y, x1, y1 in matrix_coords(6, 7, rowh, colw, ox, oy): x1 -= 1 y1 -= 1 if redraw: rec = self._recmat[i] canvas.coords(rec, x, y, x1, y1) canvas.itemconfigure(rec, fill=options['calendarbg']) else: rec = canvas.create_rectangle(x, y, x1, y1, width=1, fill=options['calendarbg'], outline=options['calendarbg'], activeoutline=options['selectbg'], activewidth=1, tags='cell') self._recmat[i] = rec # text matrix weeks = self._weeks xoffset = colw / 2.0 yoffset = rowh / 2.0 oy = rowh ox = 0 for i, x, y, x1, y1 in matrix_coords(6, 7, rowh, colw, ox, oy): x += coffset y += yoffset # day text txt = "" f, c = i2rc(i, 7) if f < len(weeks): day = weeks[f][c] txt = "{0}".format(day) if day != 0 else "" if redraw: item = self._txtmat[i] canvas.coords(item, x, y) canvas.itemconfigure(item, text=txt) else: self._txtmat[i] = canvas.create_text(x, y, text=txt, state=tk.DISABLED) # Mark days self._mark_days()
Draws calendar.
def _Build(self, storage_file): """Builds the event tag index. Args: storage_file (BaseStorageFile): storage file. """ self._index = {} for event_tag in storage_file.GetEventTags(): self.SetEventTag(event_tag)
Builds the event tag index. Args: storage_file (BaseStorageFile): storage file.
def left_axis_label(self, label, position=None, rotation=60, offset=0.08, **kwargs): """ Sets the label on the left axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 60 The angle of rotation of the label offset: float, Used to compute the distance of the label from the axis kwargs: Any kwargs to pass through to matplotlib. """ if not position: position = (-offset, 3./5, 2./5) self._labels["left"] = (label, position, rotation, kwargs)
Sets the label on the left axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 60 The angle of rotation of the label offset: float, Used to compute the distance of the label from the axis kwargs: Any kwargs to pass through to matplotlib.
def _find_spherical_axes(self): """ Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point group T molecules have only one unique 3-fold and one unique 2-fold axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules have a unique 5-fold axis. """ rot_present = defaultdict(bool) origin_site, dist_el_sites = cluster_sites(self.centered_mol, self.tol) test_set = min(dist_el_sites.values(), key=lambda s: len(s)) coords = [s.coords for s in test_set] for c1, c2, c3 in itertools.combinations(coords, 3): for cc1, cc2 in itertools.combinations([c1, c2, c3], 2): if not rot_present[2]: test_axis = cc1 + cc2 if np.linalg.norm(test_axis) > self.tol: op = SymmOp.from_axis_angle_and_translation(test_axis, 180) rot_present[2] = self.is_valid_op(op) if rot_present[2]: self.symmops.append(op) self.rot_sym.append((test_axis, 2)) test_axis = np.cross(c2 - c1, c3 - c1) if np.linalg.norm(test_axis) > self.tol: for r in (3, 4, 5): if not rot_present[r]: op = SymmOp.from_axis_angle_and_translation( test_axis, 360 / r) rot_present[r] = self.is_valid_op(op) if rot_present[r]: self.symmops.append(op) self.rot_sym.append((test_axis, r)) break if rot_present[2] and rot_present[3] and ( rot_present[4] or rot_present[5]): break
Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point group T molecules have only one unique 3-fold and one unique 2-fold axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules have a unique 5-fold axis.
def print_header(text): """Prints header with given text and frame composed of '#' characters.""" print() print('#'*(len(text)+4)) print('# ' + text + ' #') print('#'*(len(text)+4)) print()
Prints header with given text and frame composed of '#' characters.
def _dispatch_change_event(self, object, trait_name, old, new, handler): """ Prepare and dispatch a trait change event to a listener. """ # Extract the arguments needed from the handler. args = self.argument_transform(object, trait_name, old, new) # Send a description of the event to the change event tracer. if tnotifier._pre_change_event_tracer is not None: tnotifier._pre_change_event_tracer(object, trait_name, old, new, handler) # Dispatch the event to the listener. from automate.common import SystemNotReady try: self.dispatch(handler, *args) except SystemNotReady: pass except Exception as e: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=e) # This call needs to be made inside the `except` block in case # the handler wants to re-raise the exception. tnotifier.handle_exception(object, trait_name, old, new) else: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=None)
Prepare and dispatch a trait change event to a listener.
def _matches(self, url, options, general_re, domain_required_rules, rules_with_options): """ Return if ``url``/``options`` are matched by rules defined by ``general_re``, ``domain_required_rules`` and ``rules_with_options``. ``general_re`` is a compiled regex for rules without options. ``domain_required_rules`` is a {domain: [rules_which_require_it]} mapping. ``rules_with_options`` is a list of AdblockRule instances that don't require any domain, but have other options. """ if general_re and general_re.search(url): return True rules = [] if 'domain' in options and domain_required_rules: src_domain = options['domain'] for domain in _domain_variants(src_domain): if domain in domain_required_rules: rules.extend(domain_required_rules[domain]) rules.extend(rules_with_options) if self.skip_unsupported_rules: rules = [rule for rule in rules if rule.matching_supported(options)] return any(rule.match_url(url, options) for rule in rules)
Return if ``url``/``options`` are matched by rules defined by ``general_re``, ``domain_required_rules`` and ``rules_with_options``. ``general_re`` is a compiled regex for rules without options. ``domain_required_rules`` is a {domain: [rules_which_require_it]} mapping. ``rules_with_options`` is a list of AdblockRule instances that don't require any domain, but have other options.
def only_path(self): """Finds the only path from the start node. If there is more than one, raises ValueError.""" start = [v for v in self.nodes if self.nodes[v].get('start', False)] if len(start) != 1: raise ValueError("graph does not have exactly one start node") path = [] [v] = start while True: path.append(v) u = v vs = self.edges.get(u, ()) if len(vs) == 0: break elif len(vs) > 1: raise ValueError("graph does not have exactly one path") [v] = vs return path
Finds the only path from the start node. If there is more than one, raises ValueError.
def has_conversion(self, plugin): """Return True if the plugin supports this block.""" plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins
Return True if the plugin supports this block.
def show_keyword_version_message(sender, keyword_version, inasafe_version): """Show a message indicating that the keywords version is mismatch .. versionadded: 3.2 :param sender: Sender of the message signal. Default to Any object. :type sender: object :param keyword_version: The version of the layer's keywords :type keyword_version: str :param inasafe_version: The version of the InaSAFE :type inasafe_version: str .. note:: The print button will be disabled if this method is called. """ LOGGER.debug('Showing Mismatch Version Message') message = generate_input_error_message( tr('Layer Keyword\'s Version Mismatch:'), m.Paragraph( tr( 'Your layer\'s keyword\'s version ({layer_version}) does not ' 'match with your InaSAFE version ({inasafe_version}). If you ' 'wish to use it as an exposure, hazard, or aggregation layer ' 'in an analysis, please use the keyword wizard to update the ' 'keywords. You can open the wizard by clicking on ' 'the ').format( layer_version=keyword_version, inasafe_version=inasafe_version), m.Image( 'file:///%s/img/icons/' 'show-keyword-wizard.svg' % resources_path(), **SMALL_ICON_STYLE), tr( ' icon in the toolbar.')) ) send_static_message(sender, message)
Show a message indicating that the keywords version is mismatch .. versionadded: 3.2 :param sender: Sender of the message signal. Default to Any object. :type sender: object :param keyword_version: The version of the layer's keywords :type keyword_version: str :param inasafe_version: The version of the InaSAFE :type inasafe_version: str .. note:: The print button will be disabled if this method is called.
def addFilteringOptions(parser, samfileIsPositionalArg=False): """ Add options to an argument parser for filtering SAM/BAM. @param samfileIsPositionalArg: If C{True} the SAM/BAM file must be given as the final argument on the command line (without being preceded by --samfile). @param parser: An C{argparse.ArgumentParser} instance. """ parser.add_argument( '%ssamfile' % ('' if samfileIsPositionalArg else '--'), required=True, help='The SAM/BAM file to filter.') parser.add_argument( '--referenceId', metavar='ID', nargs='+', action='append', help=('A reference sequence id whose alignments should be kept ' '(alignments against other references will be dropped). ' 'If omitted, alignments against all references will be ' 'kept. May be repeated.')) parser.add_argument( '--dropUnmapped', default=False, action='store_true', help='If given, unmapped matches will not be output.') parser.add_argument( '--dropSecondary', default=False, action='store_true', help='If given, secondary matches will not be output.') parser.add_argument( '--dropSupplementary', default=False, action='store_true', help='If given, supplementary matches will not be output.') parser.add_argument( '--dropDuplicates', default=False, action='store_true', help=('If given, matches flagged as optical or PCR duplicates ' 'will not be output.')) parser.add_argument( '--keepQCFailures', default=False, action='store_true', help=('If given, reads that are considered quality control ' 'failures will be included in the output.')) parser.add_argument( '--minScore', type=float, help=('If given, alignments with --scoreTag (default AS) values ' 'less than this value will not be output. If given, ' 'alignments that do not have a score will not be output.')) parser.add_argument( '--maxScore', type=float, help=('If given, alignments with --scoreTag (default AS) values ' 'greater than this value will not be output. If given, ' 'alignments that do not have a score will not be output.')) parser.add_argument( '--scoreTag', default='AS', help=('The alignment tag to extract for --minScore and --maxScore ' 'comparisons.'))
Add options to an argument parser for filtering SAM/BAM. @param samfileIsPositionalArg: If C{True} the SAM/BAM file must be given as the final argument on the command line (without being preceded by --samfile). @param parser: An C{argparse.ArgumentParser} instance.
async def _into_id_set(client, chats): """Helper util to turn the input chat or chats into a set of IDs.""" if chats is None: return None if not utils.is_list_like(chats): chats = (chats,) result = set() for chat in chats: if isinstance(chat, int): if chat < 0: result.add(chat) # Explicitly marked IDs are negative else: result.update({ # Support all valid types of peers utils.get_peer_id(types.PeerUser(chat)), utils.get_peer_id(types.PeerChat(chat)), utils.get_peer_id(types.PeerChannel(chat)), }) elif isinstance(chat, TLObject) and chat.SUBCLASS_OF_ID == 0x2d45687: # 0x2d45687 == crc32(b'Peer') result.add(utils.get_peer_id(chat)) else: chat = await client.get_input_entity(chat) if isinstance(chat, types.InputPeerSelf): chat = await client.get_me(input_peer=True) result.add(utils.get_peer_id(chat)) return result
Helper util to turn the input chat or chats into a set of IDs.
def render_field(parser, token): """ Render a form field using given attribute-value pairs Takes form field as first argument and list of attribute-value pairs for all other arguments. Attribute-value pairs should be in the form of attribute=value or attribute="a value" for assignment and attribute+=value or attribute+="value" for appending. """ error_msg = '%r tag requires a form field followed by a list of attributes and values in the form attr="value"' % token.split_contents()[0] try: bits = token.split_contents() tag_name = bits[0] form_field = bits[1] attr_list = bits[2:] except ValueError: raise TemplateSyntaxError(error_msg) form_field = parser.compile_filter(form_field) set_attrs = [] append_attrs = [] for pair in attr_list: match = ATTRIBUTE_RE.match(pair) if not match: raise TemplateSyntaxError(error_msg + ": %s" % pair) dct = match.groupdict() attr, sign, value = \ dct['attr'], dct['sign'], parser.compile_filter(dct['value']) if sign == "=": set_attrs.append((attr, value)) else: append_attrs.append((attr, value)) return FieldAttributeNode(form_field, set_attrs, append_attrs)
Render a form field using given attribute-value pairs Takes form field as first argument and list of attribute-value pairs for all other arguments. Attribute-value pairs should be in the form of attribute=value or attribute="a value" for assignment and attribute+=value or attribute+="value" for appending.
def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) return wrapper
Adds a request to be sent to the remoting gateway.
def cli(): """\ Frogsay generates an ASCII picture of a FROG spouting a FROG tip. FROG tips are fetched from frog.tips's API endpoint when needed, otherwise they are cached locally in an application-specific folder. """ with open_client(cache_dir=get_cache_dir()) as client: tip = client.frog_tip() terminal_width = click.termui.get_terminal_size()[0] wisdom = make_frog_fresco(tip, width=terminal_width) click.echo(wisdom)
\ Frogsay generates an ASCII picture of a FROG spouting a FROG tip. FROG tips are fetched from frog.tips's API endpoint when needed, otherwise they are cached locally in an application-specific folder.
def _create_subepochs(x, nperseg, step): """Transform the data into a matrix for easy manipulation Parameters ---------- x : 1d ndarray actual data values nperseg : int number of samples in each row to create step : int distance in samples between rows Returns ------- 2d ndarray a view (i.e. doesn't copy data) of the original x, with shape determined by nperseg and step. You should use the last dimension """ axis = x.ndim - 1 # last dim nsmp = x.shape[axis] stride = x.strides[axis] noverlap = nperseg - step v_shape = *x.shape[:axis], (nsmp - noverlap) // step, nperseg v_strides = *x.strides[:axis], stride * step, stride v = as_strided(x, shape=v_shape, strides=v_strides, writeable=False) # much safer return v
Transform the data into a matrix for easy manipulation Parameters ---------- x : 1d ndarray actual data values nperseg : int number of samples in each row to create step : int distance in samples between rows Returns ------- 2d ndarray a view (i.e. doesn't copy data) of the original x, with shape determined by nperseg and step. You should use the last dimension
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials): """ Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features. """ ######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f, c, t] = how long it took it to converge with f unique # features, c columns and topology t. convergence = numpy.zeros((max(featureRange), max(columnRange) + 1, len(networkType))) networkTypeNames = {} for i, topologyType in enumerate(networkType): if "Topology" in topologyType: networkTypeNames[i] = "Normal" else: networkTypeNames[i] = "Dense" for r in results: convergence[r["numFeatures"] - 1, r["numColumns"], networkType.index(r["networkType"])] += r["convergencePoint"] convergence /= numTrials # For each column, print convergence as fct of number of unique features for c in range(1, max(columnRange) + 1): for t in range(len(networkType)): print c, convergence[:, c, t] # Print everything anyway for debugging print "Average convergence array=", convergence ######################################################################## # # Create the plot. x-axis= plt.figure() plotPath = os.path.join("plots", "convergence_by_column_topology.pdf") # Plot each curve legendList = [] colormap = plt.get_cmap("jet") colorList = [colormap(x) for x in numpy.linspace(0., 1., len(featureRange)*len(networkType))] for i in range(len(featureRange)): for t in range(len(networkType)): f = featureRange[i] print columnRange print convergence[f-1,columnRange, t] legendList.append('Unique features={}, topology={}'.format(f, networkTypeNames[t])) plt.plot(columnRange, convergence[f-1,columnRange, t], color=colorList[i*len(networkType) + t]) # format plt.legend(legendList, loc="upper right") plt.xlabel("Number of columns") plt.xticks(columnRange) plt.yticks(range(0,int(convergence.max())+1)) plt.ylabel("Average number of touches") plt.title("Number of touches to recognize one object (multiple columns)") # save plt.savefig(plotPath) plt.close()
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
def xml_path_completion(xml_path): """ Takes in a local xml path and returns a full path. if @xml_path is absolute, do nothing if @xml_path is not absolute, load xml that is shipped by the package """ if xml_path.startswith("/"): full_path = xml_path else: full_path = os.path.join(robosuite.models.assets_root, xml_path) return full_path
Takes in a local xml path and returns a full path. if @xml_path is absolute, do nothing if @xml_path is not absolute, load xml that is shipped by the package
def run(self): ''' Running the workbench CLI ''' # Announce versions self.versions() # Sample/Tag info and Help self.tags() print '\n%s' % self.workbench.help('cli') # Now that we have the Workbench connection spun up, we register some stuff # with the embedded IPython interpreter and than spin it up # cfg = IPython.config.loader.Config() cfg = Config() cfg.InteractiveShellEmbed.autocall = 2 cfg.InteractiveShellEmbed.colors = 'Linux' cfg.InteractiveShellEmbed.color_info = True cfg.InteractiveShellEmbed.autoindent = True cfg.InteractiveShellEmbed.deep_reload = True cfg.PromptManager.in_template = ( r'{color.LightPurple}{short_md5}{color.Yellow}{prompt_deco}{color.LightBlue} Workbench{color.Green}[\#]> ') # cfg.PromptManager.out_template = '' # Create the IPython shell self.ipshell = IPython.terminal.embed.InteractiveShellEmbed( config=cfg, banner1='', exit_msg='\nWorkbench has SuperCowPowers...') # Register our transformer, the shell will use this for 'shortcut' commands auto_quoter = auto_quote_xform.AutoQuoteTransformer(self.ipshell, self.ipshell.prefilter_manager) auto_quoter.register_command_set(self.command_set) # Setting up some Pandas options pd.set_option('display.width', 140) pd.set_option('max_colwidth', 15) # Start up the shell with our set of workbench commands self.ipshell(local_ns=self.command_dict)
Running the workbench CLI
def _meta_schema_factory(self, columns, model, class_mixin): """ Creates ModelSchema marshmallow-sqlalchemy :param columns: a list of columns to mix :param model: Model :param class_mixin: a marshamallow Schema to mix :return: ModelSchema """ _model = model if columns: class MetaSchema(ModelSchema, class_mixin): class Meta: model = _model fields = columns strict = True sqla_session = self.datamodel.session else: class MetaSchema(ModelSchema, class_mixin): class Meta: model = _model strict = True sqla_session = self.datamodel.session return MetaSchema
Creates ModelSchema marshmallow-sqlalchemy :param columns: a list of columns to mix :param model: Model :param class_mixin: a marshamallow Schema to mix :return: ModelSchema
def _get_prog_memory(resources, cores_per_job): """Get expected memory usage, in Gb per core, for a program from resource specification. """ out = None for jvm_opt in resources.get("jvm_opts", []): if jvm_opt.startswith("-Xmx"): out = _str_memory_to_gb(jvm_opt[4:]) memory = resources.get("memory") if memory: out = _str_memory_to_gb(memory) prog_cores = resources.get("cores") # if a single core with memory is requested for the job # and we run multiple cores, scale down to avoid overscheduling if out and prog_cores and int(prog_cores) == 1 and cores_per_job > int(prog_cores): out = out / float(cores_per_job) return out
Get expected memory usage, in Gb per core, for a program from resource specification.
def main(): ''' Main function ''' # We should only steal the root logger if we're the application, not the module logging.basicConfig(level=logging.DEBUG) args = get_args() if args.password: password = args.password else: password = getpass( prompt='Enter password for {}@{}: '.format(args.user, args.host) ) opsview = Opsview( host=args.host, port=args.port, use_ssl=args.ssl, verify_ssl=not args.skip_ssl_verification, username=args.user, password=password, verbose=args.verbose, ) d = {} with open('vcenter.json') as f: d = json.load(f) logger.debug( pformat(opsview.create_host(params=d, verbose=args.verbose)) )
Main function
def predict_step(F, covX, filt): """Predictive step of Kalman filter. Parameters ---------- F: (dx, dx) numpy array Mean of X_t | X_{t-1} is F * X_{t-1} covX: (dx, dx) numpy array covariance of X_t | X_{t-1} filt: MeanAndCov object filtering distribution at time t-1 Returns ------- pred: MeanAndCov object predictive distribution at time t Note ---- filt.mean may either be of shape (dx,) or (N, dx); in the latter case N predictive steps are performed in parallel. """ pred_mean = np.matmul(filt.mean, F.T) pred_cov = dotdot(F, filt.cov, F.T) + covX return MeanAndCov(mean=pred_mean, cov=pred_cov)
Predictive step of Kalman filter. Parameters ---------- F: (dx, dx) numpy array Mean of X_t | X_{t-1} is F * X_{t-1} covX: (dx, dx) numpy array covariance of X_t | X_{t-1} filt: MeanAndCov object filtering distribution at time t-1 Returns ------- pred: MeanAndCov object predictive distribution at time t Note ---- filt.mean may either be of shape (dx,) or (N, dx); in the latter case N predictive steps are performed in parallel.
def phase_search_names(self, source, phase): """Search the bundle.yaml metadata file for pipeline configurations. Looks for: - <phase>-<source_table> - <phase>-<dest_table> - <phase>-<source_name> """ search = [] assert phase is not None # Create a search list of names for getting a pipline from the metadata if source and source.source_table_name: search.append(phase + '-' + source.source_table_name) if source and source.dest_table_name: search.append(phase + '-' + source.dest_table_name) if source: search.append(phase + '-' + source.name) search.append(phase) return search
Search the bundle.yaml metadata file for pipeline configurations. Looks for: - <phase>-<source_table> - <phase>-<dest_table> - <phase>-<source_name>
def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" self.collect_children() pid = os.fork() # @UndefinedVariable if pid: # Parent process if self.active_children is None: self.active_children = [] self.active_children.append(pid) self.close_request(request) #close handle in parent process return else: # Child process. # This must never return, hence os._exit()! try: self.finish_request(request, client_address) self.shutdown_request(request) os._exit(0) except: try: self.handle_error(request, client_address) self.shutdown_request(request) finally: os._exit(1)
Fork a new subprocess to process the request.
def isChar(ev): """ Check if an event may be a typed character """ text = ev.text() if len(text) != 1: return False if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier): return False asciiCode = ord(text) if asciiCode <= 31 or asciiCode == 0x7f: # control characters return False if text == ' ' and ev.modifiers() == Qt.ShiftModifier: return False # Shift+Space is a shortcut, not a text return True
Check if an event may be a typed character
def calc_geo_centre_point(node_source, node_target): """ Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in config_calc.cfg. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0 source node, member of GridDing0._graph node_target: LVStationDing0, GeneratorDing0, or CableDistributorDing0 target node, member of GridDing0._graph Returns ------- :any:`float` Distance in m. """ proj_source = partial( pyproj.transform, pyproj.Proj(init='epsg:4326'), # source coordinate system pyproj.Proj(init='epsg:3035')) # destination coordinate system # ETRS (equidistant) to WGS84 (conformal) projection proj_target = partial( pyproj.transform, pyproj.Proj(init='epsg:3035'), # source coordinate system pyproj.Proj(init='epsg:4326')) # destination coordinate system branch_shp = transform(proj_source, LineString([node_source.geo_data, node_target.geo_data])) distance = vincenty((node_source.geo_data.y, node_source.geo_data.x), (node_target.geo_data.y, node_target.geo_data.x)).m centre_point_shp = transform(proj_target, branch_shp.interpolate(distance/2)) return centre_point_shp
Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in config_calc.cfg. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0 source node, member of GridDing0._graph node_target: LVStationDing0, GeneratorDing0, or CableDistributorDing0 target node, member of GridDing0._graph Returns ------- :any:`float` Distance in m.
def append_code_expr(self, code): """Compile argument and adds it to the list of code objects.""" # expects a string. if isinstance(code, str) and not isinstance(code, unicode): code = unicode(code) if not isinstance(code, unicode): raise TypeError("string expected") log.debug("compiling code %s...", code) try: code_obj = compile(code, '<string>', 'eval') self.code_objs[code] = code_obj except SyntaxError as syntax_err: log.error("cannot compile %s: %s", code, syntax_err) raise log.debug("compiled code %s", code)
Compile argument and adds it to the list of code objects.
def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype """ if ary is not None: shape, dtype = ary.shape, ary.dtype elif shape is None or dtype is None: raise ValueError(( 'random_like(ary, shape, dtype) must be supplied ' 'with either an array argument, or the shape and dtype ' 'of the desired random array.')) if np.issubdtype(dtype, np.complexfloating): return (np.random.random(size=shape) + \ np.random.random(size=shape)*1j).astype(dtype) else: return np.random.random(size=shape).astype(dtype)
Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype
def _prepare_transition(self, is_on=None, brightness=None, color=None): """ Perform pre-transition tasks and construct the destination state. :param is_on: The on-off state to transition to. :param brightness: The brightness to transition to (0.0-1.0). :param color: The color to transition to. :return: The destination state of the transition. """ dest_state = super()._prepare_transition(is_on, brightness=brightness, color=color) # Handle transitions from off to on and changing color if is_on and not self.is_on and color is not None: self.set(color=color, cancel_transition=False) return dest_state
Perform pre-transition tasks and construct the destination state. :param is_on: The on-off state to transition to. :param brightness: The brightness to transition to (0.0-1.0). :param color: The color to transition to. :return: The destination state of the transition.
def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL): """ Wrap self._call_geocoder, handling tokens. """ if self.token is None or int(time()) > self.token_expiry: self._refresh_authentication_token() request = Request( "&".join((url, urlencode({"token": self.token}))), headers={"Referer": self.referer} ) return self._base_call_geocoder(request, timeout=timeout)
Wrap self._call_geocoder, handling tokens.
def _get_data_files(data_specs, existing, top=HERE): """Expand data file specs into valid data files metadata. Parameters ---------- data_specs: list of tuples See [create_cmdclass] for description. existing: list of tuples The existing distrubution data_files metadata. Returns ------- A valid list of data_files items. """ # Extract the existing data files into a staging object. file_data = defaultdict(list) for (path, files) in existing or []: file_data[path] = files # Extract the files and assign them to the proper data # files path. for (path, dname, pattern) in data_specs or []: if os.path.isabs(dname): dname = os.path.relpath(dname, top) dname = dname.replace(os.sep, '/') offset = 0 if dname in ('.', '') else len(dname) + 1 files = _get_files(_glob_pjoin(dname, pattern), top=top) for fname in files: # Normalize the path. root = os.path.dirname(fname) full_path = _glob_pjoin(path, root[offset:]) print(dname, root, full_path, offset) if full_path.endswith('/'): full_path = full_path[:-1] file_data[full_path].append(fname) # Construct the data files spec. data_files = [] for (path, files) in file_data.items(): data_files.append((path, files)) return data_files
Expand data file specs into valid data files metadata. Parameters ---------- data_specs: list of tuples See [create_cmdclass] for description. existing: list of tuples The existing distrubution data_files metadata. Returns ------- A valid list of data_files items.
def primary_from_name(self, tax_name): """ Return tax_id and primary tax_name corresponding to tax_name. """ names = self.names s1 = select([names.c.tax_id, names.c.is_primary], names.c.tax_name == tax_name) log.debug(str(s1)) res = s1.execute().fetchone() if res: tax_id, is_primary = res else: msg = '"{}" not found in names.tax_names'.format(tax_name) raise ValueError(msg) if not is_primary: s2 = select([names.c.tax_name], and_(names.c.tax_id == tax_id, names.c.is_primary)) tax_name = s2.execute().fetchone()[0] return tax_id, tax_name, bool(is_primary)
Return tax_id and primary tax_name corresponding to tax_name.
async def get_authenticated_user( self, redirect_uri: str, code: str ) -> Dict[str, Any]: """Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not return any additional information about the user. The returned access token can be used with `OAuth2Mixin.oauth2_request` to request additional information (perhaps from ``https://www.googleapis.com/oauth2/v2/userinfo``) Example usage: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ # noqa: E501 handler = cast(RequestHandler, self) http = self.get_auth_http_client() body = urllib.parse.urlencode( { "redirect_uri": redirect_uri, "code": code, "client_id": handler.settings[self._OAUTH_SETTINGS_KEY]["key"], "client_secret": handler.settings[self._OAUTH_SETTINGS_KEY]["secret"], "grant_type": "authorization_code", } ) response = await http.fetch( self._OAUTH_ACCESS_TOKEN_URL, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"}, body=body, ) return escape.json_decode(response.body)
Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not return any additional information about the user. The returned access token can be used with `OAuth2Mixin.oauth2_request` to request additional information (perhaps from ``https://www.googleapis.com/oauth2/v2/userinfo``) Example usage: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
def point2pos(self, point): """Converts a point or offset in a file to a (row, col) position.""" row = self._vim.eval('byte2line({})'.format(point)) col = self._vim.eval('{} - line2byte({})'.format(point, row)) return (int(row), int(col))
Converts a point or offset in a file to a (row, col) position.
def _setProperty(self, _type, data, win=None, mask=None): """ Send a ClientMessage event to the root window """ if not win: win = self.root if type(data) is str: dataSize = 8 else: data = (data+[0]*(5-len(data)))[:5] dataSize = 32 ev = protocol.event.ClientMessage( window=win, client_type=self.display.get_atom(_type), data=(dataSize, data)) if not mask: mask = (X.SubstructureRedirectMask | X.SubstructureNotifyMask) self.root.send_event(ev, event_mask=mask)
Send a ClientMessage event to the root window
def view(ctx): """ Build and view docs. """ report.info(ctx, "docs.view", f"viewing documentation") build_path = ctx.docs.directory / "build" / "html" / "index.html" build_path = pathname2url(build_path.as_posix()) webbrowser.open(f"file:{build_path!s}")
Build and view docs.
def _get_span(self, m): """ Gets a tuple that identifies a figure for the specific mention class that m belongs to. """ return (m.figure.document.id, m.figure.position)
Gets a tuple that identifies a figure for the specific mention class that m belongs to.
def set_target_from_config(self, cp, section): """Sets the target using the given config file. This looks for ``niterations`` to set the ``target_niterations``, and ``effective-nsamples`` to set the ``target_eff_nsamples``. Parameters ---------- cp : ConfigParser Open config parser to retrieve the argument from. section : str Name of the section to retrieve from. """ if cp.has_option(section, "niterations"): niterations = int(cp.get(section, "niterations")) else: niterations = None if cp.has_option(section, "effective-nsamples"): nsamples = int(cp.get(section, "effective-nsamples")) else: nsamples = None self.set_target(niterations=niterations, eff_nsamples=nsamples)
Sets the target using the given config file. This looks for ``niterations`` to set the ``target_niterations``, and ``effective-nsamples`` to set the ``target_eff_nsamples``. Parameters ---------- cp : ConfigParser Open config parser to retrieve the argument from. section : str Name of the section to retrieve from.
def check_w_normalized(W, N_k, tolerance = 1.0e-4): """Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1 Parameters ---------- W : np.ndarray, shape=(N, K), dtype='float' The normalized weight matrix for snapshots and states. W[n, k] is the weight of snapshot n in state k. N_k : np.ndarray, shape=(K), dtype='int' N_k[k] is the number of samples from state k. tolerance : float, optional, default=1.0e-4 Tolerance for checking equality of sums Returns ------- None : NoneType Returns a None object if test passes, otherwise raises a ParameterError with appropriate message if W is not normalized within tolerance. """ [N, K] = W.shape column_sums = np.sum(W, axis=0) badcolumns = (np.abs(column_sums - 1) > tolerance) if np.any(badcolumns): which_badcolumns = np.arange(K)[badcolumns] firstbad = which_badcolumns[0] raise ParameterError( 'Warning: Should have \sum_n W_nk = 1. Actual column sum for state %d was %f. %d other columns have similar problems' % (firstbad, column_sums[firstbad], np.sum(badcolumns))) row_sums = np.sum(W * N_k, axis=1) badrows = (np.abs(row_sums - 1) > tolerance) if np.any(badrows): which_badrows = np.arange(N)[badrows] firstbad = which_badrows[0] raise ParameterError( 'Warning: Should have \sum_k N_k W_nk = 1. Actual row sum for sample %d was %f. %d other rows have similar problems' % (firstbad, row_sums[firstbad], np.sum(badrows))) return
Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1 Parameters ---------- W : np.ndarray, shape=(N, K), dtype='float' The normalized weight matrix for snapshots and states. W[n, k] is the weight of snapshot n in state k. N_k : np.ndarray, shape=(K), dtype='int' N_k[k] is the number of samples from state k. tolerance : float, optional, default=1.0e-4 Tolerance for checking equality of sums Returns ------- None : NoneType Returns a None object if test passes, otherwise raises a ParameterError with appropriate message if W is not normalized within tolerance.
def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i \ in range(0, selection_num_starting_points)]
Random sample some init seed within bounds.
async def _wait(self, entity_type, entity_id, action, predicate=None): """ Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details. """ q = asyncio.Queue(loop=self._connector.loop) async def callback(delta, old, new, model): await q.put(delta.get_id()) self.add_observer(callback, entity_type, action, entity_id, predicate) entity_id = await q.get() # object might not be in the entity_map if we were waiting for a # 'remove' action return self.state._live_entity_map(entity_type).get(entity_id)
Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details.
def _set_many(self, i, j, x): """Sets value at each (i, j) to x Here (i,j) index major and minor respectively, and must not contain duplicate entries. """ i, j, M, N = self._prepare_indices(i, j) n_samples = len(x) offsets = np.empty(n_samples, dtype=self.indices.dtype) ret = _sparsetools.csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) if ret == 1: # rinse and repeat self.sum_duplicates() _sparsetools.csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, i, j, offsets) if -1 not in offsets: # make a list for interaction with h5py offsets = list(offsets) # only affects existing non-zero cells self.data[offsets] = x return else: # raise ValueError( # 'Currently, you cannot change the sparsity structure of a SparseDataset.') # replace where possible mask = offsets > -1 self.data[offsets[mask]] = x[mask] # only insertions remain mask = ~mask i = i[mask] i[i < 0] += M j = j[mask] j[j < 0] += N self._insert_many(i, j, x[mask])
Sets value at each (i, j) to x Here (i,j) index major and minor respectively, and must not contain duplicate entries.
def _validate_entities(self, tasks): """ Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task. """ if not tasks: raise TypeError(expected_type=Task, actual_type=type(tasks)) if not isinstance(tasks, set): if not isinstance(tasks, list): tasks = set([tasks]) else: tasks = set(tasks) for t in tasks: if not isinstance(t, Task): raise TypeError(expected_type=Task, actual_type=type(t)) return tasks
Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task.
def t_singlecomment_NEWLINE(self, t): r'\r?\n' t.lexer.pop_state() # Back to initial t.lexer.lineno += 1 return t
r'\r?\n
def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip() return randomip
Return a randomly generated, public IPv4 address. :return: ip address
def get_file_paths(self, id_list): """Get a list of file paths based of a set of ids Parameters ---------- id_list : list List of integer file keys Returns list of file paths """ if id_list is None: return [] try: path_array = self._table[id_list - 1]['path'] except IndexError: print("IndexError ", len(self._table), id_list) path_array = [] return [path for path in path_array]
Get a list of file paths based of a set of ids Parameters ---------- id_list : list List of integer file keys Returns list of file paths
def get_sequence_rule_admin_session_for_bank(self, bank_id): """Gets the ``OsidSession`` associated with the sequence rule administration service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` return: (osid.assessment.authoring.SequenceRuleAdminSession) - a ``SequenceRuleAdminSession`` raise: NotFound - no ``Bank`` found by the given ``Id`` raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_sequence_rule_admin()`` or ``supports_visible_federation()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_sequence_rule_admin()`` and ``supports_visible_federation()`` are ``true``.* """ if not self.supports_sequence_rule_admin(): raise errors.Unimplemented() ## # Also include check to see if the catalog Id is found otherwise raise errors.NotFound ## # pylint: disable=no-member return sessions.SequenceRuleAdminSession(bank_id, runtime=self._runtime)
Gets the ``OsidSession`` associated with the sequence rule administration service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` return: (osid.assessment.authoring.SequenceRuleAdminSession) - a ``SequenceRuleAdminSession`` raise: NotFound - no ``Bank`` found by the given ``Id`` raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_sequence_rule_admin()`` or ``supports_visible_federation()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_sequence_rule_admin()`` and ``supports_visible_federation()`` are ``true``.*
def load_environment(global_conf, app_conf): """Configure the Pylons environment via the ``pylons.config`` object """ # Pylons paths root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templates=[os.path.join(root, 'templates')]) # Initialize config with the basic options config.init_app(global_conf, app_conf, package='studio', paths=paths) # Defines custom config parameters config['resources_dir'] = os.path.join(root, 'resources') # path to mapserver dir containing default fonts and symbols config['mapserver_dir'] = os.path.join(config['resources_dir'], 'mapserver') # path to default directory datastore config['default_datastore_dir'] = os.path.join(config['resources_dir'], 'default_datastore') # path to the template including the <script> tags config['js_tmpl'] = os.path.join(paths['templates'][0], 'index.html') # Convert the debug variable from the config to a boolean value config['debug'] = asbool(config['debug']) config['routes.map'] = make_map() config['pylons.app_globals'] = app_globals.Globals() config['pylons.h'] = studio.lib.helpers # Create the Mako TemplateLookup, with the default auto-escaping config['pylons.app_globals'].mako_lookup = TemplateLookup( directories=paths['templates'], error_handler=handle_mako_error, module_directory=os.path.join(app_conf['cache_dir'], 'templates'), input_encoding='utf-8', output_encoding='utf-8', imports=['from webhelpers.html import escape'], default_filters=['escape']) # Setup SQLAlchemy database engine engine = engine_from_config(config, 'sqlalchemy.') init_model(engine)
Configure the Pylons environment via the ``pylons.config`` object
def windows_k_distinct(x, k): """Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)` """ dist, i, j = 0, 0, 0 # dist = |{x[i], ..., x[j-1]}| occ = {xi: 0 for xi in x} # number of occurrences in x[i:j] while j < len(x): while dist == k: # move start of interval occ[x[i]] -= 1 # update counters if occ[x[i]] == 0: dist -= 1 i += 1 while j < len(x) and (dist < k or occ[x[j]]): if occ[x[j]] == 0: # update counters dist += 1 occ[x[j]] += 1 j += 1 # move end of interval if dist == k: yield (i, j)
Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)`
def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read()
Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page.
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry): """tickEFP(EWrapper self, TickerId tickerId, TickType tickType, double basisPoints, IBString const & formattedBasisPoints, double totalDividends, int holdDays, IBString const & futureExpiry, double dividendImpact, double dividendsToExpiry)""" return _swigibpy.EWrapper_tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry)
tickEFP(EWrapper self, TickerId tickerId, TickType tickType, double basisPoints, IBString const & formattedBasisPoints, double totalDividends, int holdDays, IBString const & futureExpiry, double dividendImpact, double dividendsToExpiry)
def transform_frame(frame, transform, columns=None, direction='forward', return_all=True, args=(), **kwargs): """ Apply transform to specified columns. direction: 'forward' | 'inverse' return_all: bool True - return all columns, with specified ones transformed. False - return only specified columns. .. warning:: deprecated """ tfun, tname = parse_transform(transform, direction) columns = to_list(columns) if columns is None: columns = frame.columns if return_all: transformed = frame.copy() for c in columns: transformed[c] = tfun(frame[c], *args, **kwargs) else: transformed = frame.filter(columns).apply(tfun, *args, **kwargs) return transformed
Apply transform to specified columns. direction: 'forward' | 'inverse' return_all: bool True - return all columns, with specified ones transformed. False - return only specified columns. .. warning:: deprecated
def validate_header(cls, header: BlockHeader, parent_header: BlockHeader, check_seal: bool = True) -> None: """ :raise eth.exceptions.ValidationError: if the header is not valid """ if parent_header is None: # to validate genesis header, check if it equals canonical header at block number 0 raise ValidationError("Must have access to parent header to validate current header") else: validate_length_lte(header.extra_data, 32, title="BlockHeader.extra_data") validate_gas_limit(header.gas_limit, parent_header.gas_limit) if header.block_number != parent_header.block_number + 1: raise ValidationError( "Blocks must be numbered consecutively. Block number #{} has parent #{}".format( header.block_number, parent_header.block_number, ) ) # timestamp if header.timestamp <= parent_header.timestamp: raise ValidationError( "timestamp must be strictly later than parent, but is {} seconds before.\n" "- child : {}\n" "- parent : {}. ".format( parent_header.timestamp - header.timestamp, header.timestamp, parent_header.timestamp, ) ) if check_seal: cls.validate_seal(header)
:raise eth.exceptions.ValidationError: if the header is not valid
def assert_valid(self, instance, value=None): """Checks if valid, including HasProperty instances pass validation""" valid = super(Instance, self).assert_valid(instance, value) if not valid: return False if value is None: value = instance._get(self.name) if isinstance(value, HasProperties): value.validate() return True
Checks if valid, including HasProperty instances pass validation
def from_pickle(cls, path): """Load all objects from pickle file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening. """ with open(os.path.expanduser(path), "rb") as pickle: return cPickle.Unpickler(pickle).load()
Load all objects from pickle file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss.Computer().retrieve_all()). This method can potentially take a very long time! Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. Args: path: String file path to the file you wish to load from. Path will have ~ expanded prior to opening.
def plot(ID, pipeline='everest2', show=True, campaign=None): ''' Plots the de-trended flux for the given EPIC `ID` and for the specified `pipeline`. ''' # Get the data time, flux = get(ID, pipeline=pipeline, campaign=campaign) # Remove nans mask = np.where(np.isnan(flux))[0] time = np.delete(time, mask) flux = np.delete(flux, mask) # Plot it fig, ax = pl.subplots(1, figsize=(10, 4)) fig.subplots_adjust(bottom=0.15) ax.plot(time, flux, "k.", markersize=3, alpha=0.5) # Axis limits N = int(0.995 * len(flux)) hi, lo = flux[np.argsort(flux)][[N, -N]] pad = (hi - lo) * 0.1 ylim = (lo - pad, hi + pad) ax.set_ylim(ylim) # Show the CDPP from .k2 import CDPP ax.annotate('%.2f ppm' % CDPP(flux), xy=(0.98, 0.975), xycoords='axes fraction', ha='right', va='top', fontsize=12, color='r', zorder=99) # Appearance ax.margins(0, None) ax.set_xlabel("Time (BJD - 2454833)", fontsize=16) ax.set_ylabel("%s Flux" % pipeline.upper(), fontsize=16) fig.canvas.set_window_title("%s: EPIC %d" % (pipeline.upper(), ID)) if show: pl.show() pl.close() else: return fig, ax
Plots the de-trended flux for the given EPIC `ID` and for the specified `pipeline`.
def createNetcon(self, thresh=10): """ created netcon to record spikes """ nc = h.NetCon(self.soma(0.5)._ref_v, None, sec = self.soma) nc.threshold = thresh return nc
created netcon to record spikes
def _clean_data(self, str_value, file_data, obj_value): """This overwrite is neccesary for work with multivalues""" str_value = str_value or None obj_value = obj_value or None return (str_value, None, obj_value)
This overwrite is neccesary for work with multivalues
def parse(self, data): # type: (bytes) -> None ''' Parse the passed in data into a UDF Timestamp. Parameters: data - The data to parse. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Timestamp already initialized') (tz, timetype, self.year, self.month, self.day, self.hour, self.minute, self.second, self.centiseconds, self.hundreds_microseconds, self.microseconds) = struct.unpack_from(self.FMT, data, 0) self.timetype = timetype >> 4 def twos_comp(val, bits): # type: (int, int) -> int ''' Compute the 2's complement of int value val ''' if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is self.tz = twos_comp(((timetype & 0xf) << 8) | tz, 12) if self.tz < -1440 or self.tz > 1440: if self.tz != -2047: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF timezone') if self.year < 1 or self.year > 9999: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF year') if self.month < 1 or self.month > 12: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF month') if self.day < 1 or self.day > 31: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF day') if self.hour < 0 or self.hour > 23: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF hour') if self.minute < 0 or self.minute > 59: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF minute') if self.second < 0 or self.second > 59: raise pycdlibexception.PyCdlibInvalidISO('Invalid UDF second') self._initialized = True
Parse the passed in data into a UDF Timestamp. Parameters: data - The data to parse. Returns: Nothing.
def namedtuple_asdict(obj): """ Serializing a nested namedtuple into a Python dict """ if obj is None: return obj if hasattr(obj, "_asdict"): # detect namedtuple return OrderedDict(zip(obj._fields, (namedtuple_asdict(item) for item in obj))) if isinstance(obj, str): # iterables - strings return obj if hasattr(obj, "keys"): # iterables - mapping return OrderedDict(zip(obj.keys(), (namedtuple_asdict(item) for item in obj.values()))) if hasattr(obj, "__iter__"): # iterables - sequence return type(obj)((namedtuple_asdict(item) for item in obj)) # non-iterable cannot contain namedtuples return obj
Serializing a nested namedtuple into a Python dict
def handle_data(self, data): ''' Internal for parsing ''' if data: inTag = self._inTag if len(inTag) > 0: inTag[-1].appendText(data) elif data.strip(): #and not self.getRoot(): # Must be text prior to or after root node raise MultipleRootNodeException()
Internal for parsing
def object_merge(old, new, unique=False): """ Recursively merge two data structures. :param unique: When set to True existing list items are not set. """ if isinstance(old, list) and isinstance(new, list): if old == new: return for item in old[::-1]: if unique and item in new: continue new.insert(0, item) if isinstance(old, dict) and isinstance(new, dict): for key, value in old.items(): if key not in new: new[key] = value else: object_merge(value, new[key])
Recursively merge two data structures. :param unique: When set to True existing list items are not set.
def move(self, bucket, key, bucket_to, key_to, force='false'): """移动文件: 将资源从一个空间到另一个空间,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/move.html Args: bucket: 待操作资源所在空间 bucket_to: 目标资源空间名 key: 待操作资源文件名 key_to: 目标资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象 """ resource = entry(bucket, key) to = entry(bucket_to, key_to) return self.__rs_do('move', resource, to, 'force/{0}'.format(force))
移动文件: 将资源从一个空间到另一个空间,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/move.html Args: bucket: 待操作资源所在空间 bucket_to: 目标资源空间名 key: 待操作资源文件名 key_to: 目标资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
def generate_vector_color_map(self): """Generate color stops array for use with match expression in mapbox template""" vector_stops = [] # if join data specified as filename or URL, parse JSON to list of Python dicts if type(self.data) == str: self.data = geojson_to_dict_list(self.data) # loop through features in self.data to create join-data map for row in self.data: # map color to JSON feature using color_property color = color_map(row[self.color_property], self.color_stops, self.color_default) # link to vector feature using data_join_property (from JSON object) vector_stops.append([row[self.data_join_property], color]) return vector_stops
Generate color stops array for use with match expression in mapbox template
def profiling_query_formatter(view, context, query_document, name): """Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery """ return Markup( ''.join( [ '<div class="pymongo-query row">', '<div class="col-md-1">', '<a href="{}">'.format(query_document.get_admin_url(_external=True)), mongo_command_name_formatter( view, context, query_document, 'command_name' ), # '<span class="label {}">{}</span>'.format( # command_name_map.get(query_document.command_name, 'label-default'), # query_document.command_name, # ), '</div>', '<div class="col-md-10">', profiling_pure_query_formatter( None, None, query_document, 'command', tag='pre' ), '</div>', '<div class="col-md-1">', '<small>{} ms</small>'.format(query_document.duration), '</a>', '</div>', '</div>', ] ) )
Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery
def _set_pw_profile(self, v, load=False): """ Setter method for pw_profile, mapped from YANG variable /pw_profile (list) If this variable is read-only (config: false) in the source YANG file, then _set_pw_profile is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_pw_profile() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("pw_profile_name",pw_profile.pw_profile, yang_name="pw-profile", rest_name="pw-profile", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='pw-profile-name', extensions={u'tailf-common': {u'info': u'pw-profile for Node Specific configuration', u'callpoint': u'PWProfileBasicCallpoint', u'cli-mode-name': u'config-pw-profile-$(pw-profile-name)'}}), is_container='list', yang_name="pw-profile", rest_name="pw-profile", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'pw-profile for Node Specific configuration', u'callpoint': u'PWProfileBasicCallpoint', u'cli-mode-name': u'config-pw-profile-$(pw-profile-name)'}}, namespace='urn:brocade.com:mgmt:brocade-pw-profile', defining_module='brocade-pw-profile', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """pw_profile must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("pw_profile_name",pw_profile.pw_profile, yang_name="pw-profile", rest_name="pw-profile", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='pw-profile-name', extensions={u'tailf-common': {u'info': u'pw-profile for Node Specific configuration', u'callpoint': u'PWProfileBasicCallpoint', u'cli-mode-name': u'config-pw-profile-$(pw-profile-name)'}}), is_container='list', yang_name="pw-profile", rest_name="pw-profile", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'pw-profile for Node Specific configuration', u'callpoint': u'PWProfileBasicCallpoint', u'cli-mode-name': u'config-pw-profile-$(pw-profile-name)'}}, namespace='urn:brocade.com:mgmt:brocade-pw-profile', defining_module='brocade-pw-profile', yang_type='list', is_config=True)""", }) self.__pw_profile = t if hasattr(self, '_set'): self._set()
Setter method for pw_profile, mapped from YANG variable /pw_profile (list) If this variable is read-only (config: false) in the source YANG file, then _set_pw_profile is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_pw_profile() directly.
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" # Note: Relying on fact that vdot flattens arrays return np.vdot(tensor0, tensor1)
Return the inner product between two tensors
def _yyyymmdd_to_year_fraction(date): """Convert YYYMMDD.DD date string or float to YYYY.YYY""" date = str(date) if '.' in date: date, residual = str(date).split('.') residual = float('0.' + residual) else: residual = 0.0 date = _datetime.datetime.strptime(date, '%Y%m%d') date += _datetime.timedelta(days=residual) year = date.year year_start = _datetime.datetime(year=year, month=1, day=1) next_year_start = _datetime.datetime(year=year + 1, month=1, day=1) year_duration = next_year_start - year_start year_elapsed = date - year_start fraction = year_elapsed / year_duration return year + fraction
Convert YYYMMDD.DD date string or float to YYYY.YYY
async def _request( self, method: str, url: str, *, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against the RainMachine device.""" if not headers: headers = {} try: async with self._websession.request(method, url, headers=headers, params=params, json=json) as resp: resp.raise_for_status() data = await resp.json(content_type=None) return data except ClientError as err: raise RequestError( 'Error requesting data from {}: {}'.format(url, err))
Make a request against the RainMachine device.
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None): """ Create an Assignment Group. Create a new assignment group for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - name """The assignment group's name""" if name is not None: data["name"] = name # OPTIONAL - position """The position of this assignment group in relation to the other assignment groups""" if position is not None: data["position"] = position # OPTIONAL - group_weight """The percent of the total grade that this assignment group represents""" if group_weight is not None: data["group_weight"] = group_weight # OPTIONAL - sis_source_id """The sis source id of the Assignment Group""" if sis_source_id is not None: data["sis_source_id"] = sis_source_id # OPTIONAL - integration_data """The integration data of the Assignment Group""" if integration_data is not None: data["integration_data"] = integration_data # OPTIONAL - rules """The grading rules that are applied within this assignment group See the Assignment Group object definition for format""" if rules is not None: data["rules"] = rules self.logger.debug("POST /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/assignment_groups".format(**path), data=data, params=params, single_item=True)
Create an Assignment Group. Create a new assignment group for this course.
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. If this method is not overridden, the problem is solved without any regularisation other than the option enforcement of non-negativity of the solution and filter boundary crossing supression. When it is overridden, it should be explicitly called at the end of the overriding method. """ if self.opt['NonNegCoef']: self.Y[self.Y < 0.0] = 0.0 if self.opt['NoBndryCross']: for n in range(0, self.cri.dimN): self.Y[(slice(None),) * n + (slice(1 - self.D.shape[n], None),)] = 0.0
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. If this method is not overridden, the problem is solved without any regularisation other than the option enforcement of non-negativity of the solution and filter boundary crossing supression. When it is overridden, it should be explicitly called at the end of the overriding method.
def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None: """ Run prediction from the specified config path. If the config contains a ``predict`` section: - override hooks with ``predict.hooks`` if present - update dataset, model and main loop sections if the respective sections are present :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific path to the already trained model to be restored from. If ``None`` is passed, it is inferred from the configuration file location as the directory it is located in. :param cl_arguments: additional command line arguments which will update the configuration :param output_root: output root in which the training directory will be created """ config = None try: config_path = find_config(config_path) restore_from = restore_from or path.dirname(config_path) config = load_config(config_file=config_path, additional_args=cl_arguments) if 'predict' in config: for section in ['dataset', 'model', 'main_loop']: if section in config['predict']: config[section].update(config['predict'][section]) if 'hooks' in config['predict']: config['hooks'] = config['predict']['hooks'] else: logging.warning('Config does not contain `predict.hooks` section. ' 'No hook will be employed during the prediction.') config['hooks'] = [] validate_config(config) logging.debug('\tLoaded config: %s', config) except Exception as ex: # pylint: disable=broad-except fallback('Loading config failed', ex) run(config=config, output_root=output_root, restore_from=restore_from, eval='predict')
Run prediction from the specified config path. If the config contains a ``predict`` section: - override hooks with ``predict.hooks`` if present - update dataset, model and main loop sections if the respective sections are present :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific path to the already trained model to be restored from. If ``None`` is passed, it is inferred from the configuration file location as the directory it is located in. :param cl_arguments: additional command line arguments which will update the configuration :param output_root: output root in which the training directory will be created
def bed(args): """ %prog bed anchorsfile Convert ANCHORS file to BED format. """ from collections import defaultdict from jcvi.compara.synteny import AnchorFile, check_beds from jcvi.formats.bed import Bed from jcvi.formats.base import get_number p = OptionParser(bed.__doc__) p.add_option("--switch", default=False, action="store_true", help="Switch reference and aligned map elements") p.add_option("--scale", type="float", help="Scale the aligned map distance by factor") p.set_beds() p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) anchorsfile, = args switch = opts.switch scale = opts.scale ac = AnchorFile(anchorsfile) pairs = defaultdict(list) for a, b, block_id in ac.iter_pairs(): pairs[a].append(b) qbed, sbed, qorder, sorder, is_self = check_beds(anchorsfile, p, opts) bd = Bed() for q in qbed: qseqid, qstart, qend, qaccn = q.seqid, q.start, q.end, q.accn if qaccn not in pairs: continue for s in pairs[qaccn]: si, s = sorder[s] sseqid, sstart, send, saccn = s.seqid, s.start, s.end, s.accn if switch: qseqid, sseqid = sseqid, qseqid qstart, sstart = sstart, qstart qend, send = send, qend qaccn, saccn = saccn, qaccn if scale: sstart /= scale try: newsseqid = get_number(sseqid) except ValueError: raise ValueError("`{0}` is on `{1}` with no number to extract".\ format(saccn, sseqid)) bedline = "\t".join(str(x) for x in (qseqid, qstart - 1, qend, "{0}:{1}".format(newsseqid, sstart))) bd.add(bedline) bd.print_to_file(filename=opts.outfile, sorted=True)
%prog bed anchorsfile Convert ANCHORS file to BED format.
def _invalid_implementation(self, t, missing, mistyped, mismatched): """ Make a TypeError explaining why ``t`` doesn't implement our interface. """ assert missing or mistyped or mismatched, "Implementation wasn't invalid." message = "\nclass {C} failed to implement interface {I}:".format( C=getname(t), I=getname(self), ) if missing: message += dedent( """ The following methods of {I} were not implemented: {missing_methods}""" ).format( I=getname(self), missing_methods=self._format_missing_methods(missing) ) if mistyped: message += dedent( """ The following methods of {I} were implemented with incorrect types: {mismatched_types}""" ).format( I=getname(self), mismatched_types=self._format_mismatched_types(mistyped), ) if mismatched: message += dedent( """ The following methods of {I} were implemented with invalid signatures: {mismatched_methods}""" ).format( I=getname(self), mismatched_methods=self._format_mismatched_methods(mismatched), ) return InvalidImplementation(message)
Make a TypeError explaining why ``t`` doesn't implement our interface.
def mavlink_packet(self, m): '''handle an incoming mavlink packet from the master vehicle. Relay it to the tracker if it is a GLOBAL_POSITION_INT''' if m.get_type() in ['GLOBAL_POSITION_INT', 'SCALED_PRESSURE']: connection = self.find_connection() if not connection: return if m.get_srcSystem() != connection.target_system: connection.mav.send(m)
handle an incoming mavlink packet from the master vehicle. Relay it to the tracker if it is a GLOBAL_POSITION_INT
def get_all_reminders(self, params=None): """ Get all reminders This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list """ if not params: params = {} return self._iterate_through_pages(self.get_reminders_per_page, resource=REMINDERS, **{'params': params})
Get all reminders This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list
def info_impl(self): """Returns a dict of all runs and tags and their data availabilities.""" result = {} def add_row_item(run, tag=None): run_item = result.setdefault(run, { 'run': run, 'tags': {}, # A run-wide GraphDef of ops. 'run_graph': False}) tag_item = None if tag: tag_item = run_item.get('tags').setdefault(tag, { 'tag': tag, 'conceptual_graph': False, # A tagged GraphDef of ops. 'op_graph': False, 'profile': False}) return (run_item, tag_item) mapping = self._multiplexer.PluginRunToTagToContent( _PLUGIN_NAME_RUN_METADATA_WITH_GRAPH) for run_name, tag_to_content in six.iteritems(mapping): for (tag, content) in six.iteritems(tag_to_content): # The Summary op is defined in TensorFlow and does not use a stringified proto # as a content of plugin data. It contains single string that denotes a version. # https://github.com/tensorflow/tensorflow/blob/11f4ecb54708865ec757ca64e4805957b05d7570/tensorflow/python/ops/summary_ops_v2.py#L789-L790 if content != b'1': logger.warn('Ignoring unrecognizable version of RunMetadata.') continue (_, tag_item) = add_row_item(run_name, tag) tag_item['op_graph'] = True # Tensors associated with plugin name _PLUGIN_NAME_RUN_METADATA contain # both op graph and profile information. mapping = self._multiplexer.PluginRunToTagToContent( _PLUGIN_NAME_RUN_METADATA) for run_name, tag_to_content in six.iteritems(mapping): for (tag, content) in six.iteritems(tag_to_content): if content != b'1': logger.warn('Ignoring unrecognizable version of RunMetadata.') continue (_, tag_item) = add_row_item(run_name, tag) tag_item['profile'] = True tag_item['op_graph'] = True # Tensors associated with plugin name _PLUGIN_NAME_KERAS_MODEL contain # serialized Keras model in JSON format. mapping = self._multiplexer.PluginRunToTagToContent( _PLUGIN_NAME_KERAS_MODEL) for run_name, tag_to_content in six.iteritems(mapping): for (tag, content) in six.iteritems(tag_to_content): if content != b'1': logger.warn('Ignoring unrecognizable version of RunMetadata.') continue (_, tag_item) = add_row_item(run_name, tag) tag_item['conceptual_graph'] = True for (run_name, run_data) in six.iteritems(self._multiplexer.Runs()): if run_data.get(event_accumulator.GRAPH): (run_item, _) = add_row_item(run_name, None) run_item['run_graph'] = True for (run_name, run_data) in six.iteritems(self._multiplexer.Runs()): if event_accumulator.RUN_METADATA in run_data: for tag in run_data[event_accumulator.RUN_METADATA]: (_, tag_item) = add_row_item(run_name, tag) tag_item['profile'] = True return result
Returns a dict of all runs and tags and their data availabilities.
def make_measurement(name, channels, lumi=1.0, lumi_rel_error=0.1, output_prefix='./histfactory', POI=None, const_params=None, verbose=False): """ Create a Measurement from a list of Channels """ if verbose: llog = log['make_measurement'] llog.info("creating measurement {0}".format(name)) if not isinstance(channels, (list, tuple)): channels = [channels] # Create the measurement meas = Measurement('measurement_{0}'.format(name), '') meas.SetOutputFilePrefix(output_prefix) if POI is not None: if isinstance(POI, string_types): if verbose: llog.info("setting POI {0}".format(POI)) meas.SetPOI(POI) else: if verbose: llog.info("adding POIs {0}".format(', '.join(POI))) for p in POI: meas.AddPOI(p) if verbose: llog.info("setting lumi={0:f} +/- {1:f}".format(lumi, lumi_rel_error)) meas.lumi = lumi meas.lumi_rel_error = lumi_rel_error for channel in channels: if verbose: llog.info("adding channel {0}".format(channel.GetName())) meas.AddChannel(channel) if const_params is not None: if verbose: llog.info("adding constant parameters {0}".format( ', '.join(const_params))) for param in const_params: meas.AddConstantParam(param) return meas
Create a Measurement from a list of Channels
def ipv4_private(self, network=False, address_class=None): """ Returns a private IPv4. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Private IPv4 """ # compute private networks from given class supernet = _IPv4Constants._network_classes[ address_class or self.ipv4_network_class() ] private_networks = [ subnet for subnet in _IPv4Constants._private_networks if subnet.overlaps(supernet) ] # exclude special networks private_networks = self._exclude_ipv4_networks( private_networks, _IPv4Constants._excluded_networks, ) # choose random private network from the list private_network = self.generator.random.choice(private_networks) return self._random_ipv4_address_from_subnet(private_network, network)
Returns a private IPv4. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Private IPv4
def process_quantity(self, properties): """Process the uncertainty information from a given quantity and return it """ quant = Q_(properties[0]) if len(properties) > 1: unc = properties[1] uncertainty = unc.get('uncertainty', False) upper_uncertainty = unc.get('upper-uncertainty', False) lower_uncertainty = unc.get('lower-uncertainty', False) uncertainty_type = unc.get('uncertainty-type') if uncertainty_type == 'relative': if uncertainty: quant = quant.plus_minus(float(uncertainty), relative=True) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(float(upper_uncertainty), float(lower_uncertainty)) quant = quant.plus_minus(uncertainty, relative=True) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') elif uncertainty_type == 'absolute': if uncertainty: uncertainty = Q_(uncertainty) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(Q_(upper_uncertainty), Q_(lower_uncertainty)) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') else: raise ValueError('uncertainty-type must be one of "absolute" or "relative"') return quant
Process the uncertainty information from a given quantity and return it
def remove_event(self, ref): """ Removes an event for a ref (reference), """ # is this reference one which has been setup? if ref in self._refs: self._refs[ref].remove_callback(ref)
Removes an event for a ref (reference),
def vertical_headers(self, value): """ Setter for **self.__vertical_headers** attribute. :param value: Attribute value. :type value: OrderedDict """ if value is not None: assert type(value) is OrderedDict, "'{0}' attribute: '{1}' type is not 'OrderedDict'!".format( "vertical_headers", value) self.__vertical_headers = value
Setter for **self.__vertical_headers** attribute. :param value: Attribute value. :type value: OrderedDict
def get_activities(self, activity_ids=None, max_records=50): """ Get all activies for this group. """ return self.connection.get_all_activities(self, activity_ids, max_records)
Get all activies for this group.
def from_pandas_dataframe(cls, bqm_df, offset=0.0, interactions=None): """Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame. Args: bqm_df (:class:`pandas.DataFrame`): Quadratic unconstrained binary optimization (QUBO) model formatted as a pandas DataFrame. Row and column indices label the QUBO variables; values are QUBO coefficients. offset (optional, default=0.0): Constant offset for the binary quadratic model. interactions (iterable, optional, default=[]): Any additional 0.0-bias interactions to be added to the binary quadratic model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`vartype.BINARY`. Examples: This example creates a binary quadratic model from a QUBO in pandas DataFrame format while adding an interaction and setting a constant offset. >>> import dimod >>> import pandas as pd >>> pd_qubo = pd.DataFrame(data={0: [-1, 0], 1: [2, -1]}) >>> pd_qubo 0 1 0 -1 2 1 0 -1 >>> model = dimod.BinaryQuadraticModel.from_pandas_dataframe(pd_qubo, ... offset = 2.5, ... interactions = {(0,2), (1,2)}) >>> model.linear # doctest: +SKIP {0: -1, 1: -1.0, 2: 0.0} >>> model.quadratic # doctest: +SKIP {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0} >>> model.offset 2.5 >>> model.vartype <Vartype.BINARY: frozenset({0, 1})> """ if interactions is None: interactions = [] bqm = cls({}, {}, offset, Vartype.BINARY) for u, row in bqm_df.iterrows(): for v, bias in row.iteritems(): if u == v: bqm.add_variable(u, bias) elif bias: bqm.add_interaction(u, v, bias) for u, v in interactions: bqm.add_interaction(u, v, 0.0) return bqm
Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame. Args: bqm_df (:class:`pandas.DataFrame`): Quadratic unconstrained binary optimization (QUBO) model formatted as a pandas DataFrame. Row and column indices label the QUBO variables; values are QUBO coefficients. offset (optional, default=0.0): Constant offset for the binary quadratic model. interactions (iterable, optional, default=[]): Any additional 0.0-bias interactions to be added to the binary quadratic model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`vartype.BINARY`. Examples: This example creates a binary quadratic model from a QUBO in pandas DataFrame format while adding an interaction and setting a constant offset. >>> import dimod >>> import pandas as pd >>> pd_qubo = pd.DataFrame(data={0: [-1, 0], 1: [2, -1]}) >>> pd_qubo 0 1 0 -1 2 1 0 -1 >>> model = dimod.BinaryQuadraticModel.from_pandas_dataframe(pd_qubo, ... offset = 2.5, ... interactions = {(0,2), (1,2)}) >>> model.linear # doctest: +SKIP {0: -1, 1: -1.0, 2: 0.0} >>> model.quadratic # doctest: +SKIP {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0} >>> model.offset 2.5 >>> model.vartype <Vartype.BINARY: frozenset({0, 1})>