code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_tags(self, repo_slug=None): """ Get a single repository on Bitbucket and return its tags.""" repo_slug = repo_slug or self.repo_slug or '' url = self.url('GET_TAGS', username=self.username, repo_slug=repo_slug) return self.dispatch('GET', url, auth=self.auth)
Get a single repository on Bitbucket and return its tags.
def attr(self, key): """Returns the attribute string for corresponding input key from the symbol. This function only works for non-grouped symbols. Example ------- >>> data = mx.sym.Variable('data', attr={'mood': 'angry'}) >>> data.attr('mood') 'angry' ...
Returns the attribute string for corresponding input key from the symbol. This function only works for non-grouped symbols. Example ------- >>> data = mx.sym.Variable('data', attr={'mood': 'angry'}) >>> data.attr('mood') 'angry' Parameters ---------- ...
def Length(min=None, max=None, min_message="Must have a length of at least {min}", max_message="Must have a length of at most {max}"): """ Creates a validator that checks if the given value's length is in the specified range, inclusive. (Returns the original value.) See :func:`.Range`. """ vali...
Creates a validator that checks if the given value's length is in the specified range, inclusive. (Returns the original value.) See :func:`.Range`.
def raise_flapping_start_log_entry(self, change_ratio, threshold): """Raise HOST FLAPPING ALERT START entry (critical level) Format is : "HOST FLAPPING ALERT: *self.get_name()*;STARTED; Host appears to have started flapping (*change_ratio*% change >= *threshold*...
Raise HOST FLAPPING ALERT START entry (critical level) Format is : "HOST FLAPPING ALERT: *self.get_name()*;STARTED; Host appears to have started flapping (*change_ratio*% change >= *threshold*% threshold)" Example : "HOST FLAPPING ALERT: server;STARTED; ...
def private_config_path(self): """ :returns: Path of the private config """ return os.path.join(self._working_directory, "configs", "i{}_private-config.cfg".format(self._dynamips_id))
:returns: Path of the private config
def isns_isns_vrf_isns_ipaddress_loopback(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns") isns_vrf = ET.SubElement(isns, "isns-vrf") isns_vrf_instance_key = ET.SubEle...
Auto Generated Code
def add_newlines(f, output, char): """Adds line breaks after every occurance of a given character in a file. Args: f: string, path to input file. output: string, path to output file. Returns: None. """ line_count = get_line_count(f) f = open(f, 'r+') output = open(...
Adds line breaks after every occurance of a given character in a file. Args: f: string, path to input file. output: string, path to output file. Returns: None.
def strain_out_of_plane(self, **kwargs): ''' Returns the out-of-plane strain assuming no lattice relaxation, which is negative for tensile strain and positive for compressive strain. This is the strain measured by X-ray diffraction (XRD) symmetric omega-2theta scans. ''' ...
Returns the out-of-plane strain assuming no lattice relaxation, which is negative for tensile strain and positive for compressive strain. This is the strain measured by X-ray diffraction (XRD) symmetric omega-2theta scans.
def _get_cpu_info_internal(): ''' Returns the CPU info by using the best sources of information for your OS. Returns {} if nothing is found. ''' # Get the CPU arch and bits arch, bits = _parse_arch(DataSource.arch_string_raw) friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unkn...
Returns the CPU info by using the best sources of information for your OS. Returns {} if nothing is found.
def levels(self): """ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` """ ret = [[] for i in range(self.height)] ...
Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree`
def post_url(self, url, token='', json=None, data=None, headers=None): """ Returns a post resquest object taking in a url, user token, and possible json information. Arguments: url (str): The url to make post to token (str): The authentication token j...
Returns a post resquest object taking in a url, user token, and possible json information. Arguments: url (str): The url to make post to token (str): The authentication token json (dict): json info to send Returns: obj: Post request object
def robo_avatar_url(user_data, size=80): """Return the gravatar image for the given email address.""" hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest() url = "https://robohash.org/{hash}.png?size={size}x{size}".format( hash=hash, size=size) return url
Return the gravatar image for the given email address.
def net_connections(self, include_virtual_nodes=False): """ Returns a representation of the current block useful for creating a graph. :param include_virtual_nodes: if enabled, the wire itself will be used to signal an external source or sink (such as the source for an Input net). I...
Returns a representation of the current block useful for creating a graph. :param include_virtual_nodes: if enabled, the wire itself will be used to signal an external source or sink (such as the source for an Input net). If disabled, these nodes will be excluded from the adjacency dictiona...
def best_response_2p(payoff_matrix, opponent_mixed_action, tol=1e-8): """ Numba-optimized version of `Player.best_response` compilied in nopython mode, specialized for 2-player games (where there is only one opponent). Return the best response action (with the smallest index if more than one) t...
Numba-optimized version of `Player.best_response` compilied in nopython mode, specialized for 2-player games (where there is only one opponent). Return the best response action (with the smallest index if more than one) to `opponent_mixed_action` under `payoff_matrix`. Parameters ---------- ...
def set_icon(self, bmp): """Sets main window icon to given wx.Bitmap""" _icon = wx.EmptyIcon() _icon.CopyFromBitmap(bmp) self.SetIcon(_icon)
Sets main window icon to given wx.Bitmap
def activate_hopscotch(driver): """ Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ """ hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style verify_script = ("""// ...
Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/
def PluginAssets(self, plugin_name): """Get index of runs and assets for a given plugin. Args: plugin_name: Name of the plugin we are checking for. Returns: A dictionary that maps from run_name to a list of plugin assets for that run. """ with self._accumulators_mutex: # ...
Get index of runs and assets for a given plugin. Args: plugin_name: Name of the plugin we are checking for. Returns: A dictionary that maps from run_name to a list of plugin assets for that run.
def set_bgcolor(self, color): """set color for background of plot""" self.bgcolor = color for ax in self.canvas.figure.get_axes(): if matplotlib.__version__ < '2.0': ax.set_axis_bgcolor(color) else: ax.set_facecolor(color) if callab...
set color for background of plot
def unescape(self): r"""Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from jinja2.constants import HTML_ENTITIES def handle_ma...
r"""Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>'
def get_division(self, obj): """Division.""" if obj.level.name == DivisionLevel.DISTRICT: return DivisionSerializer(obj.parent).data return DivisionSerializer(obj).data
Division.
def _items(mappingorseq): """Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v """ ...
Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v
def get_override_votes(self, obj): """ Votes entered into backend. Only used if ``override_ap_votes = True``. """ if hasattr(obj, "meta"): # TODO: REVISIT THIS if obj.meta.override_ap_votes: all_votes = None for ce in obj.candidate_ele...
Votes entered into backend. Only used if ``override_ap_votes = True``.
def autocomplete(input_list): """ <Purpose> Returns all valid input completions for the specified command line input. <Arguments> input_list: A list of tokens. <Side Effects> None <Exceptions> None <Returns> A list of strings representing valid completions. """ # We are only inte...
<Purpose> Returns all valid input completions for the specified command line input. <Arguments> input_list: A list of tokens. <Side Effects> None <Exceptions> None <Returns> A list of strings representing valid completions.
def _login(self, user='', password=''): """Do login to zabbix server. :type user: str :param user: Zabbix user :type password: str :param password: Zabbix user password """ logger.debug("ZabbixAPI.login({0},{1})".format(user, password)) self.auth = Non...
Do login to zabbix server. :type user: str :param user: Zabbix user :type password: str :param password: Zabbix user password
def rdotplot(args): """ %prog rdotplotfile Dot plot to visualize relationship between two sequences, by plotting .rdotplot file (often generated by LASTZ) """ p = OptionParser(rdotplot.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ...
%prog rdotplotfile Dot plot to visualize relationship between two sequences, by plotting .rdotplot file (often generated by LASTZ)
def _validate_for_numeric_binop(self, other, op): """ Return valid other; evaluate or raise TypeError if we are not of the appropriate type. Notes ----- This is an internal method called by ops. """ opstr = '__{opname}__'.format(opname=op.__name__) ...
Return valid other; evaluate or raise TypeError if we are not of the appropriate type. Notes ----- This is an internal method called by ops.
def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> None: """ When we add a new expr...
When we add a new expression, there may be other expressions that refer to it, and we need to update those to point to the new expression.
def bucket_keys_to_guarantee_result_set_size(self, bucket_key, N, tree_depth): """ Returns list of bucket keys based on the specified bucket key and minimum result size N. """ if tree_depth == len(bucket_key): #print 'Returning leaf bucket key %s with %d vectors' % (...
Returns list of bucket keys based on the specified bucket key and minimum result size N.
def parse_value_instancewithpath(self, tup_tree): """ The VALUE.INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object. :: <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEP...
The VALUE.INSTANCEWITHPATH is used to define a value that comprises a single CIMInstance with additional information that defines the absolute path to that object. :: <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEPATH, INSTANCE)>
def set_dtype(self, opt, dtype): """Set the `dtype` attribute. If opt['DataType'] has a value other than None, it overrides the `dtype` parameter of this method. No changes are made if the `dtype` attribute already exists and has a value other than 'None'. Parameters ---...
Set the `dtype` attribute. If opt['DataType'] has a value other than None, it overrides the `dtype` parameter of this method. No changes are made if the `dtype` attribute already exists and has a value other than 'None'. Parameters ---------- opt : :class:`cdict.Constrai...
def sha1(filename): """Return SHA1 of filename.""" filename = unmap_file(filename) if filename not in file_cache: cache_file(filename) if filename not in file_cache: return None pass if file_cache[filename].sha1: return file_cache[filename].sha1.hexdigest() ...
Return SHA1 of filename.
def list(gandi, limit, step): """List operations.""" output_keys = ['id', 'type', 'step'] options = { 'step': step, 'items_per_page': limit, 'sort_by': 'date_created DESC' } result = gandi.oper.list(options) for num, oper in enumerate(reversed(result)): if num: ...
List operations.
def filter(self, entries): """Filter a set of declarations: keep only those related to this object. This will keep: - Declarations that 'override' the current ones - Declarations that are parameters to current ones """ return [ entry for entry in entries ...
Filter a set of declarations: keep only those related to this object. This will keep: - Declarations that 'override' the current ones - Declarations that are parameters to current ones
def atomic_copy(src, dst): """Copy the file src to dst, overwriting dst atomically.""" with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst: shutil.copyfile(src, tmp_dst.name) os.chmod(tmp_dst.name, os.stat(src).st_mode) os.rename(tmp_dst.name, dst)
Copy the file src to dst, overwriting dst atomically.
def __output_unpaired_vals(d_vals, used_ff_keys, f_f_header, sf_d, s_f_header, missing_val, out_handler, outfh, delim="\t"): """ Use an output handler to output keys that could not be paired. Go over the keys in d_vals and for any that were not used (i.e. not in used_ff_keys), build ...
Use an output handler to output keys that could not be paired. Go over the keys in d_vals and for any that were not used (i.e. not in used_ff_keys), build an output line using the values from d_vals, populated the missing columns with missing_val, and output these using the provided output hander.
def reverse_char(self, hints): """Return QuerySet of objects from SQLAlchemy of results. Parameters ---------- hints: list of str strings to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : reverse matches """ ...
Return QuerySet of objects from SQLAlchemy of results. Parameters ---------- hints: list of str strings to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : reverse matches
def bar(self, column_for_categories=None, select=None, overlay=True, width=6, height=4, **vargs): """Plot bar charts for the table. Each plot is labeled using the values in `column_for_categories` and one plot is produced for every other column (or for the columns designated by `select`...
Plot bar charts for the table. Each plot is labeled using the values in `column_for_categories` and one plot is produced for every other column (or for the columns designated by `select`). Every selected column except `column_for_categories` must be numerical. Args: ...
def pruneChanges(self, changeHorizon): """ Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}. """ if not changeHorizon: return None def thd(conn): changes_tbl = self.db.model.changes # First,...
Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}.
def find_tokens(sentence, pattern): """Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which senten...
Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: Spacy...
def datasetScalarTimeStepChunk(lines, numberColumns, numberCells): """ Process the time step chunks for scalar datasets """ END_DATASET_TAG = 'ENDDS' # Define the result object result = {'iStatus': None, 'timestamp': None, 'cellArray': None, 'rasterText...
Process the time step chunks for scalar datasets
def hybrid_forward(self, F, candidates_like, prob, alias): # pylint: disable=unused-argument """Draw samples from uniform distribution and return sampled candidates. Parameters ---------- candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol This input specifies the ...
Draw samples from uniform distribution and return sampled candidates. Parameters ---------- candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol This input specifies the shape of the to be sampled candidates. # TODO shape selection is not yet supported. Shape must be sp...
def spop(self, key, count=None, *, encoding=_NOTSET): """Remove and return one or multiple random members from a set.""" args = [key] if count is not None: args.append(count) return self.execute(b'SPOP', *args, encoding=encoding)
Remove and return one or multiple random members from a set.
def fetch_cache_key(request): """ Returns a hashed cache key. """ m = hashlib.md5() m.update(request.body) return m.hexdigest()
Returns a hashed cache key.
def selected_course(func): """ Passes the selected course as the first argument to func. """ @wraps(func) def inner(*args, **kwargs): course = Course.get_selected() return func(course, *args, **kwargs) return inner
Passes the selected course as the first argument to func.
def progress_bar(name, maxval, prefix='Converting'): """Manages a progress bar for a conversion. Parameters ---------- name : str Name of the file being converted. maxval : int Total number of steps for the conversion. """ widgets = ['{} {}: '.format(prefix, name), Percenta...
Manages a progress bar for a conversion. Parameters ---------- name : str Name of the file being converted. maxval : int Total number of steps for the conversion.
def sync_one(self, aws_syncr, amazon, gateway): """Make sure this gateway exists and has only attributes we want it to have""" gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location) if not gateway_info: amazon.apigateway.create_gateway(gateway.name, gateway.loc...
Make sure this gateway exists and has only attributes we want it to have
def close_tab(self): """ Close active tab. """ if len(self.tab_pages) > 1: # Cannot close last tab. del self.tab_pages[self.active_tab_index] self.active_tab_index = max(0, self.active_tab_index - 1) # Clean up buffers. self._auto_close_new_empty...
Close active tab.
def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is...
Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting...
def normalize_string_keys(old): """Given a dictionary, make sure keys are unicode strings, not bytes.""" new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
Given a dictionary, make sure keys are unicode strings, not bytes.
def parse(self, buffer, inlineparent = None): ''' Compatible to Parser.parse() ''' if len(buffer) < self.struct.size: return None try: return (self.struct.unpack(buffer[:self.struct.size])[0], self.struct.size) except struct.error as exc: ...
Compatible to Parser.parse()
def assemble_graph(): """Assemble INDRA Statements and return Graphviz graph dot string.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ga ...
Assemble INDRA Statements and return Graphviz graph dot string.
def create_chunk(buf): """Create a chunk for the HTTP "chunked" transfer encoding.""" chunk = [] chunk.append(s2b('{:X}\r\n'.format(len(buf)))) chunk.append(buf) chunk.append(b'\r\n') return b''.join(chunk)
Create a chunk for the HTTP "chunked" transfer encoding.
def get_slot_offsets(self): """ col_offset - from bottom left corner of 1 to bottom corner of 2 row_offset - from bottom left corner of 1 to bottom corner of 4 TODO: figure out actual X and Y offsets (from origin) """ SLOT_OFFSETS = { 'slots'...
col_offset - from bottom left corner of 1 to bottom corner of 2 row_offset - from bottom left corner of 1 to bottom corner of 4 TODO: figure out actual X and Y offsets (from origin)
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and Py...
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably...
def load_reg(): ''' Load the register from msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: with salt.utils.files.fopen(regfile, 'r') as fh_: return salt.utils.msgpack.load(fh_) except Exception: log.error('Could not write to...
Load the register from msgpack files
def child(self, offset256): """ Derive new private key from this key and a sha256 "offset" """ a = bytes(self.pubkey) + offset256 s = hashlib.sha256(a).digest() return self.derive_from_seed(s)
Derive new private key from this key and a sha256 "offset"
def compute(self, config, budget, **kwargs): """ Simple example for a compute function The loss is just a the config + some noise (that decreases with the budget) For dramatization, the function can sleep for a given interval to emphasizes the speed ups achievable with parallel ...
Simple example for a compute function The loss is just a the config + some noise (that decreases with the budget) For dramatization, the function can sleep for a given interval to emphasizes the speed ups achievable with parallel workers. Args: config: dictionary containing...
def register_view(self, view): """Loads the text taking it from the model, then starts a timer to scroll it.""" self.view.set_text(self.model.credits) gobject.timeout_add(1500, self.on_begin_scroll) return
Loads the text taking it from the model, then starts a timer to scroll it.
def action_attr(attr_name): """ Creates a setter that will set the specified action attribute to the current value. @param attr_name: the name of an attribute belonging to the action. @type attr_name: str """ def action_attr(value, context, **_params): setattr(context["action"], att...
Creates a setter that will set the specified action attribute to the current value. @param attr_name: the name of an attribute belonging to the action. @type attr_name: str
def cone(cls, **kwargs): """ Returns a cone. Kwargs: start (list): Start of cone, default [0, -1, 0]. end (list): End of cone, default [0, 1, 0]. radius (float): Maximum radius of cone at start, default 1....
Returns a cone. Kwargs: start (list): Start of cone, default [0, -1, 0]. end (list): End of cone, default [0, 1, 0]. radius (float): Maximum radius of cone at start, default 1.0. s...
def serialize_value(value, ty): ''' Serialize a value from an xtuml metamodel instance. ''' ty = ty.upper() null_value = { 'BOOLEAN' : False, 'INTEGER' : 0, 'REAL' : 0.0, 'STRING' : '', 'UNIQUE_ID' : 0 } transfer_fn = { 'B...
Serialize a value from an xtuml metamodel instance.
def get_version(self, extra=None): """ This will return a string that can be used as a prefix for django's cache key. Something like key.1 or key.1.2 If a version was not found '1' will be stored and returned as the number for that key. If extra is given a version will ...
This will return a string that can be used as a prefix for django's cache key. Something like key.1 or key.1.2 If a version was not found '1' will be stored and returned as the number for that key. If extra is given a version will be returned for that value. Otherwise the major...
def partial(cls, id, token, *, adapter): """Creates a partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. Parameters ----------- id: :class:`int` The ID of the webhook. token: :class:`str` The authenticati...
Creates a partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. Parameters ----------- id: :class:`int` The ID of the webhook. token: :class:`str` The authentication token of the webhook. adapter: :class:`We...
async def connect(self) -> Connection: """ Get or create a connection. """ if self._conn is None: self._conn = await r.connect(host=self._host, port=self._port, db=self._db, ...
Get or create a connection.
def moving_average(a, length, mode='valid'): """ From ``bruges`` Computes the mean in a moving window. Naive implementation. Example: >>> test = np.array([1,9,9,9,9,9,9,2,3,9,2,2,3,1,1,1,1,3,4,9,9,9,8,3]) >>> moving_average(test, 7, mode='same') [ 4.42857143, 5.57142857, 6.71...
From ``bruges`` Computes the mean in a moving window. Naive implementation. Example: >>> test = np.array([1,9,9,9,9,9,9,2,3,9,2,2,3,1,1,1,1,3,4,9,9,9,8,3]) >>> moving_average(test, 7, mode='same') [ 4.42857143, 5.57142857, 6.71428571, 7.85714286, 8. , 7.14285714, 7....
def filter_infinity(self): """Filter infinite distances from ``PointCloud.``""" mask = self.coordinates[:, 2] > self.coordinates[:, 2].min() coords = self.coordinates[mask] colors = self.colors[mask] return PointCloud(coords, colors)
Filter infinite distances from ``PointCloud.``
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)): '''Return given points rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis. ''' assert isinstance(pts, list) and len(pts) > 0 l_pt_prev = None for pt in pts: assert isinstance(pt, tu...
Return given points rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis.
def umap(X, y=None, ax=None, classes=None, colors=None, colormap=None, alpha=0.7, **kwargs): """ Display a projection of a vectorized corpus in two dimensions using UMAP (Uniform Manifold Approximation and Projection), a nonlinear dimensionality reduction method that is particularly well ...
Display a projection of a vectorized corpus in two dimensions using UMAP (Uniform Manifold Approximation and Projection), a nonlinear dimensionality reduction method that is particularly well suited to embedding in two or three dimensions for visualization as a scatter plot. UMAP is a relatively new tec...
def get_ehlo_lines(self): """Return the capabilities to be advertised after EHLO.""" lines = [] if self._authenticator != None: # TODO: Make the authentication pluggable but separate mechanism # from user look-up. lines.append('AUTH PLAIN') if self._po...
Return the capabilities to be advertised after EHLO.
def get_translations(self): """Return the correct gettext translations for a request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found. """ ctx = _request_ctx_stack.top if ctx is None: ...
Return the correct gettext translations for a request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found.
def list_types(self): """ Returns a list of all available notification types. """ uri = "/notification_types" resp, resp_body = self.api.method_get(uri) return [CloudMonitorNotificationType(self, info) for info in resp_body["values"]]
Returns a list of all available notification types.
def _build_likelihood(self): """ This gives a variational bound on the model likelihood. """ # Get prior KL. KL = self.build_prior_KL() # Get conditionals fmean, fvar = self._build_predict(self.X, full_cov=False, full_output_cov=False) # Get variational...
This gives a variational bound on the model likelihood.
def list(self, all_tenants=False, **search_opts): """Fetches a list of all floating IPs. :returns: List of FloatingIp object """ if not all_tenants: tenant_id = self.request.user.tenant_id # In Neutron, list_floatingips returns Floating IPs from # all...
Fetches a list of all floating IPs. :returns: List of FloatingIp object
def stop(self): ''' shutdown cache process ''' # avoid getting called twice self.cleanup() if self.running: self.running = False self.timer_stop.set() self.timer.join()
shutdown cache process
def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return ...
Import a referenced message and return a handle
def _time_marker_release(self, event): """Callback for <B1-Release> Event: Hide time marker window""" if not self._time_visible: return self._time_label.destroy() self._time_window.destroy() self._time_label = None self._time_window = None self._time_v...
Callback for <B1-Release> Event: Hide time marker window
def reorder_resource_views(self, resource_views): # type: (List[Union[ResourceView,Dict,str]]) -> None """Order resource views in resource. Args: resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView obje...
Order resource views in resource. Args: resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView objects or dictionaries Returns: None
def _get_django_sites(): """ Get a list of sites as dictionaries {site_id:'domain.name'} """ deployed = version_state('deploy_project') if not env.sites and 'django.contrib.sites' in env.INSTALLED_APPS and deployed: with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',en...
Get a list of sites as dictionaries {site_id:'domain.name'}
def compute_affinity_matrix(self, copy=False, **kwargs): """ This function will compute the affinity matrix. In order to acquire the existing affinity matrix use self.affinity_matrix as comptute_affinity_matrix() will re-compute the affinity matrix. Parameters ----------...
This function will compute the affinity matrix. In order to acquire the existing affinity matrix use self.affinity_matrix as comptute_affinity_matrix() will re-compute the affinity matrix. Parameters ---------- copy : boolean whether to return a copied version of the...
def _guess_vc(self): """ Locate Visual C for 2017 """ if self.vc_ver <= 14.0: return default = r'VC\Tools\MSVC' guess_vc = os.path.join(self.VSInstallDir, default) # Subdir with VC exact version as name try: vc_exact_ver = os.listd...
Locate Visual C for 2017
def decrypt_string(self, token_str, expiration_in_seconds=None): """Verify signature, verify timestamp, and decrypt a token using ``cryptography.fernet.Fernet()``.""" # Add '=' padding if needed if len(token_str) % 4: token_str += '=' * (4 - len(token_str) % 4) # Convert st...
Verify signature, verify timestamp, and decrypt a token using ``cryptography.fernet.Fernet()``.
def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """ logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) r...
If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook.
def almost_hermitian(gate: Gate) -> bool: """Return true if gate tensor is (almost) Hermitian""" return np.allclose(asarray(gate.asoperator()), asarray(gate.H.asoperator()))
Return true if gate tensor is (almost) Hermitian
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
def path(self, path): """ Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolute path the path is returned. :param path: The path that should be joined with the backends location. """ if os...
Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolute path the path is returned. :param path: The path that should be joined with the backends location.
def air_dps(self) -> Union[int, float]: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) if weapon: ...
Does not include upgrades
def upload_index_file(self, test_address, timestamp): """ Create an index.html file with links to all the log files that were just uploaded. """ global already_uploaded_files already_uploaded_files = list(set(already_uploaded_files)) already_uploaded_files.sort() file...
Create an index.html file with links to all the log files that were just uploaded.
def get_current_traceback(*, ignore_system_exceptions=False, show_hidden_frames=False, skip=0, exc): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavio...
Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the function as first parameter.
def sample_uniform_initial_state(parameter, return_constrained=True, init_sample_shape=(), seed=None): """Initialize from a uniform [-2, 2] distribution in unconstrained space. Args: parameter: `sts.Parameter` na...
Initialize from a uniform [-2, 2] distribution in unconstrained space. Args: parameter: `sts.Parameter` named tuple instance. return_constrained: if `True`, re-applies the constraining bijector to return initializations in the original domain. Otherwise, returns initializations in the unconstrain...
def _recompress_archive(archive, verbosity=0, interactive=True): """Try to recompress an archive to smaller size.""" format, compression = get_archive_format(archive) if compression: # only recompress the compression itself (eg. for .tar.xz) format = compression tmpdir = util.tmpdir() ...
Try to recompress an archive to smaller size.
def get_table_idcb_field(endianess, data): """ Return data from a packed TABLE_IDC_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, f...
Return data from a packed TABLE_IDC_BFLD bit-field. :param str endianess: The endianess to use when packing values ('>' or '<') :param str data: The packed and machine-formatted data to parse :rtype: tuple :return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
def harvest_collection(community_name): """Harvest a Zenodo community's record metadata. Examples -------- You can harvest record metadata for a Zenodo community via its identifier name. For example, the identifier for LSST Data Management's Zenodo collection is ``'lsst-dm'``: >>> import z...
Harvest a Zenodo community's record metadata. Examples -------- You can harvest record metadata for a Zenodo community via its identifier name. For example, the identifier for LSST Data Management's Zenodo collection is ``'lsst-dm'``: >>> import zenodio.harvest import harvest_collection >>...
def main(argv=sys.argv[1:], loop=None): """Parse argument and setup main program loop.""" args = docopt(__doc__, argv=argv, version=pkg_resources.require('rflink')[0].version) level = logging.ERROR if args['-v']: level = logging.INFO if args['-v'] == 2: level = log...
Parse argument and setup main program loop.
def user_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#create-user" api_path = "/api/v2/users.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/users#create-user
def _maybe_to_sparse(array): """ array must be SparseSeries or SparseArray """ if isinstance(array, ABCSparseSeries): array = array.values.copy() return array
array must be SparseSeries or SparseArray
async def send(self, sender, **kwargs): ''' send a signal from the sender to all connected receivers ''' if not self.receivers: return [] responses = [] futures = [] for receiver in self._get_receivers(sender): method = receiver() if callable(m...
send a signal from the sender to all connected receivers
def insert(self, revision, index): """ Insert a :class:`revision.data.Revision` at a given index. :param revision: :type revision: :class:`revision.data.Revision` :param index: :type index: int """ if not isinstance(revision, Revision): raise ...
Insert a :class:`revision.data.Revision` at a given index. :param revision: :type revision: :class:`revision.data.Revision` :param index: :type index: int
def prepare_token_request(self, token_url, authorization_response=None, redirect_url=None, state=None, body='', **kwargs): """Prepare a token creation request. Note that these requests usually require client authentication, either by including client_id or a set of...
Prepare a token creation request. Note that these requests usually require client authentication, either by including client_id or a set of provider specific authentication credentials. :param token_url: Provider token creation endpoint URL. :param authorization_response: The ...
def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100): """GetMusicAlbumList Args: tagtype = ??? startnum pagingrow Returns: ??? False: Failed to get property """ url = nurls['setProperty'] ...
GetMusicAlbumList Args: tagtype = ??? startnum pagingrow Returns: ??? False: Failed to get property
def make_cache_key(call_signature: str, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signatur...
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signature. The logic behind these decisions is as follows: - We have a bunch of components of arbitrary t...