code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def offset(img, offset, fill_value=0): """ Moves the contents of image without changing the image size. The missing values are given a specified fill value. Parameters ---------- img : array Image. offset : (vertical_offset, horizontal_offset) Tuple of length 2, specifying t...
Moves the contents of image without changing the image size. The missing values are given a specified fill value. Parameters ---------- img : array Image. offset : (vertical_offset, horizontal_offset) Tuple of length 2, specifying the offset along the two axes. fill_value : dtyp...
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None): """Perform all checks on a host using acquired artifacts. Checks are selected based on the artifacts available and the host attributes (e...
Perform all checks on a host using acquired artifacts. Checks are selected based on the artifacts available and the host attributes (e.g. os_name/cpe/labels) provided as either parameters, or in the knowledgebase artifact. A KnowledgeBase artifact should be provided that contains, at a minimum: - OS - Hos...
def get_platform_node_selector(self, platform): """ search the configuration for entries of the form node_selector.platform :param platform: str, platform to search for, can be null :return dict """ nodeselector = {} if platform: nodeselector_str = sel...
search the configuration for entries of the form node_selector.platform :param platform: str, platform to search for, can be null :return dict
def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INE...
Returns a list of IP addresses of a given hostname or None if not found.
def get_idxs(data, eid2idx): """ Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices """ uniq, inv = numpy.unique(data['eid'], return_inverse=True) idxs = numpy.array([eid2idx[eid] f...
Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices
def init_config(self, config): ''' Configures this extension with a given configuration dictionary. This allows use of this extension without a flask app. Args: config (dict): A dictionary with configuration keys ''' self.config.update(config) self....
Configures this extension with a given configuration dictionary. This allows use of this extension without a flask app. Args: config (dict): A dictionary with configuration keys
def search(cls, query, search_opts=None): """ Search tags. For more information, see the backend function :py:func:`nipap.backend.Nipap.search_tag`. """ if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection() try: se...
Search tags. For more information, see the backend function :py:func:`nipap.backend.Nipap.search_tag`.
def delete(self): """Removes .sqlite file. **CAREFUL** needless say""" self._ensure_filename() self._close_if_open() os.remove(self.filename)
Removes .sqlite file. **CAREFUL** needless say
def units2pint(value): """Return the pint Unit for the DataArray units. Parameters ---------- value : xr.DataArray or string Input data array or expression. Returns ------- pint.Unit Units of the data array. """ def _transform(s): """Convert a CF-unit string t...
Return the pint Unit for the DataArray units. Parameters ---------- value : xr.DataArray or string Input data array or expression. Returns ------- pint.Unit Units of the data array.
def delete_endpoint_config(self, endpoint_config_name): """Delete an Amazon SageMaker endpoint configuration. Args: endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete. """ LOGGER.info('Deleting endpoint configuration with name: {}'.form...
Delete an Amazon SageMaker endpoint configuration. Args: endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete.
def _ns_var( py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS ) -> ast.Assign: """Assign a Python variable named `ns_var` to the value of the current namespace.""" return ast.Assign( targets=[ast.Name(id=py_ns_var, ctx=ast.Store())], value=ast.Call( ...
Assign a Python variable named `ns_var` to the value of the current namespace.
def find_le(self, dt): '''Find the index corresponding to the rightmost value less than or equal to *dt*. If *dt* is less than :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.LeftOutOfBound` exception will raise. *dt* must be a python datetime.date instance.''' i = bisect_right(self.dat...
Find the index corresponding to the rightmost value less than or equal to *dt*. If *dt* is less than :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.LeftOutOfBound` exception will raise. *dt* must be a python datetime.date instance.
def _api_all(self): """Glances API RESTful implementation. Return the JSON representation of all the plugins HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ response.content_type = 'application/json; charset=utf-8' if self.arg...
Glances API RESTful implementation. Return the JSON representation of all the plugins HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error
def get_current_context_id(): """Identifis which context it is (greenlet, stackless, or thread). :returns: the identifier of the current context. """ global get_current_context_id if greenlet is not None: if stackless is None: get_current_context_id = greenlet.getcurrent ...
Identifis which context it is (greenlet, stackless, or thread). :returns: the identifier of the current context.
def children(self): """Retrieve tags associated to the current node""" tags = {'*'} if self.tag: network_tags = {self.tag: self.campaign.network.tags[self.tag]} else: network_tags = self.campaign.network.tags for tag, configs in network_tags.items(): ...
Retrieve tags associated to the current node
def blocking(self): """ Display queries holding locks other queries are waiting to be released. Record( pid=40821, source='', running_for=datetime.timedelta(0, 0, 2857), waiting=False, query='SELECT pg_sleep(10);' ) ...
Display queries holding locks other queries are waiting to be released. Record( pid=40821, source='', running_for=datetime.timedelta(0, 0, 2857), waiting=False, query='SELECT pg_sleep(10);' ) :returns: list of Records
def delete_database(self, instance_id, database_id, project_id=None): """ Drops a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner...
Drops a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner. :type database_id: str :param project_id: Optional, the ID of the GCP p...
def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath...
Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. ...
def commit_new_version(version: str): """ Commits the file containing the version number variable with the version number as the commit message. :param version: The version number to be used in the commit message. """ check_repo() commit_message = config.get('semantic_release', 'commit_mes...
Commits the file containing the version number variable with the version number as the commit message. :param version: The version number to be used in the commit message.
def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCrea...
Initialize data from a CSR matrix.
def try_disk(self, path, gpg=True): """ Try to load json off disk """ if not os.path.isfile(path): return if not gpg or self.validate_gpg_sig(path): stream = open(path, 'r') json_stream = stream.read() if len(json_stream): ...
Try to load json off disk
def keys(self): """ return a list of the content types this set supports. this is not a complete list: serializers can accept more than one content type. However, it is a good representation of the class of content types supported. """ return_value = [] f...
return a list of the content types this set supports. this is not a complete list: serializers can accept more than one content type. However, it is a good representation of the class of content types supported.
def package(self): """Build the App package for deployment to ThreatConnect Exchange.""" # create build directory tmp_path = os.path.join(self.app_path, self.args.outdir, 'build') if not os.path.isdir(tmp_path): os.makedirs(tmp_path) # temp path and cleanup t...
Build the App package for deployment to ThreatConnect Exchange.
def _compute_confidence_bounds_of_transform(self, transform, alpha, ci_labels): """ This computes the confidence intervals of a transform of the parameters. Ex: take the fitted parameters, a function/transform and the variance matrix and give me back confidence intervals of the transform...
This computes the confidence intervals of a transform of the parameters. Ex: take the fitted parameters, a function/transform and the variance matrix and give me back confidence intervals of the transform. Parameters ----------- transform: function must a function of...
def _is_device_active(device): """ Checks dmsetup to see if a device is already active """ cmd = ['dmsetup', 'info', device] dmsetup_info = util.subp(cmd) for dm_line in dmsetup_info.stdout.split("\n"): line = dm_line.split(':') if ('State' in line...
Checks dmsetup to see if a device is already active
def success_response(self, method_resp, **kw): """ Make a standard "success" response, which contains some ancilliary data. Also, detect if this node is too far behind the Bitcoin blockchain, and if so, convert this into an error message. """ resp = { ...
Make a standard "success" response, which contains some ancilliary data. Also, detect if this node is too far behind the Bitcoin blockchain, and if so, convert this into an error message.
def decode(): """Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_binary_stream('stdin') sink = click.get_text_stream('stdout') try: pbf = stdin.read() data = geobuf.decode(pbf) js...
Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.
def linkRecord(self, existing_domain, new_domain, rtype, callback=None, errback=None, **kwargs): """ Create a new linked record in this zone. These records use the configuration (answers, ttl, filters, etc) from an existing record in the NS1 platform. :param ...
Create a new linked record in this zone. These records use the configuration (answers, ttl, filters, etc) from an existing record in the NS1 platform. :param str existing_domain: FQDN of the target record whose config \ should be used. Does not have to be in the same zone. :...
def pull(directory: str) -> Commit: """ Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on """ if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}...
Pulls the subrepo that has been cloned into the given directory. :param directory: the directory containing the subrepo :return: the commit the subrepo is on
def _populate_cmd_lists(self): """ Populate self.lists and hashes: self.commands, and self.aliases, self.category """ self.commands = {} self.aliases = {} self.category = {} # self.short_help = {} for cmd_instance in self.cmd_instances: if not hasattr(...
Populate self.lists and hashes: self.commands, and self.aliases, self.category
def _put(self, route, data, headers=None, failure_message=None): """ Execute a put request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.put( ...
Execute a put request and return the result :param data: :param headers: :return:
def send_topic_message(self, topic_name, message=None): ''' Enqueues a message into the specified topic. The limit to the number of messages which may be present in the topic is governed by the message size in MaxTopicSizeInBytes. If this message causes the topic to exceed its qu...
Enqueues a message into the specified topic. The limit to the number of messages which may be present in the topic is governed by the message size in MaxTopicSizeInBytes. If this message causes the topic to exceed its quota, a quota exceeded error is returned and the message will be reje...
def add_title_widget(self, ref, text="Title"): """ Add Title Widget """ if ref not in self.widgets: widget = widgets.TitleWidget(screen=self, ref=ref, text=text) self.widgets[ref] = widget return self.widgets[ref]
Add Title Widget
def add_why(voevent, importance=None, expires=None, inferences=None): """Add Inferences, or set importance / expires attributes of the Why section. .. note:: ``importance`` / ``expires`` are 'Why' attributes, therefore setting them will overwrite previous values. ``inferences``, on the...
Add Inferences, or set importance / expires attributes of the Why section. .. note:: ``importance`` / ``expires`` are 'Why' attributes, therefore setting them will overwrite previous values. ``inferences``, on the other hand, are appended to the list. Args: voevent(:class:`Vo...
def options(self, parser, env): """Sets additional command line options.""" Plugin.options(self, parser, env) parser.add_option( '--html-file', action='store', dest='html_file', metavar="FILE", default=env.get('NOSE_HTML_FILE', 'nosetests.html'), h...
Sets additional command line options.
def export_coreml(self, path, image_shape=(256, 256), include_flexible_shape=True): """ Save the model in Core ML format. The Core ML model takes an image of fixed size, and a style index inputs and produces an output of an image of fixed size Parameters -------...
Save the model in Core ML format. The Core ML model takes an image of fixed size, and a style index inputs and produces an output of an image of fixed size Parameters ---------- path : string A string to the path for saving the Core ML model. image_shape: tu...
def attrgetter_atom_handle(loc, tokens): """Process attrgetter literals.""" name, args = attrgetter_atom_split(tokens) if args is None: return '_coconut.operator.attrgetter("' + name + '")' elif "." in name: raise CoconutDeferredSyntaxError("cannot have attribute access in implicit metho...
Process attrgetter literals.
def get_binary_stream(name): """Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Pyth...
Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Python 3. :param name: the name of ...
def set_vm_status(self, device='FLOPPY', boot_option='BOOT_ONCE', write_protect='YES'): """Sets the Virtual Media drive status and allows the boot options for booting from the virtual media. """ return self._call_method('set_vm_status', device, boot_option, ...
Sets the Virtual Media drive status and allows the boot options for booting from the virtual media.
def execCmdThruIUCV(rh, userid, strCmd, hideInLog=[]): """ Send a command to a virtual machine using IUCV. Input: Request Handle Userid of the target virtual machine Command string to send (Optional) List of strCmd words (by index) to hide in sysLog by replacing the wo...
Send a command to a virtual machine using IUCV. Input: Request Handle Userid of the target virtual machine Command string to send (Optional) List of strCmd words (by index) to hide in sysLog by replacing the word with "<hidden>". Output: Dictionary containing the f...
def extract_labels(self) -> np.ndarray: """Extract condition labels. Returns ------- np.ndarray The condition label of each epoch. """ condition_idxs, epoch_idxs, _ = np.where(self) _, unique_epoch_idxs = np.unique(epoch_idxs, return_index=True) ...
Extract condition labels. Returns ------- np.ndarray The condition label of each epoch.
def stub(base_class=None, **attributes): """creates a python class on-the-fly with the given keyword-arguments as class-attributes accessible with .attrname. The new class inherits from Use this to mock rather than stub. """ if base_class is None: base_class = object members = { ...
creates a python class on-the-fly with the given keyword-arguments as class-attributes accessible with .attrname. The new class inherits from Use this to mock rather than stub.
def _log_start_transaction(self, endpoint, data, json, files, params): """Log the beginning of an API request.""" # TODO: add information about the caller, i.e. which module + line of code called the .request() method # This can be done by fetching current traceback and then traversing it ...
Log the beginning of an API request.
def factory_profiles(self): '''The factory profiles of all loaded modules.''' with self._mutex: if not self._factory_profiles: self._factory_profiles = [] for fp in self._obj.get_factory_profiles(): self._factory_profiles.append(utils.nvlis...
The factory profiles of all loaded modules.
def get_cov_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper, lambda1=None, lambda2=None, quadparam1=None, quadparam2=None): """ Function to convert between masses and spins and locations in the xi parameter space. Xi = Cartesian metric and rotated to principal...
Function to convert between masses and spins and locations in the xi parameter space. Xi = Cartesian metric and rotated to principal components. Parameters ----------- mass1 : float Mass of heavier body. mass2 : float Mass of lighter body. spin1z : float Spin of body 1. ...
def user(self, id, expand=None): """Get a user Resource from the server. :param id: ID of the user to get :param id: str :param expand: Extra information to fetch inside each resource :type expand: Optional[Any] :rtype: User """ user = User(self._options...
Get a user Resource from the server. :param id: ID of the user to get :param id: str :param expand: Extra information to fetch inside each resource :type expand: Optional[Any] :rtype: User
def Debugger_setBlackboxedRanges(self, scriptId, positions): """ Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the ...
Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script. 'positions' (type: array) -> No description No return...
def node_save(self, astr_pathInTree, **kwargs): """ Typically called by the explore()/recurse() methods and of form: f(pathInTree, **kwargs) and returns dictionary of which one element is 'status': True|False recursion continuation fl...
Typically called by the explore()/recurse() methods and of form: f(pathInTree, **kwargs) and returns dictionary of which one element is 'status': True|False recursion continuation flag is returned: 'continue': True|False to sign...
def emit(self, signalName, *args, **kwargs): """ Emits a signal by name if it exists. Any additional args or kwargs are passed to the signal :param signalName: the signal name to emit """ assert signalName in self, "%s is not a registered signal" % signalName self[signalN...
Emits a signal by name if it exists. Any additional args or kwargs are passed to the signal :param signalName: the signal name to emit
def get_label(self, name): """ :calls: `GET /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param name: string :rtype: :class:`github.Label.Label` """ assert isinstance(name, (str, unicode)), name headers, data = self._requester....
:calls: `GET /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param name: string :rtype: :class:`github.Label.Label`
def read_igor_marginals_txt(marginals_file_name , dim_names=False): """Load raw IGoR model marginals. Parameters ---------- marginals_file_name : str File name for a IGOR model marginals file. Returns ------- model_dict : dict Dictionary with model marginals. dimens...
Load raw IGoR model marginals. Parameters ---------- marginals_file_name : str File name for a IGOR model marginals file. Returns ------- model_dict : dict Dictionary with model marginals. dimension_names_dict : dict Dictionary that defines IGoR model dependecie...
def load_local_config(filename): """Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module. """ if not filename: return imp.new_module('local_pylint_config') module = imp.load_...
Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module.
def generator(self, Xgen, Xexc, Xgov, Vgen): """ Generator model. Based on Generator.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/ matdyn/} for more information. """ generators = self.dyn_gene...
Generator model. Based on Generator.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/ matdyn/} for more information.
def argument_parser(args): """Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file ...
Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file a boolean to declare if we wa...
def _insert_file(cursor, file, media_type): """Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file. """ resource_hash = _get_file_sha1(file) cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resource_hash...
Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file.
def job_listener(event): '''Listens to completed job''' job_id = event.job.args[0] if event.code == events.EVENT_JOB_MISSED: db.mark_job_as_missed(job_id) elif event.exception: if isinstance(event.exception, util.JobError): error_object = event.exception.as_dict() el...
Listens to completed job
def install(name=None, sources=None, saltenv='base', **kwargs): ''' Install the passed package. Can install packages from the following sources: * Locally (package already exists on the minion * HTTP/HTTPS server * FTP server * Salt master Returns a dict containing the new package name...
Install the passed package. Can install packages from the following sources: * Locally (package already exists on the minion * HTTP/HTTPS server * FTP server * Salt master Returns a dict containing the new package names and versions: .. code-block:: python {'<package>': {'old': '...
def run(*awaitables, timeout: float = None): """ By default run the event loop forever. When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results. An optional timeout (in seconds) can be given that will raise asyncio...
By default run the event loop forever. When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results. An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready within the ...
def set_dut_configuration(self, ident, config): """ Set requirements for dut ident. :param ident: Identity of dut. :param config: If ResourceRequirements object, add object as requirements for resource ident. If dictionary, create new ResourceRequirements object from dictionary....
Set requirements for dut ident. :param ident: Identity of dut. :param config: If ResourceRequirements object, add object as requirements for resource ident. If dictionary, create new ResourceRequirements object from dictionary. :return: Nothing
def _read_datasets(self, dataset_nodes, **kwargs): """Read the given datasets from file.""" # Sort requested datasets by reader reader_datasets = {} for node in dataset_nodes: ds_id = node.name # if we already have this node loaded or the node was assigned ...
Read the given datasets from file.
def unzip(from_file, to_folder): """ Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`. """ with ZipFile(os.path.abspath(from_file), 'r') as to_unzip: to_unzip.extractall(os.path.abspath(to_folder))
Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`.
def map_reduce(self, map, reduce, out, full_response=False, **kwargs): """Perform a map/reduce operation on this collection. If `full_response` is ``False`` (default) returns a :class:`~pymongo.collection.Collection` instance containing the results of the operation. Otherwise, returns t...
Perform a map/reduce operation on this collection. If `full_response` is ``False`` (default) returns a :class:`~pymongo.collection.Collection` instance containing the results of the operation. Otherwise, returns the full response from the server to the `map reduce command`_. :P...
def echo(root_resource, message): """Have the server echo our message back.""" params = dict(message=message) return root_resource.get(ECHO_PATH, params)
Have the server echo our message back.
def parse_file_provider(uri): """Find the file provider for a URI.""" providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL} # URI scheme detector uses a range up to 30 since none of the IANA # registered schemes are longer than this. provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29...
Find the file provider for a URI.
def _single_array_element(data_obj, xj_path, array_path, create_dict_path): """Retrieves a single array for a '@' JSON path marker. :param list data_obj: The current data object. :param str xj_path: A json path. :param str array_path: A lookup key. :param bool create_dict_path create a dict path. ...
Retrieves a single array for a '@' JSON path marker. :param list data_obj: The current data object. :param str xj_path: A json path. :param str array_path: A lookup key. :param bool create_dict_path create a dict path.
def _get_anon_bind(self): """Check anonymous bind :return: 'on', 'off', 'rootdse' or None """ r = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-allow-anonymous-access'], scope=ldap.SCOPE_BASE ) dn, attrs = r[0] ...
Check anonymous bind :return: 'on', 'off', 'rootdse' or None
def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0, only_standard=False): """ Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @...
Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @type lang: str @param lang: Languaje. @type num: int @param num: Number of results per page. @type s...
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded day. dt : pd.Timestamp The dt a...
def list_container_instance_groups(access_token, subscription_id, resource_group): '''List the container groups in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group nam...
List the container groups in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON list of container groups and their properties...
def pipeline(pipe=None, name=None, autoexec=False, exit_handler=None): """ This is the foundational function for all of redpipe. Everything goes through here. create pipelines, nest pipelines, get pipelines for a specific name. It all happens here. Here's a simple example: .. code:: python...
This is the foundational function for all of redpipe. Everything goes through here. create pipelines, nest pipelines, get pipelines for a specific name. It all happens here. Here's a simple example: .. code:: python with pipeline() as pipe: pipe.set('foo', 'bar') f...
def lookup(instruction, instructions = None): """Looks up instruction, which can either be a function or a string. If it's a string, returns the corresponding method. If it's a function, returns the corresponding name. """ if instructions is None: instructions = default_instructions if ...
Looks up instruction, which can either be a function or a string. If it's a string, returns the corresponding method. If it's a function, returns the corresponding name.
def _compute_value(power, wg): """Return the weight corresponding to single power.""" if power not in wg: p1, p2 = power # y power if p1 == 0: yy = wg[(0, -1)] wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy) # x power else: xx = wg[...
Return the weight corresponding to single power.
def __precision(y_true, y_pred): ''' Precision metric tolerant to unlabeled data in y_true, NA values are ignored for the precision calculation ''' # make copies of the arrays to avoid modifying the original ones y_true = np.copy(y_true) y_pred = np.copy(y_pred) # precision = tp...
Precision metric tolerant to unlabeled data in y_true, NA values are ignored for the precision calculation
def resetaA(self,pot=None,type=None): """ NAME: resetaA PURPOSE: re-set up an actionAngle module for this Orbit INPUT: (none) OUTPUT: True if reset happened, False otherwise HISTORY: 2014-01-06 - Written - Bo...
NAME: resetaA PURPOSE: re-set up an actionAngle module for this Orbit INPUT: (none) OUTPUT: True if reset happened, False otherwise HISTORY: 2014-01-06 - Written - Bovy (IAS)
def _add_nic_to_mapping(self, net, dom, nic): """ Populates the given net spec mapping entry with the nics of the given domain, by the following rules: * If ``net`` is management, 'domain_name': nic_ip * For each interface: 'domain_name-eth#': nic_ip, where # is the ...
Populates the given net spec mapping entry with the nics of the given domain, by the following rules: * If ``net`` is management, 'domain_name': nic_ip * For each interface: 'domain_name-eth#': nic_ip, where # is the index of the nic in the *domain* definition. *...
def default_absorbers(Tatm, ozone_file = 'apeozone_cam3_5_54.nc', verbose = True,): '''Initialize a dictionary of well-mixed radiatively active gases All values are volumetric mixing ratios. Ozone is set to a climatology. All other gases are assumed well-mixed: ...
Initialize a dictionary of well-mixed radiatively active gases All values are volumetric mixing ratios. Ozone is set to a climatology. All other gases are assumed well-mixed: - CO2 - CH4 - N2O - O2 - CFC11 - CFC12 - CFC22 - CCL4 Specifi...
def query_cast(value, answers, ignorecase = False): """A cast function for query Answers should look something like it does in query """ if ignorecase: value = value.lower() for item in answers: for a in item['values']: if ignorecase and (value == str(a).lower()): ...
A cast function for query Answers should look something like it does in query
def get_count(cls, date_field=None, start=None, end=None, filters={}): """ Build the DSL query for counting the number of items. :param date_field: field with the date :param start: date from which to start counting, should be a datetime.datetime object :param end: date until wh...
Build the DSL query for counting the number of items. :param date_field: field with the date :param start: date from which to start counting, should be a datetime.datetime object :param end: date until which to count items, should be a datetime.datetime object :param filters: dict with ...
def async_(fn): """Wrap the given function into a coroutine function.""" @functools.wraps(fn) async def wrapper(*args, **kwargs): return await fn(*args, **kwargs) return wrapper
Wrap the given function into a coroutine function.
def create_atomic_wrapper(cls, wrapped_func): """Returns a wrapped function.""" def _create_atomic_wrapper(*args, **kwargs): """Actual wrapper.""" # When a view call fails due to a permissions error, it raises an exception. # An uncaught exception breaks the DB transa...
Returns a wrapped function.
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: ...
Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees.
def setup_matchedfltr_dax_generated(workflow, science_segs, datafind_outs, tmplt_banks, output_dir, injection_file=None, tags=None, link_to_tmpltbank=False, compatibility_mode=...
Setup matched-filter jobs that are generated as part of the workflow. This module can support any matched-filter code that is similar in principle to lalapps_inspiral, but for new codes some additions are needed to define Executable and Job sub-classes (see jobutils.py). Parameters ----------- ...
def calculate_statistics(self, start, stop): """Starts the statistics calculation. :param start: The left limit of the time window in percent. :param stop: The right limit of the time window in percent. .. note:: The calculation takes some time. Check the status byte to se...
Starts the statistics calculation. :param start: The left limit of the time window in percent. :param stop: The right limit of the time window in percent. .. note:: The calculation takes some time. Check the status byte to see when the operation is done. A running scan...
def get_console_info(kernel32, handle): """Get information about this current console window (Windows only). https://github.com/Robpol86/colorclass/blob/ab42da59/colorclass/windows.py#L111 :raise OSError: When handle is invalid or GetConsoleScreenBufferInfo API call fails. :param ctypes.windll.kernel...
Get information about this current console window (Windows only). https://github.com/Robpol86/colorclass/blob/ab42da59/colorclass/windows.py#L111 :raise OSError: When handle is invalid or GetConsoleScreenBufferInfo API call fails. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :par...
def dns_name(self): """Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found. """ for scope in ['public', 'local-cloud']: addresses = self.safe_data['addresses'] or []...
Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found.
def content_upload(self, key, model, contentid, data, mimetype): """Store the given data as a result of a query for content id given the model. This method maps to https://github.com/exosite/docs/tree/master/provision#post---upload-content Args: key: The CIK or Token for th...
Store the given data as a result of a query for content id given the model. This method maps to https://github.com/exosite/docs/tree/master/provision#post---upload-content Args: key: The CIK or Token for the device model: contentid: The ID used to name the e...
def get_window_by_caption(caption): """ finds the window by caption and returns handle (int) """ try: hwnd = win32gui.FindWindow(None, caption) return hwnd except Exception as ex: print('error calling win32gui.FindWindow ' + str(ex)) return -1
finds the window by caption and returns handle (int)
def _virial(self, T): """Virial coefficient Parameters ---------- T : float Temperature [K] Returns ------- prop : dict Dictionary with residual adimensional helmholtz energy: * B: ∂fir/∂δ|δ->0 * C: ∂²fir/∂...
Virial coefficient Parameters ---------- T : float Temperature [K] Returns ------- prop : dict Dictionary with residual adimensional helmholtz energy: * B: ∂fir/∂δ|δ->0 * C: ∂²fir/∂δ²|δ->0
def get_quant_NAs(quantdata, quantheader): """Takes quantdata in a dict and header with quantkeys (eg iTRAQ isotopes). Returns dict of quant intensities with missing keys set to NA.""" out = {} for qkey in quantheader: out[qkey] = quantdata.get(qkey, 'NA') return out
Takes quantdata in a dict and header with quantkeys (eg iTRAQ isotopes). Returns dict of quant intensities with missing keys set to NA.
def evict(self, key): """ Evicts the specified key from this map. **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), key to evict. :retu...
Evicts the specified key from this map. **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), key to evict. :return: (bool), ``true`` if the key is evicted...
def method_delegate(**methods): """ Construct a renderer that delegates based on the request's HTTP method. """ methods = {k.upper(): v for k, v in iteritems(methods)} if PY3: methods = {k.encode("utf-8"): v for k, v in iteritems(methods)} def render(request): renderer = meth...
Construct a renderer that delegates based on the request's HTTP method.
def foreign_key(model_or_table_name_or_column_name: Union[str, Type[Model]], model_or_table_name: Optional[Union[str, Type[Model]]] = None, *, fk_col: str = 'id', primary_key: bool = False, **kwargs, ) -> Column: """Help...
Helper method to add a foreign key column to a model. For example:: class Post(Model): category_id = foreign_key('Category') category = relationship('Category', back_populates='posts') Is equivalent to:: class Post(Model): category_id = Column(BigInteger, ...
def new_code_cell(input=None, prompt_number=None, outputs=None, language=u'python', collapsed=False, metadata=None): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = u'code' if language is not None: cell.language = unicode(language) if input is no...
Create a new code cell with input and output
def archive_insert_data(self, data_dump): ''' :param data: Archive table data :type data: list[archive] :raises: IOError ''' with self.session as session: try: data = [self.tables.archive(**entry) for entry in data_dump] sessio...
:param data: Archive table data :type data: list[archive] :raises: IOError
def remove_log_action(portal): """Removes the old Log action from types """ logger.info("Removing Log Tab ...") portal_types = api.get_tool("portal_types") for name in portal_types.listContentTypes(): ti = portal_types[name] actions = map(lambda action: action.id, ti._actions) ...
Removes the old Log action from types
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict
Return a json dictionary representing this model.
def _matrix_input_from_dict2d(matrix): """makes input for running clearcut on a matrix from a dict2D object""" #clearcut truncates names to 10 char- need to rename before and #reassign after #make a dict of env_index:full name int_keys = dict([('env_' + str(i), k) for i,k in \ enumerate...
makes input for running clearcut on a matrix from a dict2D object
def add_data_field(self, name, i1, i2, subfields_dict): """ Add new datafield into :attr:`datafields` and take care of OAI MARC differencies. Args: name (str): Name of datafield. i1 (char): Value of i1/ind1 parameter. i2 (char): Value of i2/ind2 param...
Add new datafield into :attr:`datafields` and take care of OAI MARC differencies. Args: name (str): Name of datafield. i1 (char): Value of i1/ind1 parameter. i2 (char): Value of i2/ind2 parameter. subfields_dict (dict): Dictionary containing subfields (as...
def commits(self, branch, since=0, to=int(time.time()) + 86400): """For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maxima...
For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maximal timestamp for commit's commit date :type to: int
def get_absolute_url(self): """Return a path""" from django.urls import NoReverseMatch if self.alternate_url: return self.alternate_url try: prefix = reverse('categories_tree_list') except NoReverseMatch: prefix = '/' ancestors = list(...
Return a path