Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,600
def offset(img, offset, fill_value=0): sh = img.shape if sh == (0, 0): return img else: x = np.empty(sh) x[:] = fill_value x[max(offset[0], 0):min(sh[0]+offset[0], sh[0]), max(offset[1], 0):min(sh[1]+offset[1], sh[1])] = \ img[max(-offset[0], 0):mi...
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...
370,601
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None): kb = host_data.get("KnowledgeBase") if os_name is None: os_name = kb.os if cpe is None: pass if labels is None: ...
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...
370,602
def get_platform_node_selector(self, platform): nodeselector = {} if platform: nodeselector_str = self._get_value("node_selector." + platform, self.conf_section, "node_selector." + platform) nodeselector = self.generate_node...
search the configuration for entries of the form node_selector.platform :param platform: str, platform to search for, can be null :return dict
370,603
def host_to_ips(host): ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ...
Returns a list of IP addresses of a given hostname or None if not found.
370,604
def get_idxs(data, eid2idx): uniq, inv = numpy.unique(data[], return_inverse=True) idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv] return idxs
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
370,605
def init_config(self, config): self.config.update(config) self.config.setdefault(, 389) self.config.setdefault(, None) self.config.setdefault(, False) self.config.setdefault(, True) self.config.setdefault(, True) self.config.setdefault(, False) ...
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
370,606
def search(cls, query, search_opts=None): if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection() try: search_result = xmlrpc.connection.search_tag( { : query, : search_opts, ...
Search tags. For more information, see the backend function :py:func:`nipap.backend.Nipap.search_tag`.
370,607
def delete(self): self._ensure_filename() self._close_if_open() os.remove(self.filename)
Removes .sqlite file. **CAREFUL** needless say
370,608
def units2pint(value): def _transform(s): return re.subn(r, r, s)[0] if isinstance(value, str): unit = value elif isinstance(value, xr.DataArray): unit = value.attrs[] elif isinstance(value, units.Quantity): return value.units else: raise NotIm...
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.
370,609
def delete_endpoint_config(self, endpoint_config_name): LOGGER.info(.format(endpoint_config_name)) self.sagemaker_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name)
Delete an Amazon SageMaker endpoint configuration. Args: endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete.
370,610
def _ns_var( py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS ) -> ast.Assign: return ast.Assign( targets=[ast.Name(id=py_ns_var, ctx=ast.Store())], value=ast.Call( func=_FIND_VAR_FN_NAME, args=[ ast.Call( ...
Assign a Python variable named `ns_var` to the value of the current namespace.
370,611
def find_le(self, dt): i = bisect_right(self.dates, dt) if i: return i-1 raise LeftOutOfBound
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.
370,612
def _api_all(self): response.content_type = if self.args.debug: fname = os.path.join(tempfile.gettempdir(), ) try: with open(fname) as f: return f.read() except IOError: logger.debug("Debug file (%s) not f...
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
370,613
def get_current_context_id(): global get_current_context_id if greenlet is not None: if stackless is None: get_current_context_id = greenlet.getcurrent return greenlet.getcurrent() return greenlet.getcurrent(), stackless.getcurrent() elif stackless is not None: ...
Identifis which context it is (greenlet, stackless, or thread). :returns: the identifier of the current context.
370,614
def children(self): 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(): for config in configs: for mod...
Retrieve tags associated to the current node
370,615
def blocking(self): return self.execute( sql.BLOCKING.format( query_column=self.query_column, pid_column=self.pid_column ) )
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
370,616
def delete_database(self, instance_id, database_id, project_id=None): instance = self._get_client(project_id=project_id).\ instance(instance_id=instance_id) if not instance.exists(): raise AirflowException("The instance {} does not exist in project {} !". ...
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...
370,617
def from_api_repr(cls, api_repr): api_repr = api_repr.strip() if not api_repr: raise ValueError("Field path API representation cannot be empty.") return cls(*parse_field_path(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`) An instance parsed from ``api_repr``. ...
370,618
def commit_new_version(version: str): check_repo() commit_message = config.get(, ) message = .format(version, commit_message) repo.git.add(config.get(, ).split()[0]) return repo.git.commit(m=message, author="semantic-release <semantic-release>")
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.
370,619
def _init_from_csr(self, csr): if len(csr.indices) != len(csr.data): raise ValueError(.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFromCSR(c_array(ctypes.c_ulong, csr.indptr), ...
Initialize data from a CSR matrix.
370,620
def try_disk(self, path, gpg=True): if not os.path.isfile(path): return if not gpg or self.validate_gpg_sig(path): stream = open(path, ) json_stream = stream.read() if len(json_stream): try: json_config = json....
Try to load json off disk
370,621
def keys(self): return_value = [] for s in self.serializers: return_value += s.content_type return return_value
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.
370,622
def package(self): tmp_path = os.path.join(self.app_path, self.args.outdir, ) if not os.path.isdir(tmp_path): os.makedirs(tmp_path) template_app_path = os.path.join(tmp_path, ) if os.access(template_app_path, os.W_OK): shut...
Build the App package for deployment to ThreatConnect Exchange.
370,623
def _compute_confidence_bounds_of_transform(self, transform, alpha, ci_labels): alpha2 = 1 - alpha / 2.0 z = inv_normal_cdf(alpha2) df = pd.DataFrame(index=self.timeline) gradient_of_cum_hazard_at_mle = make_jvp_reversemode(transform)( self._fitted_paramete...
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...
370,624
def _is_device_active(device): cmd = [, , device] dmsetup_info = util.subp(cmd) for dm_line in dmsetup_info.stdout.split("\n"): line = dm_line.split() if ( in line[0].strip()) and ( in line[1].strip()): return True return False
Checks dmsetup to see if a device is already active
370,625
def success_response(self, method_resp, **kw): resp = { : True, : config.is_indexing(self.working_dir), : virtualchain_hooks.get_last_block(self.working_dir), } resp.update(kw) resp.update(method_resp) if self.is_stale(): ...
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.
370,626
def decode(): logger = logging.getLogger() stdin = click.get_binary_stream() sink = click.get_text_stream() try: pbf = stdin.read() data = geobuf.decode(pbf) json.dump(data, sink) sys.exit(0) except Exception: logger.exception("Failed. Exception caught") ...
Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.
370,627
def linkRecord(self, existing_domain, new_domain, rtype, callback=None, errback=None, **kwargs): if not in existing_domain: existing_domain = existing_domain + + self.zone record = Record(self, new_domain, rtype) return record.create(answers=[], ...
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. :...
370,628
def pull(directory: str) -> Commit: if not os.path.exists(directory): raise ValueError(f"No subrepo found in \"{directory}\"") try: result = run([GIT_COMMAND, _GIT_SUBREPO_COMMAND, _GIT_SUBREPO_PULL_COMMAND, _GIT_SUBREPO_VERBOSE_FLAG, get_directory_relative_to_git_root...
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
370,629
def _populate_cmd_lists(self): self.commands = {} self.aliases = {} self.category = {} for cmd_instance in self.cmd_instances: if not hasattr(cmd_instance, ): continue alias_names = cmd_instance.aliases cmd_name = cmd_instance.name ...
Populate self.lists and hashes: self.commands, and self.aliases, self.category
370,630
def _put(self, route, data, headers=None, failure_message=None): headers = self._get_headers(headers) response_lambda = ( lambda: requests.put( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) ...
Execute a put request and return the result :param data: :param headers: :return:
370,631
def send_topic_message(self, topic_name, message=None): _validate_not_none(, topic_name) _validate_not_none(, message) request = HTTPRequest() request.method = request.host = self._get_host() request.path = + _str(topic_name) + request.headers = messag...
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...
370,632
def add_title_widget(self, ref, text="Title"): 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
370,633
def add_why(voevent, importance=None, expires=None, inferences=None): if not voevent.xpath(): etree.SubElement(voevent, ) if importance is not None: voevent.Why.attrib[] = str(importance) if expires is not None: voevent.Why.attrib[] = expires.replace( microsecond=0)....
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...
370,634
def options(self, parser, env): Plugin.options(self, parser, env) parser.add_option( , action=, dest=, metavar="FILE", default=env.get(, ), help="Path to html file to store the report in. " "Default is nosetests.html in the workin...
Sets additional command line options.
370,635
def export_coreml(self, path, image_shape=(256, 256), include_flexible_shape=True): import mxnet as _mx from .._mxnet._mxnet_to_coreml import _mxnet_converter import coremltools transformer = self._model index = _mx.sym.Variable("index", shape=(1,), dtype=_np.i...
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...
370,636
def attrgetter_atom_handle(loc, tokens): name, args = attrgetter_atom_split(tokens) if args is None: return + name + elif "." in name: raise CoconutDeferredSyntaxError("cannot have attribute access in implicit methodcaller partial", loc) elif args == "": return + tokens[0...
Process attrgetter literals.
370,637
def get_binary_stream(name): opener = binary_streams.get(name) if opener is None: raise TypeError( % name) return opener()
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 ...
370,638
def set_vm_status(self, device=, boot_option=, write_protect=): return self._call_method(, device, boot_option, write_protect)
Sets the Virtual Media drive status and allows the boot options for booting from the virtual media.
370,639
def execCmdThruIUCV(rh, userid, strCmd, hideInLog=[]): if len(hideInLog) == 0: rh.printSysLog("Enter vmUtils.execCmdThruIUCV, userid: " + userid + " cmd: " + strCmd) else: logCmd = strCmd.split() for i in hideInLog: logCmd[i] = rh.printSys...
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...
370,640
def extract_labels(self) -> np.ndarray: condition_idxs, epoch_idxs, _ = np.where(self) _, unique_epoch_idxs = np.unique(epoch_idxs, return_index=True) return condition_idxs[unique_epoch_idxs]
Extract condition labels. Returns ------- np.ndarray The condition label of each epoch.
370,641
def stub(base_class=None, **attributes): if base_class is None: base_class = object members = { "__init__": lambda self: None, "__new__": lambda *args, **kw: object.__new__( *args, *kw ), "__metaclass__": None, } members.update(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.
370,642
def _log_start_transaction(self, endpoint, data, json, files, params): self._requests_counter += 1 if not self._is_logging: return msg = "\n---- %d --------------------------------------------------------\n" % self._requests_counter msg += "[%s] %s\n" % (time.s...
Log the beginning of an API request.
370,643
def factory_profiles(self): with self._mutex: if not self._factory_profiles: self._factory_profiles = [] for fp in self._obj.get_factory_profiles(): self._factory_profiles.append(utils.nvlist_to_dict(fp.properties)) return self._fa...
The factory profiles of all loaded modules.
370,644
def get_cov_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper, lambda1=None, lambda2=None, quadparam1=None, quadparam2=None): mus = get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper, lambda1=lambda1, lambda2=lambda2,...
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. ...
370,645
def user(self, id, expand=None): user = User(self._options, self._session) params = {} if expand is not None: params[] = expand user.find(id, params=params) return user
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
370,646
def Debugger_setBlackboxedRanges(self, scriptId, positions): assert isinstance(positions, (list, tuple) ), "Argument must be of type listtuple. Received type: " % type( positions) subdom_funcs = self.synchronous_command(, scriptId=scriptId, positions=positions) return subdom_funcs
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...
370,647
def node_save(self, astr_pathInTree, **kwargs): str_pathDiskRoot = str_pathDiskOrig = os.getcwd() srt_pathDiskFull = str_pathTree = str_pathTreeOrig = self.pwd() b_failOnDirExist = True b_saveJSON ...
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...
370,648
def emit(self, signalName, *args, **kwargs): assert signalName in self, "%s is not a registered signal" % signalName self[signalName].emit(*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
370,649
def get_label(self, name): assert isinstance(name, (str, unicode)), name headers, data = self._requester.requestJsonAndCheck( "GET", self.url + "/labels/" + urllib.quote(name) ) return github.Label.Label(self._requester, headers, data, completed=True)
:calls: `GET /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param name: string :rtype: :class:`github.Label.Label`
370,650
def read_igor_marginals_txt(marginals_file_name , dim_names=False): with open(marginals_file_name,) as file: model_dict = {} dimension_names_dict = {} element_name="" first = True first_dim_line = False element_marginal_array = [] indices_array =...
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...
370,651
def load_local_config(filename): if not filename: return imp.new_module() module = imp.load_source(, filename) return module
Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module.
370,652
def generator(self, Xgen, Xexc, Xgov, Vgen): generators = self.dyn_generators omegas = 2 * pi * self.freq F = zeros(Xgen.shape) typ1 = [g._i for g in generators if g.model == CLASSICAL] typ2 = [g._i for g in generators if g.model == FOURTH_ORDER] omeg...
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.
370,653
def argument_parser(args): parser = argparse.ArgumentParser( prog="nagaram", description="Finds Scabble anagrams.", formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False, ) parser.add_argument( "-h", "--help", dest="help", action=...
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...
370,654
def _insert_file(cursor, file, media_type): resource_hash = _get_file_sha1(file) cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resource_hash,)) try: fileid = cursor.fetchone()[0] except (IndexError, TypeError): cursor.execute("INSERT INTO files (file...
Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file.
370,655
def job_listener(event): 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() else: error_object =...
Listens to completed job
370,656
def install(name=None, sources=None, saltenv=, **kwargs): <package>old<old-version>new<new-version>*[{"<pkg name>": "/dir/on/minion/<pkg filename>"}]*[{"SMClgcc346": "/var/spool/pkg/gcc-3.4.6-sol10-sparc-local.pkg"}]*[{"<pkg name>": "salt://pkgs/<pkg filename>"}]*[{"SMClgcc346": "salt://pkgs/gcc-3.4.6-sol10-sparc-l...
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': '...
370,657
def run(*awaitables, timeout: float = None): loop = asyncio.get_event_loop() if not awaitables: if loop.is_running(): return loop.run_forever() f = asyncio.gather(*asyncio.Task.all_tasks()) f.cancel() result = None try: loop.run_until_...
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 ...
370,658
def set_dut_configuration(self, ident, config): if hasattr(config, "get_requirements"): self._dut_requirements[ident] = config elif isinstance(config, dict): self._dut_requirements[ident] = ResourceRequirements(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. :return: Nothing
370,659
def _read_datasets(self, dataset_nodes, **kwargs): reader_datasets = {} for node in dataset_nodes: ds_id = node.name raise RuntimeError("Dependency tree has a corrupt node.") reader_datasets.setdefault(reader_name, set(...
Read the given datasets from file.
370,660
def unzip(from_file, to_folder): with ZipFile(os.path.abspath(from_file), ) as to_unzip: to_unzip.extractall(os.path.abspath(to_folder))
Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`.
370,661
def map_reduce(self, map, reduce, out, full_response=False, **kwargs): if not isinstance(out, (string_type, collections.Mapping)): raise TypeError(" must be an instance of " "%s or a mapping" % (string_type.__name__,)) cmd = SON([("mapreduce", self.__nam...
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...
370,662
def echo(root_resource, message): params = dict(message=message) return root_resource.get(ECHO_PATH, params)
Have the server echo our message back.
370,663
def parse_file_provider(uri): providers = {: job_model.P_GCS, : job_model.P_LOCAL} provider_found = re.match(r, uri) if provider_found: prefix = provider_found.group(1).lower() else: prefix = if prefix in providers: return providers[prefix] ...
Find the file provider for a URI.
370,664
def _single_array_element(data_obj, xj_path, array_path, create_dict_path): val_type, array_path = _clean_key_type(array_path) array_idx = _get_array_index(array_path) if data_obj and isinstance(data_obj, (list, tuple)): try: value = data_obj[array_idx] if val_type is n...
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.
370,665
def _get_anon_bind(self): r = self._search( , , [], scope=ldap.SCOPE_BASE ) dn, attrs = r[0] state = attrs.get()[0].decode(, ) if state in [, , ]: r = state else: r = None self._anon_...
Check anonymous bind :return: 'on', 'off', 'rootdse' or None
370,666
def search(query, tld=, lang=, num=10, start=0, stop=None, pause=2.0, only_standard=False): global BeautifulSoup if BeautifulSoup is None: try: from bs4 import BeautifulSoup except ImportError: from BeautifulSoup import BeautifulSoup ...
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...
370,667
def get_last_traded_dt(self, asset, dt): sid_ix = self.sids.searchsorted(asset.sid) dt_limit_ix = self.dates.searchsorted(dt.asm8, side=) nonzero_volume_ixs = np.ravel( np.nonzero(self._country_group[DATA][VOLUME][sid_ix, :dt_limit_ix]) ) ...
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...
370,668
def list_container_instance_groups(access_token, subscription_id, resource_group): endpoint = .join([get_rm_endpoint(), , subscription_id, , resource_group, , , CONTAINER_API]) return do_get(endpoint, access_tok...
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...
370,669
def pipeline(pipe=None, name=None, autoexec=False, exit_handler=None): if pipe is None: return Pipeline(name=name, autoexec=autoexec, exit_handler=exit_handler) try: if pipe.supports_redpipe_pipeline(): return NestedPipeline( parent=pipe,...
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...
370,670
def lookup(instruction, instructions = None): if instructions is None: instructions = default_instructions if isinstance(instruction, str): return instructions[instruction] elif hasattr(instruction, "__call__"): rev = dict(((v,k) for (k,v) in instructions.items())) retu...
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.
370,671
def _compute_value(power, wg): if power not in wg: p1, p2 = power if p1 == 0: yy = wg[(0, -1)] wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy) else: xx = wg[(-1, 0)] wg[power] = numpy.power(xx, p1 / 2).sum() / len(xx)...
Return the weight corresponding to single power.
370,672
def __precision(y_true, y_pred): y_true = np.copy(y_true) y_pred = np.copy(y_pred) is_nan = np.isnan(y_true) y_true[is_nan] = 0 y_pred[is_nan] = 0 precision = precision_score(y_true, y_pred) return precision
Precision metric tolerant to unlabeled data in y_true, NA values are ignored for the precision calculation
370,673
def resetaA(self,pot=None,type=None): try: delattr(self._orb,) except AttributeError: return False else: return True
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)
370,674
def _add_nic_to_mapping(self, net, dom, nic): dom_name = dom[] idx = dom[].index(nic) name = .format(dom_name, idx) net[][name] = nic[] if dom[][idx][] == dom[]: net[][dom_name] = nic[] name_by_net = .format(dom_name, nic[]) named_nets = sort...
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. *...
370,675
def default_absorbers(Tatm, ozone_file = , verbose = True,): absorber_vmr = {} absorber_vmr[] = 348. / 1E6 absorber_vmr[] = 1650. / 1E9 absorber_vmr[] = 306. / 1E9 absorber_vmr[] = 0.21 absorber_vmr[] = 0. absorber_vmr[] = 0. absorber_vmr[] =...
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...
370,676
def query_cast(value, answers, ignorecase = False): if ignorecase: value = value.lower() for item in answers: for a in item[]: if ignorecase and (value == str(a).lower()): return item[][0] elif value == a: return item[][0] raise ValueError...
A cast function for query Answers should look something like it does in query
370,677
def get_count(cls, date_field=None, start=None, end=None, filters={}): query_basic = cls.__get_query_basic(date_field=date_field, start=start, end=end, filters=filters) query = query_basic....
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 ...
370,678
def async_(fn): @functools.wraps(fn) async def wrapper(*args, **kwargs): return await fn(*args, **kwargs) return wrapper
Wrap the given function into a coroutine function.
370,679
def create_atomic_wrapper(cls, wrapped_func): def _create_atomic_wrapper(*args, **kwargs): with transaction.atomic(): return wrapped_func(*args, **kwargs) return _create_atomic_wrapper
Returns a wrapped function.
370,680
def get_dip(self): if self.dip is None: mesh = self.mesh self.dip, self.strike = mesh.get_mean_inclination_and_azimuth() return self.dip
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.
370,681
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 ----------- ...
370,682
def calculate_statistics(self, start, stop): cmd = , Integer, Integer self._write(cmd, 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 see when the operation is done. A running scan...
370,683
def get_console_info(kernel32, handle): if handle == INVALID_HANDLE_VALUE: raise OSError() lpcsbi = ctypes.create_string_buffer(22) if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi): raise ctypes.WinError() left, top, right, bottom = struct.unpack(, lpcsbi.r...
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...
370,684
def dns_name(self): for scope in [, ]: addresses = self.safe_data[] or [] addresses = [address for address in addresses if address[] == scope] if addresses: return addresses[0][] return None
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.
370,685
def content_upload(self, key, model, contentid, data, mimetype): headers = {"Content-Type": mimetype} path = PROVISION_MANAGE_CONTENT + model + + contentid return self._request(path, key, data, , self._manage_by_cik, headers)
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...
370,686
def get_window_by_caption(caption): try: hwnd = win32gui.FindWindow(None, caption) return hwnd except Exception as ex: print( + str(ex)) return -1
finds the window by caption and returns handle (int)
370,687
def _virial(self, T): Tc = self._constants.get("Tref", self.Tc) tau = Tc/T B = C = 0 delta = 1e-200 nr1 = self._constants.get("nr1", []) d1 = self._constants.get("d1", []) t1 = self._constants.get("t1", []) for n, d, t in zip(nr1, d1, t1...
Virial coefficient Parameters ---------- T : float Temperature [K] Returns ------- prop : dict Dictionary with residual adimensional helmholtz energy: * B: ∂fir/∂δ|δ->0 * C: ∂²fir/∂δ²|δ->0
370,688
def get_quant_NAs(quantdata, quantheader): out = {} for qkey in quantheader: out[qkey] = quantdata.get(qkey, ) 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.
370,689
def evict(self, key): check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._evict_internal(key_data)
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...
370,690
def method_delegate(**methods): 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 = methods.get(request.method) if renderer is None: return Response(code=40...
Construct a renderer that delegates based on the request's HTTP method.
370,691
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 = , primary_key: bool = False, **kwargs, ) -> Column: column...
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, ...
370,692
def new_code_cell(input=None, prompt_number=None, outputs=None, language=u, collapsed=False, metadata=None): cell = NotebookNode() cell.cell_type = u if language is not None: cell.language = unicode(language) if input is not None: cell.input = unicode(input) if prompt_number...
Create a new code cell with input and output
370,693
def archive_insert_data(self, data_dump): with self.session as session: try: data = [self.tables.archive(**entry) for entry in data_dump] session.add_all(data) session.commit() except SQLAlchemyError as exc: sessio...
:param data: Archive table data :type data: list[archive] :raises: IOError
370,694
def remove_log_action(portal): 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) for index, action in enumerate(actions): ...
Removes the old Log action from types
370,695
def _to_dict(self): _dict = {} if hasattr(self, ) and self.pronunciation is not None: _dict[] = self.pronunciation return _dict
Return a json dictionary representing this model.
370,696
def _matrix_input_from_dict2d(matrix): int_keys = dict([( + str(i), k) for i,k in \ enumerate(sorted(matrix.keys()))]) int_map = {} for i in int_keys: int_map[int_keys[i]] = i new_dists = [] for env1 in matrix: for env2 in matrix[env1]...
makes input for running clearcut on a matrix from a dict2D object
370,697
def add_data_field(self, name, i1, i2, subfields_dict): if i1 not in self.valid_i_chars: raise ValueError("Invalid i1 parameter !") if i2 not in self.valid_i_chars: raise ValueError("Invalid i2 parameter !") if len(name) != 3: raise ValueError( ...
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...
370,698
def commits(self, branch, since=0, to=int(time.time()) + 86400): since_str = datetime.datetime.fromtimestamp(since).strftime() to_str = datetime.datetime.fromtimestamp(to).strftime() commits = {} req_message = + self.reponame + \ + branch loop_continue = True while loop_continue: response_d...
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
370,699
def get_absolute_url(self): from django.urls import NoReverseMatch if self.alternate_url: return self.alternate_url try: prefix = reverse() except NoReverseMatch: prefix = ancestors = list(self.get_ancestors()) + [self, ] ret...
Return a path