positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def incremental_fit(self, train_x, train_y): """ Incrementally fit the regressor. """ if not self._first_fitted: raise ValueError("The first_fit function needs to be called first.") train_x, train_y = np.array(train_x), np.array(train_y) # Incrementally compute K up...
Incrementally fit the regressor.
def add_post(self, *args, **kwargs): """ Shortcut for add_route with method POST """ return self.add_route(hdrs.METH_POST, *args, **kwargs)
Shortcut for add_route with method POST
def disabled(name, **kwargs): ''' Ensure a job is disabled in the schedule name The unique name that is given to the scheduled job. persist Whether the job should persist between minion restarts, defaults to True. ''' ret = {'name': name, 'result': True, ...
Ensure a job is disabled in the schedule name The unique name that is given to the scheduled job. persist Whether the job should persist between minion restarts, defaults to True.
def paginate_stream_index(self, bucket, index, startkey, endkey=None, max_results=1000, return_terms=None, continuation=None, timeout=None, term_regex=None): """ Iterates over a streaming paginated index query. Thi...
Iterates over a streaming paginated index query. This is equivalent to calling :meth:`stream_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke paginatio...
def filter_networks(self, predicate): """ Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include ...
Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include Returns ------- Class1AffinityPredicto...
def make_nb(config, path=None, stop_on_error=True, just_tests=False): """Create a Jupyter notebook sciunit tests for the given configuration.""" root, nb_name = nb_name_from_path(config, path) clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr) name = clean(nb_name) mpl_style = config.get('mis...
Create a Jupyter notebook sciunit tests for the given configuration.
def cli(env, package_keyname, location, preset, verify, billing, complex_type, quantity, extras, order_items): """Place or verify an order. This CLI command is used for placing/verifying an order of the specified package in the given location (denoted by a datacenter's long name). Orders made via t...
Place or verify an order. This CLI command is used for placing/verifying an order of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_order() with the s...
def custom_action(sender, action, instance, user=None, **kwargs): """ Manually trigger a custom action (or even a standard action). """ opts = get_opts(instance) model = '.'.join([opts.app_label, opts.object_name]) dis...
Manually trigger a custom action (or even a standard action).
def _dump_stats(self): ''' Dumps the stats out ''' extras = {} if 'total' in self.stats_dict: self.logger.debug("Compiling total/fail dump stats") for key in self.stats_dict['total']: final = 'total_{t}'.format(t=key) extras...
Dumps the stats out
def get(cls, xuid, scid, clip_id): ''' Gets a specific game clip :param xuid: xuid of an xbox live user :param scid: scid of a clip :param clip_id: id of a clip ''' url = ( 'https://gameclipsmetadata.xboxlive.com/users' '/xuid(%(xuid)s)/sc...
Gets a specific game clip :param xuid: xuid of an xbox live user :param scid: scid of a clip :param clip_id: id of a clip
def currency_pair(code): '''Construct a :class:`ccy_pair` from a six letter string.''' c = str(code) c1 = currency(c[:3]) c2 = currency(c[3:]) return ccy_pair(c1, c2)
Construct a :class:`ccy_pair` from a six letter string.
def devices(self) -> selectiontools.Selection: """The additional devices defined for the respective `reader` or `writer` element contained within a |Selection| object. ToDo If the `reader` or `writer` element does not define its own additional devices, |XMLInterface.devices| of |XMLInte...
The additional devices defined for the respective `reader` or `writer` element contained within a |Selection| object. ToDo If the `reader` or `writer` element does not define its own additional devices, |XMLInterface.devices| of |XMLInterface| is used. >>> from hydpy.core.examples impo...
def std(self, axis): """Returns d-1 dimensional histogram of (estimated) std value along axis NB this is very different from just std of the histogram values (which describe bin counts) """ def weighted_std(values, weights, axis): # Stolen from http://stackoverflow.com/questi...
Returns d-1 dimensional histogram of (estimated) std value along axis NB this is very different from just std of the histogram values (which describe bin counts)
def inputs_outputs(self): """Get information on method inputs & outputs.""" r = fapi.get_inputs_outputs(self.namespace, self.name, self.snapshot_id, self.api_url) fapi._check_response_code(r, 200) return r.json()
Get information on method inputs & outputs.
def open(self, options=None, mimetype='application/octet-stream'): """ open: return a file like object for self. The method can be used with the 'with' statment. """ return self.connection.open(self, options, mimetype)
open: return a file like object for self. The method can be used with the 'with' statment.
def path(self): """Return the full path to the Group, including any parent Groups.""" # If root, return '/' if self.dataset is self: return '' else: # Otherwise recurse return self.dataset.path + '/' + self.name
Return the full path to the Group, including any parent Groups.
def mouseMoveEvent(self, event): """Override Qt method. Show code analisis, if left button pressed select lines. """ line_number = self.editor.get_linenumber_from_mouse_event(event) block = self.editor.document().findBlockByNumber(line_number-1) data = block.userData() ...
Override Qt method. Show code analisis, if left button pressed select lines.
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []): """ Generates a set of sliding windows for the specified dataset. """ # Determine the dimensions of the input data width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] # Generate the windows return gene...
Generates a set of sliding windows for the specified dataset.
def setValidityErrorHandler(self, err_func, warn_func, arg=None): """ Register error and warning handlers for RelaxNG validation. These will be called back as f(msg,arg) """ libxml2mod.xmlRelaxNGSetValidErrors(self._o, err_func, warn_func, arg)
Register error and warning handlers for RelaxNG validation. These will be called back as f(msg,arg)
def expunge(self, instance): '''Remove *instance* from the :class:`Session`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an *id* :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session. ''' instance = self.pop(instan...
Remove *instance* from the :class:`Session`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an *id* :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session.
def get_calc_ids(datadir=None): """ Extract the available calculation IDs from the datadir, in order. """ datadir = datadir or get_datadir() if not os.path.exists(datadir): return [] calc_ids = set() for f in os.listdir(datadir): mo = re.match(CALC_REGEX, f) if mo: ...
Extract the available calculation IDs from the datadir, in order.
def query_ssos(self, target_name, lunation_count=None): """Send a query to the SSOS web service, looking for available observations using the given track. :param target_name: name of target to query against SSOIS db :param lunation_count: ignored :rtype: SSOSData """ # ...
Send a query to the SSOS web service, looking for available observations using the given track. :param target_name: name of target to query against SSOIS db :param lunation_count: ignored :rtype: SSOSData
def getServiceJobsToStart(self, maxWait): """ :param float maxWait: Time in seconds to wait to get a job before returning. :return: a tuple of (serviceJobStoreID, memory, cores, disk, ..) representing a service job to start. :rtype: toil.job.ServiceJobNode """ try...
:param float maxWait: Time in seconds to wait to get a job before returning. :return: a tuple of (serviceJobStoreID, memory, cores, disk, ..) representing a service job to start. :rtype: toil.job.ServiceJobNode
def first_unique_char(s): """ :type s: str :rtype: int """ if (len(s) == 1): return 0 ban = [] for i in range(len(s)): if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban: return i else: ban.append(s[i]) return -1
:type s: str :rtype: int
def get_client(self, destination_params, job_id, **kwargs): """Build a client given specific destination parameters and job_id.""" destination_params = _parse_destination_params(destination_params) destination_params.update(**kwargs) job_manager_interface_class = self.job_manager_interfa...
Build a client given specific destination parameters and job_id.
def ls(self, folder="", begin_from_file="", num=-1, get_grants=False, all_grant_data=False): """ gets the list of file names (keys) in a s3 folder Parameters ---------- folder : string Path to file on S3 num: integer, optional number of results ...
gets the list of file names (keys) in a s3 folder Parameters ---------- folder : string Path to file on S3 num: integer, optional number of results to return, by default it returns all results. begin_from_file: string, optional which file t...
def unpack(self, buff=None, offset=0): """Unpack *buff* into this object. This method will convert a binary data into a readable value according to the attribute format. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: ...
Unpack *buff* into this object. This method will convert a binary data into a readable value according to the attribute format. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: I...
def walk(start, ofn, cyc=None): """ Non recursive DFS to detect cycles :param start: start vertex in graph :param ofn: function to get the list of outgoing edges of a vertex :param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex. :return: cycles :rtype...
Non recursive DFS to detect cycles :param start: start vertex in graph :param ofn: function to get the list of outgoing edges of a vertex :param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex. :return: cycles :rtype: list of lists
def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default...
.. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be ...
def czdivide(a, b, null=0): ''' czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide, czdivide works with sparse matrices. Additionally, czdivide multiplies a by t...
czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide, czdivide works with sparse matrices. Additionally, czdivide multiplies a by the zinv of b, so divide-by-zero en...
def splitname(path): """Split a path into a directory, name, and extensions.""" dirpath, filename = os.path.split(path) # we don't use os.path.splitext here because we want all extensions, # not just the last, to be put in exts name, exts = filename.split(os.extsep, 1) return dirpath, name, ext...
Split a path into a directory, name, and extensions.
def reclassify(layer, exposure_key=None, overwrite_input=False): """Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3182 This function is a wrapper for the code from https://github.com/chiatt/gdal_reclassify For instance if you want to reclassify like this t...
Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3182 This function is a wrapper for the code from https://github.com/chiatt/gdal_reclassify For instance if you want to reclassify like this table : Original Value | Class - ∞ < val <=...
def _get_parameter(self, parameter, dest_addr_long=None): """ Fetches and returns the value of the specified parameter. """ frame = self._send_and_wait( command=parameter, dest_addr_long=dest_addr_long) return frame["parameter"]
Fetches and returns the value of the specified parameter.
def result(self, wait=0): """ return the full list of results from the chain when it finishes. blocks until timeout. :param int wait: how many milliseconds to wait for a result :return: an unsorted list of results """ if self.started: return result_group(self....
return the full list of results from the chain when it finishes. blocks until timeout. :param int wait: how many milliseconds to wait for a result :return: an unsorted list of results
def flatten(iterable): """Fully flattens an iterable: In: flatten([1,2,3,4,[5,6,[7,8]]]) Out: [1,2,3,4,5,6,7,8] """ container = iterable.__class__ placeholder = [] for item in iterable: try: placeholder.extend(flatten(item)) except TypeError: placehol...
Fully flattens an iterable: In: flatten([1,2,3,4,[5,6,[7,8]]]) Out: [1,2,3,4,5,6,7,8]
def save(self, conflict_resolver=choose_mine): '''Save all options in memory to the `config_file`. Options are read once more from the file (to allow other writers to save configuration), keys in conflict are resolved, and the final results are written back to the file. :param conflic...
Save all options in memory to the `config_file`. Options are read once more from the file (to allow other writers to save configuration), keys in conflict are resolved, and the final results are written back to the file. :param conflict_resolver: a simple lambda or function to choose when an o...
def add_param(self, name, **kwargs): '''Add a parameter to this group. Parameters ---------- name : str Name of the parameter to add to this group. The name will automatically be case-normalized. Additional keyword arguments will be passed to the `Param`...
Add a parameter to this group. Parameters ---------- name : str Name of the parameter to add to this group. The name will automatically be case-normalized. Additional keyword arguments will be passed to the `Param` constructor.
def glob(self, filename): """Returns a list of files that match the given pattern(s).""" # Only support prefix with * at the end and no ? in the string star_i = filename.find('*') quest_i = filename.find('?') if quest_i >= 0: raise NotImplementedError( ...
Returns a list of files that match the given pattern(s).
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = fil...
Parse out filename from any specified extensions. Returns rootname and string version of extension name.
def _make_callsites(self, stack_pointer_tracker=None): """ Simplify all function call statements. :return: None """ # Computing reaching definitions rd = self.project.analyses.ReachingDefinitions(func=self.function, func_graph=self.graph, observe_all=True) f...
Simplify all function call statements. :return: None
def vector_angle_cos(u, v): ''' vector_angle_cos(u, v) yields the cosine of the angle between the two vectors u and v. If u or v (or both) is a (d x n) matrix of n vectors, the result will be a length n vector of the cosines. ''' u = np.asarray(u) v = np.asarray(v) return (u * v).sum(0) ...
vector_angle_cos(u, v) yields the cosine of the angle between the two vectors u and v. If u or v (or both) is a (d x n) matrix of n vectors, the result will be a length n vector of the cosines.
def error(self, amplexception): """ Receives notification of an error. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Error:\n{:s}'.format(msg)) raise amplexception
Receives notification of an error.
def make_chars_uppercase( lst: Union[list, tuple, str, set], uppercase: int ) -> Union[list, tuple, str, set]: """Make uppercase some randomly selected characters. The characters can be in a (mix of) string, list, tuple or set. Keyword arguments: lst -- the ...
Make uppercase some randomly selected characters. The characters can be in a (mix of) string, list, tuple or set. Keyword arguments: lst -- the object to make all chars uppercase, which can be a (mix of) list, tuple, string or set. uppercase -- Number of characters to be set as...
def p_SingleType_any(p): """SingleType : any TypeSuffixStartingWithArray""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( model.SimpleType.ANY), p[2])
SingleType : any TypeSuffixStartingWithArray
def get_object(self, request, object_id, from_field=None): """ our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called """ # from_field breaks in 1.7....
our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called
def do_rmfit(self, arg): """Removes a fit function from a variable. See 'fit'.""" if arg in self.curargs["fits"]: del self.curargs["fits"][arg] #We also need to remove the variable entry if it exists. if "timing" in arg: fitvar = "{}|fit".format(arg) ...
Removes a fit function from a variable. See 'fit'.
def alias_log_entry(self, log_entry_id, alias_id): """Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``LogEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to...
Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``LogEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another log entry, it is reassigned to the given log ...
def submit_row(context): """ Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'. Manipulates the context going into that function by hiding all of the buttons in the submit row if the key `readonly` is set in the context. """ ctx = original_submit_row(context) if context...
Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'. Manipulates the context going into that function by hiding all of the buttons in the submit row if the key `readonly` is set in the context.
def indel_at( self, position, check_insertions=True, check_deletions=True, one_based=True ): """Does the read contain an indel at the given position? Return True if the read contains an insertion at the given position (position must be the base before the insertion event) or if the read ...
Does the read contain an indel at the given position? Return True if the read contains an insertion at the given position (position must be the base before the insertion event) or if the read contains a deletion where the base at position is deleted. Return False otherwise.
def get_cats(self): '''Get top keywords categories''' start_url = 'http://top.taobao.com/index.php?from=tbsy' rs = self.fetch(start_url) if not rs: return None soup = BeautifulSoup(rs.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage) ca...
Get top keywords categories
def cmdargs(mysqldump: str, username: str, password: str, database: str, verbose: bool, with_drop_create_database: bool, max_allowed_packet: str, hide_password: bool = False) -> List[str]: """ Returns command arguments for a ``m...
Returns command arguments for a ``mysqldump`` call. Args: mysqldump: ``mysqldump`` executable filename username: user name password: password database: database name verbose: verbose output? with_drop_create_database: produce commands to ``DROP`` the database ...
def _find_all_simple(path): """ Find all files under 'path' """ results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results)
Find all files under 'path'
def process_xml(xml_string): """Return a TripsProcessor by processing a TRIPS EKB XML string. Parameters ---------- xml_string : str A TRIPS extraction knowledge base (EKB) string to be processed. http://trips.ihmc.us/parser/api.html Returns ------- tp : TripsProcessor ...
Return a TripsProcessor by processing a TRIPS EKB XML string. Parameters ---------- xml_string : str A TRIPS extraction knowledge base (EKB) string to be processed. http://trips.ihmc.us/parser/api.html Returns ------- tp : TripsProcessor A TripsProcessor containing the ...
def string_to_bytes(string, size): """Convert string to bytes add padding.""" if len(string) > size: raise PyVLXException("string_to_bytes::string_to_large") encoded = bytes(string, encoding='utf-8') return encoded + bytes(size-len(encoded))
Convert string to bytes add padding.
def resnet_model_fn(features, labels, mode, model_class, resnet_size, weight_decay, learning_rate_fn, momentum, data_format, version, loss_scale, loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE, label_smoothing=0.0, enable_lars=False)...
Shared functionality for different resnet model_fns. Initializes the ResnetModel representing the model layers and uses that model to build the necessary EstimatorSpecs for the `mode` in question. For training, this means building losses, the optimizer, and the train op that get passed into the EstimatorSpec. ...
def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an import error """ ...
Creates a RemoteServiceAdminEvent object from an import error
def dup_finder(file_path, directory=".", enable_scandir=False): """ Check a directory for duplicates of the specified file. This is meant for a single file only, for checking a directory for dups, use directory_duplicates. This is designed to be as fast as possible by doing lighter checks befor...
Check a directory for duplicates of the specified file. This is meant for a single file only, for checking a directory for dups, use directory_duplicates. This is designed to be as fast as possible by doing lighter checks before progressing to more extensive ones, in order they are: 1. File si...
def aggregate(raster, ndv, block_size): ''' Aggregate raster to smaller resolution, by adding cells. Usage: aggregate(raster, ndv, block_size) where: raster is a Numpy array created by importing the raster (e.g. geotiff) ndv is the NoData Value for the raster (can b...
Aggregate raster to smaller resolution, by adding cells. Usage: aggregate(raster, ndv, block_size) where: raster is a Numpy array created by importing the raster (e.g. geotiff) ndv is the NoData Value for the raster (can be read using the get_geo_info function) ...
def check_extract_from_egg(pth, todir=None): r""" Check if path points to a file inside a python egg file, extract the file from the egg to a cache directory (following pkg_resources convention) and return [(extracted path, egg file path, relative path inside egg file)]. Otherwise, just return [...
r""" Check if path points to a file inside a python egg file, extract the file from the egg to a cache directory (following pkg_resources convention) and return [(extracted path, egg file path, relative path inside egg file)]. Otherwise, just return [(original path, None, None)]. If path points ...
def hist_3d_index(x, y, z, shape): """ Fast 3d histogram of 3D indices with C++ inner loop optimization. Is more than 2 orders faster than np.histogramdd(). The indices are given in x, y, z coordinates and have to fit into a histogram of the dimensions shape. Parameters ---------- x : array ...
Fast 3d histogram of 3D indices with C++ inner loop optimization. Is more than 2 orders faster than np.histogramdd(). The indices are given in x, y, z coordinates and have to fit into a histogram of the dimensions shape. Parameters ---------- x : array like y : array like z : array like ...
def setComplete(self, basepath): """Set complete flag for this comic, ie. all comics are downloaded.""" if self.endOfLife: filename = self.getCompleteFile(basepath) if not os.path.exists(filename): with open(filename, 'w') as f: f.write('All co...
Set complete flag for this comic, ie. all comics are downloaded.
def fetch(self): """ Fetch & return a new `Image` object representing the image's current state :rtype: Image :raises DOAPIError: if the API endpoint replies with an error (e.g., if the image no longer exists) """ api = self.doapi_manager retu...
Fetch & return a new `Image` object representing the image's current state :rtype: Image :raises DOAPIError: if the API endpoint replies with an error (e.g., if the image no longer exists)
def p0f(pkt): """Passive OS fingerprinting: which OS emitted this TCP packet ? p0f(packet) -> accuracy, [list of guesses] """ db, sig = packet2p0f(pkt) if db: pb = db.get_base() else: pb = [] if not pb: warning("p0f base empty.") return [] #s = len(pb[0][0]) r...
Passive OS fingerprinting: which OS emitted this TCP packet ? p0f(packet) -> accuracy, [list of guesses]
def debug_callback(event, *args, **kwds): '''Example callback, useful for debugging. ''' l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l))
Example callback, useful for debugging.
def save(): """ save function """ results = {} cpu_number = 0 while True: try: _file = open( CPU_PREFIX + 'cpu{}/cpufreq/scaling_governor'.format(cpu_number)) except: break governor = _file.read().strip() results.setdefaul...
save function
def _save_percolator(self): """ Saves the query field as an elasticsearch percolator """ index = Content.search_objects.mapping.index query_filter = self.get_content(published=False).to_dict() q = {} if "query" in query_filter: q = {"query": query_fi...
Saves the query field as an elasticsearch percolator
def create(self): """ Create the subqueue to change the default behavior of Lock to semaphore. """ self.queue = self.scheduler.queue.addSubQueue(self.priority, LockEvent.createMatcher(self.context, self.key), maxdefault = self.size, defaultQueueCl...
Create the subqueue to change the default behavior of Lock to semaphore.
def tostr(self): """Export SVG as a string""" element = _transform.SVGFigure(self.width, self.height) element.append(self) svgstr = element.to_str() return svgstr
Export SVG as a string
def load_bytecode_definitions(*, path=None) -> dict: """Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions. """ if path is not None: ...
Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions.
def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ...
Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): r"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a DSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with a...
r"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a DSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based...
def core_profile_check(self) -> None: ''' Core profile check. FOR DEBUG PURPOSES ONLY ''' profile_mask = self.info['GL_CONTEXT_PROFILE_MASK'] if profile_mask != 1: warnings.warn('The window should request a CORE OpenGL profile') version_code...
Core profile check. FOR DEBUG PURPOSES ONLY
def _from_specs(self, dims, spacing=(1.0,1.0,1.0), origin=(0.0, 0.0, 0.0)): """ Create VTK image data directly from numpy arrays. A uniform grid is defined by the node spacings for each axis (uniform along each individual axis) and the number of nodes on each axis. These are rela...
Create VTK image data directly from numpy arrays. A uniform grid is defined by the node spacings for each axis (uniform along each individual axis) and the number of nodes on each axis. These are relative to a specified origin (default is ``(0.0, 0.0, 0.0)``). Parameters -------...
def data_complete(self): """ Return True if all the expected datadir files are present """ return task.data_complete(self.datadir, self.sitedir, self._get_container_name)
Return True if all the expected datadir files are present
def extract_formats(config_handle): """Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``. """ configurations...
Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``.
def get_center(self, element): """Get center coordinates of an element :param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value) :returns: dict with center coordinates """ web_element = self.get_web_element(element) loca...
Get center coordinates of an element :param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value) :returns: dict with center coordinates
def addImagingColumns(msname, ack=True): """ Add the columns to an MS needed for the casa imager. It adds the columns MODEL_DATA, CORRECTED_DATA, and IMAGING_WEIGHT. It also sets the CHANNEL_SELECTION keyword needed for the older casa imagers. A column is not added if already existing. """ ...
Add the columns to an MS needed for the casa imager. It adds the columns MODEL_DATA, CORRECTED_DATA, and IMAGING_WEIGHT. It also sets the CHANNEL_SELECTION keyword needed for the older casa imagers. A column is not added if already existing.
def add_mag_drifts(inst): """Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*'...
Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*', ...
def _words_at_the_beginning(word, tree, prefix=""): ''' We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations. ''' l = [] if "" in tree: l.append([prefix, tree[""]]) ...
We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations.
def help_center_categories_list(self, locale=None, sort_by=None, sort_order=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/categories#list-categories" api_path = "/api/v2/help_center/categories.json" if locale: api_opt_path = "/api/v2/help_center/{locale}/c...
https://developer.zendesk.com/rest_api/docs/help_center/categories#list-categories
def set_noise_filter(self, user_gpio, steady, active): """ Sets a noise filter on a GPIO. Level changes on the GPIO are ignored until a level which has been stable for [*steady*] microseconds is detected. Level changes on the GPIO are then reported for [*active*] microse...
Sets a noise filter on a GPIO. Level changes on the GPIO are ignored until a level which has been stable for [*steady*] microseconds is detected. Level changes on the GPIO are then reported for [*active*] microseconds after which the process repeats. user_gpio:= 0-31 ...
def simplify(self, e=None): """ Simplifies `e`. If `e` is None, simplifies the constraints of this state. """ if e is None: return self._solver.simplify() elif isinstance(e, (int, float, bool)): return e elif isinstance(e, claripy.ast.Base)...
Simplifies `e`. If `e` is None, simplifies the constraints of this state.
def time_to_first_byte(self): """ The aggregate time to first byte for all pages. """ ttfb = [] for page in self.pages: if page.time_to_first_byte is not None: ttfb.append(page.time_to_first_byte) return round(mean(ttfb), self.decimal_precision...
The aggregate time to first byte for all pages.
def from_pem(cls, data, password=None): """Creates a key from PKCS#8 formatted data loaded from a PEM file. See the function `import_from_pem` for details. :param data(bytes): The data contained in a PEM file. :param password(bytes): An optional password to unwrap the key. ""...
Creates a key from PKCS#8 formatted data loaded from a PEM file. See the function `import_from_pem` for details. :param data(bytes): The data contained in a PEM file. :param password(bytes): An optional password to unwrap the key.
def _add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers): """ :type request_bytes: bytes :type key: bytes :type iv: bytes :type custom_headers: dict[str, str] :rtype: None """ hashed = hmac.new(key, iv + request_bytes, sha1) hashed_base64 = base64.b64encode(ha...
:type request_bytes: bytes :type key: bytes :type iv: bytes :type custom_headers: dict[str, str] :rtype: None
def list_env(saltenv='base'): ''' Return all of the file paths found in an environment ''' ret = {} if saltenv not in __opts__['pillar_roots']: return ret for f_root in __opts__['pillar_roots'][saltenv]: ret[f_root] = {} for root, dirs, files in salt.utils.path.os_walk(f_...
Return all of the file paths found in an environment
def get_valid_location(location): """Check if the given location represents a valid cellular component.""" # If we're given None, return None if location is not None and cellular_components.get(location) is None: loc = cellular_components_reverse.get(location) if loc is None: rai...
Check if the given location represents a valid cellular component.
def parse_state_machine_path(path): """Parser for argparse checking pfor a proper state machine path :param str path: Input path from the user :return: The path :raises argparse.ArgumentTypeError: if the path does not contain a statemachine.json file """ sm_root_file = join(path, storage.STATEM...
Parser for argparse checking pfor a proper state machine path :param str path: Input path from the user :return: The path :raises argparse.ArgumentTypeError: if the path does not contain a statemachine.json file
def is_module_or_package(path): """Return True if path is a Python module/package""" is_module = osp.isfile(path) and osp.splitext(path)[1] in ('.py', '.pyw') is_package = osp.isdir(path) and osp.isfile(osp.join(path, '__init__.py')) return is_module or is_package
Return True if path is a Python module/package
def GetSortedEvents(self, time_range=None): """Retrieves the events in increasing chronological order. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Yield: EventObject: event. """ filter_expression = None if time_...
Retrieves the events in increasing chronological order. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Yield: EventObject: event.
def browser_authorize(self): """ Open a browser to the authorization url and spool up a CherryPy server to accept the response """ url = self.authorize_url() # Open the web browser in a new thread for command-line browser support threading.Timer(1, webbrowser.open...
Open a browser to the authorization url and spool up a CherryPy server to accept the response
def run(data): """HLA typing with OptiType, parsing output from called genotype files. """ hlas = [] for hla_fq in tz.get_in(["hla", "fastq"], data, []): hla_type = re.search("[.-](?P<hlatype>HLA-[\w-]+).fq", hla_fq).group("hlatype") if hla_type in SUPPORTED_HLAS: if utils.fi...
HLA typing with OptiType, parsing output from called genotype files.
def bulk_overwrite(self, entities_and_kinds): """ Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) p...
Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-...
def signal_handler_mapping(self): """A dict mapping (signal number) -> (a method handling the signal).""" # Could use an enum here, but we never end up doing any matching on the specific signal value, # instead just iterating over the registered signals to set handlers, so a dict is probably # better. ...
A dict mapping (signal number) -> (a method handling the signal).
def _get_geom_type(type_bytes): """Get the GeoJSON geometry type label from a WKB type byte string. :param type_bytes: 4 byte string in big endian byte order containing a WKB type number. It may also contain a "has SRID" flag in the high byte (the first type, since this is big endian by...
Get the GeoJSON geometry type label from a WKB type byte string. :param type_bytes: 4 byte string in big endian byte order containing a WKB type number. It may also contain a "has SRID" flag in the high byte (the first type, since this is big endian byte order), indicated as 0x20. If the SR...
def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): ...
Closes the event streaming.
def version_tuple(self): """tuple[int]: version tuple or None if version is not set or invalid.""" try: return tuple([int(digit, 10) for digit in self.version.split('.')]) except (AttributeError, TypeError, ValueError): return None
tuple[int]: version tuple or None if version is not set or invalid.
def remove_child(self, index): """ Removes child at given index from the Node children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) ...
Removes child at given index from the Node children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.remove_child(1) True ...
def fit(self, Xs=None, ys=None, Xt=None, yt=None): """Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt) Parameters ---------- Xs : array-like, shape (n_source_samples, n_features) The training input samples. ys : array-like,...
Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt) Parameters ---------- Xs : array-like, shape (n_source_samples, n_features) The training input samples. ys : array-like, shape (n_source_samples,) The class labels ...
def sync_proxy(self, mri, block): """Abstract method telling the ClientComms to sync this proxy Block with its remote counterpart. Should wait until it is connected Args: mri (str): The mri for the remote block block (BlockModel): The local proxy Block to keep in sync ...
Abstract method telling the ClientComms to sync this proxy Block with its remote counterpart. Should wait until it is connected Args: mri (str): The mri for the remote block block (BlockModel): The local proxy Block to keep in sync