positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_all_items_of_reminder(self, reminder_id): """ Get all items of reminder 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 reminder_id: the reminder id :return: lis...
Get all items of reminder 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 reminder_id: the reminder id :return: list
def remove_properties(self): """ Removes the property layer (if exists) of the object (in memory) """ if self.features_layer is not None: self.features_layer.remove_properties() if self.header is not None: self.header.remove_lp('features')
Removes the property layer (if exists) of the object (in memory)
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = self.saved_admins # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') #...
save users to local DB
def get_dopants_from_shannon_radii(bonded_structure, num_dopants=5, match_oxi_sign=False): """ Get dopant suggestions based on Shannon radii differences. Args: bonded_structure (StructureGraph): A pymatgen structure graph decorated with oxidation state...
Get dopant suggestions based on Shannon radii differences. Args: bonded_structure (StructureGraph): A pymatgen structure graph decorated with oxidation states. For example, generated using the CrystalNN.get_bonded_structure() method. num_dopants (int): The nummber of suggest...
def _add_conntrack_stats_metrics(self, conntrack_path, tags): """ Parse the output of conntrack -S Add the parsed metrics """ try: output, _, _ = get_subprocess_output(["sudo", conntrack_path, "-S"], self.log) # conntrack -S sample: # cpu=0 fou...
Parse the output of conntrack -S Add the parsed metrics
def enable_mesos_basic_authentication(principal, password): """ enables and adds a new authorized principal """ restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file, text=secrets_entry,...
enables and adds a new authorized principal
def jsonAsCti(dct): """ Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes. The full class name of desired CTI class should be in dct['_class_'']. """ if '_class_'in dct: full_class_name = dct['_class_'] # TODO: how to handle the full_class_name? ...
Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes. The full class name of desired CTI class should be in dct['_class_''].
def migrate_user(instance): """ Move User.organisations['global']['role'] to top-level property and remove verified flag """ instance._resource.pop('verified', None) if 'role' in instance._resource: return instance global_org = instance.organisations.pop('global', {}) instance....
Move User.organisations['global']['role'] to top-level property and remove verified flag
def contains_key(self, key): """ Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (obje...
Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ...
def search(self, query: Optional[dict] = None, offset: Optional[int] = None, limit: Optional[int] = None, order_by: Union[None, list, tuple] = None) -> Sequence['IModel']: """return search result based on specified rulez query""" raise NotImplementedError
return search result based on specified rulez query
def get_recipients(self): """ Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for wh...
Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for which the following conditions are both true: ...
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parame...
|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parameter can be used to create a 'secret' channel upon creation. This parameter expects a :class:`dict` of ...
def getDetails(self, ip_address=None): """Get details for specified IP address as a Details object.""" raw_details = self._requestDetails(ip_address) raw_details['country_name'] = self.countries.get(raw_details.get('country')) raw_details['ip_address'] = ipaddress.ip_address(raw_details....
Get details for specified IP address as a Details object.
def simstate_encode(self, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lng): ''' Status of simulation environment, if used roll : Roll angle (rad) (float) pitch : Pitch angle (rad) (float) ...
Status of simulation environment, if used roll : Roll angle (rad) (float) pitch : Pitch angle (rad) (float) yaw : Yaw angle (rad) (float) xacc : X acceleration m/s/s (floa...
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) ...
From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string.
def segments(self): """ A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute. """ segments = [] for label, slc in zip(self....
A list of `Segment` objects. The list starts with the *non-zero* label. The returned list has a length equal to the number of labels and matches the order of the ``labels`` attribute.
def guess_mime_type(self, path): """ Guess an appropriate MIME type based on the extension of the provided path. :param str path: The of the file to analyze. :return: The guessed MIME type of the default if non are found. :rtype: str """ _, ext = posixpath.splitext(path) if ext in self.extensions_map...
Guess an appropriate MIME type based on the extension of the provided path. :param str path: The of the file to analyze. :return: The guessed MIME type of the default if non are found. :rtype: str
def _get_candidates(self, v): """ Collect candidates from all buckets from all hashes """ candidates = [] for lshash in self.lshashes: for bucket_key in lshash.hash_vector(v, querying=True): bucket_content = self.storage.get_bucket( lshash.hash_nam...
Collect candidates from all buckets from all hashes
def start_session(self, causal_consistency=True, default_transaction_options=None): """Start a logical session. This method takes the same parameters as :class:`~pymongo.client_session.SessionOptions`. See the :mod:`~pymongo.client_session` mo...
Start a logical session. This method takes the same parameters as :class:`~pymongo.client_session.SessionOptions`. See the :mod:`~pymongo.client_session` module for details and examples. Requires MongoDB 3.6. It is an error to call :meth:`start_session` if this client has been ...
def get_descriptor_for_layer(self, layer): """ Returns the standard JSON descriptor for the layer. There is a lot of usefule information in there. """ if not layer in self._layer_descriptor_cache: params = {'f': 'pjson'} if self.token: para...
Returns the standard JSON descriptor for the layer. There is a lot of usefule information in there.
def addToService(self, service, namespace=None, seperator='.'): """ Add this Handler's exported methods to an RPC Service instance. """ if namespace is None: namespace = [] if isinstance(namespace, basestring): namespace = [namespace] for n, m in ...
Add this Handler's exported methods to an RPC Service instance.
def wulff_gform_and_r(self, wulffshape, bulk_entry, r, from_sphere_area=False, r_units="nanometers", e_units="keV", normalize=False, scale_per_atom=False): """ Calculates the formation energy of the particle with arbitrary radius r. Args: ...
Calculates the formation energy of the particle with arbitrary radius r. Args: wulffshape (WulffShape): Initial, unscaled WulffShape bulk_entry (ComputedStructureEntry): Entry of the corresponding bulk. r (float (Ang)): Arbitrary effective radius of the WulffShape ...
def GetHasherNamesFromString(cls, hasher_names_string): """Retrieves a list of a hasher names from a comma separated string. Takes a string of comma separated hasher names transforms it to a list of hasher names. Args: hasher_names_string (str): comma separated names of hashers to enable, ...
Retrieves a list of a hasher names from a comma separated string. Takes a string of comma separated hasher names transforms it to a list of hasher names. Args: hasher_names_string (str): comma separated names of hashers to enable, the string 'all' to enable all hashers or 'none' to disable...
def acquire(self, specification, arguments=None): """ Returns an object for `specification` injecting its provider with a mix of its :term:`dependencies <dependency>` and given `arguments`. If there is a conflict between the injectable dependencies and `arguments`, the value from...
Returns an object for `specification` injecting its provider with a mix of its :term:`dependencies <dependency>` and given `arguments`. If there is a conflict between the injectable dependencies and `arguments`, the value from `arguments` is used. When one of `arguments` keys is...
def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs): "Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining ...
Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params.
def _jacobian_det(nodes, degree, st_vals): r"""Compute :math:`\det(D B)` at a set of values. This requires that :math:`B \in \mathbf{R}^2`. .. note:: This assumes but does not check that each ``(s, t)`` in ``st_vals`` is inside the reference triangle. .. warning:: This relies o...
r"""Compute :math:`\det(D B)` at a set of values. This requires that :math:`B \in \mathbf{R}^2`. .. note:: This assumes but does not check that each ``(s, t)`` in ``st_vals`` is inside the reference triangle. .. warning:: This relies on helpers in :mod:`bezier` for computing the ...
def dragDropFilter( self ): """ Returns a drag and drop filter method. If set, the method should \ accept 2 arguments: a QWidget and a drag/drop event and process it. :usage |from projexui.qt.QtCore import QEvent | |class MyWi...
Returns a drag and drop filter method. If set, the method should \ accept 2 arguments: a QWidget and a drag/drop event and process it. :usage |from projexui.qt.QtCore import QEvent | |class MyWidget(QWidget): | def __init...
def make_paginated_list(json, client, cls, parent_id=None, page_url=None, filters=None): """ Returns a PaginatedList populated with the first page of data provided, and the ability to load additional pages. This should not be called outside of the :any:`LinodeClient` class. ...
Returns a PaginatedList populated with the first page of data provided, and the ability to load additional pages. This should not be called outside of the :any:`LinodeClient` class. :param json: The JSON list to use as the first page :param client: A LinodeClient to use to load additio...
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, me...
Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_l...
Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda
def handle_form_submit(self): """Handle form submission """ protect.CheckAuthenticator(self.request) logger.info("Handle ResultsInterpration Submit") # Save the results interpretation res = self.request.form.get("ResultsInterpretationDepts", []) self.context.setRe...
Handle form submission
def as_opcode(cls: Type[T], logic_fn: Callable[..., Any], mnemonic: str, gas_cost: int) -> Type[T]: """ Class factory method for turning vanilla functions into Opcode classes. """ if gas_cost: @functools.wraps(logic_fn) ...
Class factory method for turning vanilla functions into Opcode classes.
def from_hive_file(cls, fname, *args, **kwargs): """ Open a local JSON hive file and initialize from the hive contained in that file, paying attention to the version keyword argument. """ version = kwargs.pop('version', None) require = kwargs.pop('require_https', True) ...
Open a local JSON hive file and initialize from the hive contained in that file, paying attention to the version keyword argument.
def messages(self): '''a generator yielding the :class:`Message` structures in the index''' # the file contains the fixed-size file header followed by # fixed-size message structures. start after the file header and # then simply return the message structures in sequence until the ...
a generator yielding the :class:`Message` structures in the index
def GetCompressedStreamTypeIndicators(cls, path_spec, resolver_context=None): """Determines if a file contains a supported compressed stream types. Args: path_spec (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built-in co...
Determines if a file contains a supported compressed stream types. Args: path_spec (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built-in context which is not multi process safe. Returns: list[str]: supported forma...
def _make_token_async(scopes, service_account_id): """Get a fresh authentication token. Args: scopes: A list of scopes. service_account_id: Internal-use only. Raises: An ndb.Return with a tuple (token, expiration_time) where expiration_time is seconds since the epoch. """ rpc = app_identity....
Get a fresh authentication token. Args: scopes: A list of scopes. service_account_id: Internal-use only. Raises: An ndb.Return with a tuple (token, expiration_time) where expiration_time is seconds since the epoch.
def opensearch(request): """ Return opensearch.xml. """ contact_email = settings.CONTACT_EMAIL short_name = settings.SHORT_NAME description = settings.DESCRIPTION favicon_width = settings.FAVICON_WIDTH favicon_height = settings.FAVICON_HEIGHT favicon_type = settings.FAVICON_TYPE ...
Return opensearch.xml.
def visit_member(self, attribute_key, attribute, member_node, member_data, is_link_node, parent_data, index=None): """ Visits a member node in a resource data tree. :param tuple attribute_key: tuple containing the attribute tokens identifying the member node's pos...
Visits a member node in a resource data tree. :param tuple attribute_key: tuple containing the attribute tokens identifying the member node's position in the resource data tree. :param attribute: mapped attribute holding information about the member node's name (in the parent) and t...
def _get_initial_name(self): """ Determine the most suitable name of the function. :return: The initial function name. :rtype: string """ name = None addr = self.addr # Try to get a name from existing labels if self._function_manager is n...
Determine the most suitable name of the function. :return: The initial function name. :rtype: string
def prepare(args): """ %prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile> Inferred file names --------------------------------------------- `lookuptblfile` : rearraylibrary.lookup `rearraylibfile`: rearraylibrary.fasta Pick sequences from the original library file a...
%prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile> Inferred file names --------------------------------------------- `lookuptblfile` : rearraylibrary.lookup `rearraylibfile`: rearraylibrary.fasta Pick sequences from the original library file and the rearrayed library file ...
def prop_to_size(vals, mi=0.0, ma=5.0, power=0.5, log=False): """ Converts an array of property values (e.g. a metric or score) to values that are more useful for marker sizes, line widths, or other visual sizes. The new sizes are computed as: y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x...
Converts an array of property values (e.g. a metric or score) to values that are more useful for marker sizes, line widths, or other visual sizes. The new sizes are computed as: y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x)})^{power} If ``log=True``, the natural logarithm of the property va...
def bespoke_md5(self, md5): """Performs Bespoke MD5 lookup on an MD5. Args: md5 - A hash. """ r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5)) self._output(r.text)
Performs Bespoke MD5 lookup on an MD5. Args: md5 - A hash.
def main(argv=None): """Start the command line interface.""" parser = ArgumentParser(prog="pygenstub") parser.add_argument("--version", action="version", version="%(prog)s " + __version__) parser.add_argument("files", nargs="*", help="generate stubs for given files") parser.add_argument( "-m...
Start the command line interface.
def nvrtcGetLoweredName(self, prog, name_expression): """ Notes the given name expression denoting a __global__ function or function template instantiation. """ lowered_name = c_char_p() code = self._lib.nvrtcGetLoweredName(prog, ...
Notes the given name expression denoting a __global__ function or function template instantiation.
def least_squares(Cui, X, Y, regularization, num_threads=0): """ For each user in Cui, calculate factors Xu for them using least squares on Y. Note: this is at least 10 times slower than the cython version included here. """ users, n_factors = X.shape YtY = Y.T.dot(Y) for u in range(us...
For each user in Cui, calculate factors Xu for them using least squares on Y. Note: this is at least 10 times slower than the cython version included here.
def get(self, name, hint): """Get the canonical name for a symbol. This is the default implementation. If the user specifies a name, the user-specified name will be used. When user does not specify a name, we automatically generate a name based on the hint string. ...
Get the canonical name for a symbol. This is the default implementation. If the user specifies a name, the user-specified name will be used. When user does not specify a name, we automatically generate a name based on the hint string. Parameters ---------- ...
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display...
Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.
def approxLognormal(N, mu=0.0, sigma=1.0, tail_N=0, tail_bound=[0.02,0.98], tail_order=np.e): ''' Construct a discrete approximation to a lognormal distribution with underlying normal distribution N(mu,sigma). Makes an equiprobable distribution by default, but user can optionally request augmented tail...
Construct a discrete approximation to a lognormal distribution with underlying normal distribution N(mu,sigma). Makes an equiprobable distribution by default, but user can optionally request augmented tails with exponentially sized point masses. This can improve solution accuracy in some models. Para...
def cd(path_to): # pylint: disable=invalid-name """cd to the given path If the path is a file, then cd to its parent directory Remember current directory before the cd so that we can cd back there with cd('-') """ if path_to == '-': if not cd.previous: raise PathError(...
cd to the given path If the path is a file, then cd to its parent directory Remember current directory before the cd so that we can cd back there with cd('-')
def taskException(self, *args, **kwargs): """ Task Exception Messages Whenever Taskcluster fails to run a message is posted to this exchange. This happens if the task isn't completed before its `deadlìne`, all retries failed (i.e. workers stopped responding), the task was ...
Task Exception Messages Whenever Taskcluster fails to run a message is posted to this exchange. This happens if the task isn't completed before its `deadlìne`, all retries failed (i.e. workers stopped responding), the task was canceled by another entity, or the task carried a malformed ...
def rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml): """ This function takes any gamma in the computational frame and rotates it to the cosmic frame. """ rotated_gamma = 0 for ii in range(2*l+1): rotated_gamma += Dlmk(l,m,ii-l,phi1,phi2,theta1,theta2).conjugate()*g...
This function takes any gamma in the computational frame and rotates it to the cosmic frame.
def _operation_speak_as_literal_punctuation( self, content, index, children ): """ The operation method of _speak_as method for literal-punctuation. :param content: The text content of element. :type content: str :param index: The index of pat...
The operation method of _speak_as method for literal-punctuation. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: lis...
def log_level_from_vebosity(verbosity): """ Get the `logging` module log level from a verbosity. :param verbosity: The number of times the `-v` option was specified. :return: The corresponding log level. """ if verbosity == 0: return logging.WARNING if verbosity == 1: return...
Get the `logging` module log level from a verbosity. :param verbosity: The number of times the `-v` option was specified. :return: The corresponding log level.
def _load_fits(self, h5file): """ Loads fits from h5file and returns a dictionary of fits. """ fits = {} for key in ['mf']: fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file) for key in ['chif', 'vf']: fits[key] = self._load_vector_fit(key, h5file) ...
Loads fits from h5file and returns a dictionary of fits.
def __api_openapi_descriptor(self, services, hostname=None, x_google_api_name=False): """Builds an OpenAPI description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. hostname: string, Hostname of the API, to override the value set on the ...
Builds an OpenAPI description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary that can be deseria...
def imap(requests, stream=False, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the ...
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_h...
def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs): """ Read filenames from the input stream and detect their palette. """ for line in istream: filename = line.strip() try: palette = extract_colors(filename, **kwargs) except Exception as e: ...
Read filenames from the input stream and detect their palette.
def importance(p_todo, p_ignore_weekend=config().ignore_weekends()): """ Calculates the importance of the given task. Returns an importance of zero when the task has been completed. If p_ignore_weekend is True, the importance value of the due date will be calculated as if Friday is immediately foll...
Calculates the importance of the given task. Returns an importance of zero when the task has been completed. If p_ignore_weekend is True, the importance value of the due date will be calculated as if Friday is immediately followed by Monday. This in case of a todo list at the office and you don't work ...
def p_single_statement_systemcall(self, p): 'single_statement : systemcall SEMICOLON' p[0] = SingleStatement(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
single_statement : systemcall SEMICOLON
def flash_spi_attach(self, hspi_arg): """Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command. """ # last 3 bytes in ESP_SPI_ATTACH argument are reserved values arg = struct.pack('<I', hsp...
Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command.
def maybe_print_as_json(opts, data, page_info=None): """Maybe print data as JSON.""" if opts.output not in ("json", "pretty_json"): return False root = {"data": data} if page_info is not None and page_info.is_valid: meta = root["meta"] = {} meta["pagination"] = page_info.as_dic...
Maybe print data as JSON.
def destroy_domain_record(self, domain_id, record_id): """ This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. reco...
This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. record_id: Integer, specifies the record_id to destroy.
def flatten(iterable): """ flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: li...
flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: list Examples: >>> from adm...
def allow_headers(self, domain, headers, secure=True): """ Allows ``domain`` to push data via the HTTP headers named in ``headers``. As with ``allow_domain``, ``domain`` may be either a full domain name or a wildcard. Again, use of wildcards is discouraged for security r...
Allows ``domain`` to push data via the HTTP headers named in ``headers``. As with ``allow_domain``, ``domain`` may be either a full domain name or a wildcard. Again, use of wildcards is discouraged for security reasons. The value for ``headers`` should be a list of header names...
def edges_to_polygons(edges, vertices): """ Given an edge list of indices and associated vertices representing lines, generate a list of polygons. Parameters ----------- edges : (n, 2) int Indexes of vertices which represent lines vertices : (m, 2) float Vertices in 2D space ...
Given an edge list of indices and associated vertices representing lines, generate a list of polygons. Parameters ----------- edges : (n, 2) int Indexes of vertices which represent lines vertices : (m, 2) float Vertices in 2D space Returns ---------- polygons : (p,) shapely...
def reformat_node(item=None, full=False): ''' Reformat the returned data from joyent, determine public/private IPs and strip out fields if necessary to provide either full or brief content. :param item: node dictionary :param full: full or brief output :return: dict ''' desired_keys = [...
Reformat the returned data from joyent, determine public/private IPs and strip out fields if necessary to provide either full or brief content. :param item: node dictionary :param full: full or brief output :return: dict
def createCashContract(self, symbol, currency="USD", exchange="IDEALPRO"): """ Used for FX, etc: createCashContract("EUR", currency="USD") """ contract_tuple = (symbol, "CASH", exchange, currency, "", 0.0, "") contract = self.createContract(contract_tuple) return contract
Used for FX, etc: createCashContract("EUR", currency="USD")
def image_summary(predictions, targets, hparams): """Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of t...
Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of the same shape as predictions.
def runExperiment4B(dirName): """ This runs the second experiment in the section "Simulations with Pure Temporal Sequences". Here we check accuracy of the L2/L4 networks in classifying the sequences. This experiment averages over many parameter combinations and could take several minutes. """ # Results ar...
This runs the second experiment in the section "Simulations with Pure Temporal Sequences". Here we check accuracy of the L2/L4 networks in classifying the sequences. This experiment averages over many parameter combinations and could take several minutes.
def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") arp_entry = ET....
Auto Generated Code
def server_call(method, server, timeout=DEFAULT_TIMEOUT, verify_ssl=True, **parameters): """Makes a call to an un-authenticated method on a server :param method: The method name. :type method: str :param server: The MyGeotab server. :type server: str :param timeout: The timeout to make the call...
Makes a call to an un-authenticated method on a server :param method: The method name. :type method: str :param server: The MyGeotab server. :type server: str :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes). :type timeout: float :para...
def find_venv_DST(): """Find where this package should be installed to in this virtualenv. For example: ``/path-to-venv/lib/python2.7/site-packages/package-name`` """ dir_path = os.path.dirname(SRC) if SYS_NAME == "Windows": DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME) ...
Find where this package should be installed to in this virtualenv. For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
def unload_module(modname): '''unload a module''' for (m,pm) in mpstate.modules: if m.name == modname: if hasattr(m, 'unload'): m.unload() mpstate.modules.remove((m,pm)) print("Unloaded module %s" % modname) return True print("Unable to...
unload a module
def _close(self, name, suppress_logging): """ closes one particular pool and all its amqp amqp connections """ try: pool_names = list(self.pools) if name in pool_names: self.pools[name].close() del self.pools[name] except Exception as e: ...
closes one particular pool and all its amqp amqp connections
def _create_window_frame(self, editor_buffer): """ Create a Window for the buffer, with underneat a status bar. """ @Condition def wrap_lines(): return self.editor.wrap_lines window = Window( self._create_buffer_control(editor_buffer), ...
Create a Window for the buffer, with underneat a status bar.
def _compare_mp_alias(br_i, br_j, analysis_set, analysis_set_subdir, unique_ajps, verbose): """ Alias for instance method that allows the method to be called in a multiprocessing pool. Needed as multiprocessing does not otherwise work on object instance methods. """ return br_i.compare(br_j, ana...
Alias for instance method that allows the method to be called in a multiprocessing pool. Needed as multiprocessing does not otherwise work on object instance methods.
def push_session(document, session_id=None, url='default', io_loop=None): ''' Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is o...
Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is open, changes made on the server side will be applied to this document, and cha...
def _draw_segments(data, ax, **params): """ Draw independent line segments between all the points """ color = to_rgba(data['color'], data['alpha']) # All we do is line-up all the points in a group # into segments, all in a single list. # Along the way the other parameters are put in ...
Draw independent line segments between all the points
def get_running_step_changes(write: bool = False) -> list: """...""" project = cd.project.get_internal_project() running_steps = list(filter( lambda step: step.is_running, project.steps )) def get_changes(step): step_data = writing.step_writer.serialize(step) if wr...
...
def add_arrow(self, tipLoc, tail=None, arrow=arrow.default): """This method adds a straight arrow that points to @var{TIPLOC}, which is a tuple of integers. @var{TAIL} specifies the starting point of the arrow. It is either None or a string consisting of the following letters: 'l', 'c', ...
This method adds a straight arrow that points to @var{TIPLOC}, which is a tuple of integers. @var{TAIL} specifies the starting point of the arrow. It is either None or a string consisting of the following letters: 'l', 'c', 'r', 't', 'm,', and 'b'. Letters 'l', 'c', or 'r' means to ...
def write_header(self): """Write `header` to `file`. See Also -------- write_data """ for properties in self.header.values(): value = properties['value'] offset_bytes = int(properties['offset']) self.file.seek(offset_bytes) ...
Write `header` to `file`. See Also -------- write_data
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just return the native string. @param x: a string of type C{...
def parse(self, data=None, table_name=None): """Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_name: when inside a table array, it is the table name """ temp = self.dict_() sub_table = None is_array =...
Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_name: when inside a table array, it is the table name
def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total...
Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total classes :return: Spark RDD with feature-label pairs
def fetch_next_page(self): """ Manually, synchronously fetch the next page. Supplied for manually retrieving pages and inspecting :meth:`~.current_page`. It is not necessary to call this when iterating through results; paging happens implicitly in iteration. """ if self.r...
Manually, synchronously fetch the next page. Supplied for manually retrieving pages and inspecting :meth:`~.current_page`. It is not necessary to call this when iterating through results; paging happens implicitly in iteration.
def register_child(self, child): """ Register a new child that will be closed whenever the current instance closes. :param child: The child instance. """ if self.closing: child.close() else: self._children.add(child) child.on_c...
Register a new child that will be closed whenever the current instance closes. :param child: The child instance.
def discrete_index(self, indices): """get elements by discrete indices :param indices: list discrete indices :return: elements """ elements = [] for i in indices: elements.append(self[i]) return elements
get elements by discrete indices :param indices: list discrete indices :return: elements
def get_length(self, y): """Get true length of y. Args: y (list): padded list. Returns: lens: true length of y. Examples: >>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]] >>> self.get_length(y) [1, 2, 3] """ lens = [...
Get true length of y. Args: y (list): padded list. Returns: lens: true length of y. Examples: >>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]] >>> self.get_length(y) [1, 2, 3]
def connect_to_cloudfiles(region=None, public=None): """Creates a client for working with CloudFiles/Swift.""" if public is None: is_public = not bool(get_setting("use_servicenet")) else: is_public = public ret = _create_client(ep_name="object_store", region=region, public=is...
Creates a client for working with CloudFiles/Swift.
def get_sys_info(): """Return system information as a dict.""" blob = dict() blob["OS"] = platform.system() blob["OS-release"] = platform.release() blob["Python"] = platform.python_version() return blob
Return system information as a dict.
def raise_on_packet(self, pkt_cls, state, get_next_msg=True): """ If the next message to be processed has type 'pkt_cls', raise 'state'. If there is no message waiting to be processed, we try to get one with the default 'get_next_msg' parameters. """ # Maybe we already pa...
If the next message to be processed has type 'pkt_cls', raise 'state'. If there is no message waiting to be processed, we try to get one with the default 'get_next_msg' parameters.
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pai...
Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
def build_mappings(self): """ Uses CSV files of field names and positions for different filing types to load mappings into memory, for use in parsing different types of rows. """ self.mappings = {} for record_type in ('sa', 'sb', 'F8872'): path = os.pa...
Uses CSV files of field names and positions for different filing types to load mappings into memory, for use in parsing different types of rows.
def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" mock._mock_parent = None mock._mock_new_pare...
Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.
async def _dump_variant(self, writer, elem, elem_type=None, params=None): """ Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return: """ if isinstance(...
Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return:
def colour(colour, message, bold=False): """ Color a message """ return style(fg=colour, text=message, bold=bold)
Color a message
def iter_chunks_class(self): """ Yield each readable chunk present in the region. Chunks that can not be read for whatever reason are silently skipped. This function returns a :class:`nbt.chunk.Chunk` instance. """ for m in self.get_metadata(): try: ...
Yield each readable chunk present in the region. Chunks that can not be read for whatever reason are silently skipped. This function returns a :class:`nbt.chunk.Chunk` instance.
def _get_smallest_set_not_on_axis(self, axis): """ Returns the smallest list of atoms with the same species and distance from origin AND does not lie on the specified axis. This maximal set limits the possible rotational symmetry operations, since atoms lying on a test axis is i...
Returns the smallest list of atoms with the same species and distance from origin AND does not lie on the specified axis. This maximal set limits the possible rotational symmetry operations, since atoms lying on a test axis is irrelevant in testing rotational symmetryOperations.
def toggle_item(self, item, test_func, field_name=None): """ Toggles the section based on test_func. test_func takes an item and returns a boolean. If it returns True, the item will be added to the given section. It will be removed from the section otherwise. Intended f...
Toggles the section based on test_func. test_func takes an item and returns a boolean. If it returns True, the item will be added to the given section. It will be removed from the section otherwise. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL. Behavior ...
def fetch(self, force=False): """ returns (dict): {'core': path to new egg, None if no update, 'gpg_sig': path to new sig, None if no update} """ tmpdir = tempfile.mkdtemp() fetch_results = { 'core': os.path.join(tmpdir, 'insights-core...
returns (dict): {'core': path to new egg, None if no update, 'gpg_sig': path to new sig, None if no update}