positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_input(context, conf): """Gets a user parameter, either from the console or from an outer submodule/system Assumes conf has name, default, prompt and debug """ name = conf['name']['value'] prompt = conf['prompt']['value'] default = conf['default']['value'] or conf['debug']['va...
Gets a user parameter, either from the console or from an outer submodule/system Assumes conf has name, default, prompt and debug
def _scroll(clicks, x=None, y=None): """Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). ...
Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. ...
def tcp_client(tcp_addr): """Connect to the tcp server, and return the settings.""" family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) for i in range(300): logging.info("Connecting to: %s, attempt %d", tcp_addr, i) try:...
Connect to the tcp server, and return the settings.
def init(envVarName, enableColorOutput=False): """ Initialize the logging system and parse the environment variable of the given name. Needs to be called before starting the actual application. """ global _initialized if _initialized: return global _ENV_VAR_NAME _ENV_VAR_NA...
Initialize the logging system and parse the environment variable of the given name. Needs to be called before starting the actual application.
def make_named_stemmer(stem=None, min_len=3): """Construct a callable object and a string sufficient to reconstruct it later (unpickling) >>> make_named_stemmer('str_lower') ('str_lower', <function str_lower at ...>) >>> make_named_stemmer('Lancaster') ('lancaster', <Stemmer object at ...>) """...
Construct a callable object and a string sufficient to reconstruct it later (unpickling) >>> make_named_stemmer('str_lower') ('str_lower', <function str_lower at ...>) >>> make_named_stemmer('Lancaster') ('lancaster', <Stemmer object at ...>)
def data(self): """Return Indicator data.""" # add attributes if self._attributes: self._indicator_data['attribute'] = [] for attr in self._attributes: if attr.valid: self._indicator_data['attribute'].append(attr.data) # add fil...
Return Indicator data.
def print_err(*args, **kwargs): """ A wrapper for print() that uses stderr by default. """ if kwargs.get('file', None) is None: kwargs['file'] = sys.stderr color = dict_pop_or(kwargs, 'color', True) # Use color if asked, but only if the file is a tty. if color and kwargs['file'].isatty(): ...
A wrapper for print() that uses stderr by default.
def angle_single(self, g_num, at_1, at_2, at_3): """ Spanning angle among three atoms. The indices `at_1` and `at_3` can be the same (yielding a trivial zero angle), but `at_2` must be different from both `at_1` and `at_3`. Parameters ---------- g_num ...
Spanning angle among three atoms. The indices `at_1` and `at_3` can be the same (yielding a trivial zero angle), but `at_2` must be different from both `at_1` and `at_3`. Parameters ---------- g_num |int| -- Index of the desired geometry ...
def load(fname: str) -> 'ParallelDataSet': """ Loads a dataset from a binary .npy file. """ data = mx.nd.load(fname) n = len(data) // 3 source = data[:n] target = data[n:2 * n] label = data[2 * n:] assert len(source) == len(target) == len(label) ...
Loads a dataset from a binary .npy file.
def delete_field(self, field_name_or_ref_name, project=None): """DeleteField. [Preview API] Deletes the field. :param str field_name_or_ref_name: Field simple name or reference name :param str project: Project ID or project name """ route_values = {} if project is...
DeleteField. [Preview API] Deletes the field. :param str field_name_or_ref_name: Field simple name or reference name :param str project: Project ID or project name
def auth(self): """Authenticate with the miner and obtain a JSON web token (JWT).""" response = requests.post( parse.urljoin(self.base_url, '/api/auth'), timeout=self.timeout, data={'username': self.username, 'password': self.password}) response.raise_for_stat...
Authenticate with the miner and obtain a JSON web token (JWT).
def walk_cgroups(cgroup, action, opaque): """ The function applies the action function with the opaque object to each control group under the cgroup recursively. """ action(cgroup, opaque) for child in cgroup.childs: walk_cgroups(child, action, opaque)
The function applies the action function with the opaque object to each control group under the cgroup recursively.
def write(self, text='', wrap=True): """Write text and scroll Parameters ---------- text : str Text to write. ``''`` can be used for a blank line, as a newline is automatically added to the end of each line. wrap : str If True, long messages w...
Write text and scroll Parameters ---------- text : str Text to write. ``''`` can be used for a blank line, as a newline is automatically added to the end of each line. wrap : str If True, long messages will be wrapped to span multiple lines.
def _logger_api(self): """Add API logging handler.""" from .tcex_logger import TcExLogHandler, TcExLogFormatter api = TcExLogHandler(self.session) api.set_name('api') api.setLevel(logging.DEBUG) api.setFormatter(TcExLogFormatter()) self.log.addHandler(api)
Add API logging handler.
def _getFromTime(self, atDate=None): """ What was the time of this event? Due to time zones that depends what day we are talking about. If no day is given, assume today. """ if atDate is None: atDate = timezone.localdate(timezone=self.tz) return getLocalTime...
What was the time of this event? Due to time zones that depends what day we are talking about. If no day is given, assume today.
def find_by_type_or_id(type_or_id, prs): """ :param type_or_id: Type of the data to process or ID of the processor class :param prs: A list of :class:`anyconfig.models.processor.Processor` classes :return: A list of processor classes to process files of given data type or processor 'type...
:param type_or_id: Type of the data to process or ID of the processor class :param prs: A list of :class:`anyconfig.models.processor.Processor` classes :return: A list of processor classes to process files of given data type or processor 'type_or_id' found by its ID :raises: UnknownProcessor...
def _resolve_child(self, path): 'Return a member generator by a dot-delimited path' obj = self for component in path.split('.'): ptr = obj if not isinstance(ptr, Permuter): raise self.MessageNotFound("Bad element path [wrong type]") # pylint:...
Return a member generator by a dot-delimited path
def process(self, uid, add_footer=False, no_exec=False, disable_cache=False, ignore_cache=False): """ Execute notebook :return: self """ self.exec_begin = time.perf_counter() self.exec_begin_dt = datetime.datetime.now() ep = CachedExecutePreprocessor(timeout=Non...
Execute notebook :return: self
def accuracy(self, X=None, y=None, mu=None): """ computes the accuracy of the LogisticGAM Parameters ---------- note: X or mu must be defined. defaults to mu X : array-like of shape (n_samples, m_features), optional (default=None) containing input data ...
computes the accuracy of the LogisticGAM Parameters ---------- note: X or mu must be defined. defaults to mu X : array-like of shape (n_samples, m_features), optional (default=None) containing input data y : array-like of shape (n,) containing target dat...
def _compute_iso_line(self): """ compute LineVisual vertices, connects and color-index """ level_index = [] connects = [] verts = [] # calculate which level are within data range # this works for now and the existing examples, but should be tested # thoro...
compute LineVisual vertices, connects and color-index
def prt_report_grp1(self, prt=sys.stdout, **kws_grp): """Print full GO/gene report with grouping.""" summaryline = self.str_summaryline() # Print grouped GO IDs prt.write("{SUMMARY}\n".format(SUMMARY=summaryline)) self.prt_gos_grouped(prt, **kws_grp) # genes genes...
Print full GO/gene report with grouping.
def fill_nan(self, val: str, *cols): """ Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "mycol2")`` ...
Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "mycol2")``
def get_connection_state(self, connection: str) -> Dict[str, Any]: """ For an already established connection return its state. """ if connection not in self.connections: raise ConnectionNotOpen(connection) return self.connections[connection].state
For an already established connection return its state.
def invert(self, output_directory=None, catch_output=True, **kwargs): """Invert this instance, and import the result files No directories/files will be overwritten. Raise an IOError if the output directory exists. Parameters ---------- output_directory: string, optional...
Invert this instance, and import the result files No directories/files will be overwritten. Raise an IOError if the output directory exists. Parameters ---------- output_directory: string, optional use this directory as output directory for the generated tomodir. ...
def ParseConfigCommandLine(): """Parse all the command line options which control the config system.""" # The user may specify the primary config file on the command line. if flags.FLAGS.config: _CONFIG.Initialize(filename=flags.FLAGS.config, must_exist=True) else: raise RuntimeError("A config file is n...
Parse all the command line options which control the config system.
def parse_TSVline(self, line): """ Parses result lines """ split_row = [token.strip() for token in line.split('\t')] _results = {'DefaultResult': 'Conc.'} # ID# 1 if split_row[0] == 'ID#': return 0 # Name CBDV - cannabidivarin elif split_row[...
Parses result lines
def subscriptgroup_handle(tokens): """Process subscriptgroups.""" internal_assert(0 < len(tokens) <= 3, "invalid slice args", tokens) args = [] for arg in tokens: if not arg: arg = "None" args.append(arg) if len(args) == 1: return args[0] else: return ...
Process subscriptgroups.
def invariant_image_similarity(image1, image2, local_search_iterations=0, metric='MI', thetas=np.linspace(0,360,5), thetas2=np.linspace(0,360,5), thetas3=np.linspace(0,360,5), ...
Similarity metrics between two images as a function of geometry Compute similarity metric between two images as image is rotated about its center w/ or w/o optimization ANTsR function: `invariantImageSimilarity` Arguments --------- image1 : ANTsImage reference image image2 : ...
def prepare(*, operation='CREATE', signers=None, recipients=None, asset=None, metadata=None, inputs=None): """Prepares a transaction payload, ready to be fulfilled. Args: operation (str): The operation to perform. Must be ``'CREATE'`` or ``'TRANSFER'``. Case ...
Prepares a transaction payload, ready to be fulfilled. Args: operation (str): The operation to perform. Must be ``'CREATE'`` or ``'TRANSFER'``. Case insensitive. Defaults to ``'CREATE'``. signers (:obj:`list` | :obj:`tuple` | :obj:`str`, optional): One or...
def usersettings(request): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings). """ if has...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings).
def term_regex(term): """ Returns a case-insensitive regex for searching terms """ return re.compile(r'^{0}$'.format(re.escape(term)), re.IGNORECASE)
Returns a case-insensitive regex for searching terms
def leaf(self, node, elem, module, path): """Create a sample leaf element.""" if node.i_default is None: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment( ...
Create a sample leaf element.
def pdfFromPOST(self): """ It returns the pdf for the sampling rounds printed """ html = self.request.form.get('html') style = self.request.form.get('style') reporthtml = "<html><head>%s</head><body><div id='report'>%s</body></html>" % (style, html) return self.pr...
It returns the pdf for the sampling rounds printed
def bin2str(b): """ Binary to string. """ ret = [] for pos in range(0, len(b), 8): ret.append(chr(int(b[pos:pos + 8], 2))) return ''.join(ret)
Binary to string.
def add(self, model): """raises an exception if the model cannot be added""" def foo(m, p, i): if m[i][0].name == model.name: raise ValueError("Model already exists") return # checks if already existing self.foreach(foo) self.appen...
raises an exception if the model cannot be added
def validate_deprecation_semver(version_string, version_description): """Validates that version_string is a valid semver. If so, returns that semver. Raises an error otherwise. :param str version_string: A pantsbuild.pants version which affects some deprecated entity. :param str version_description: A string...
Validates that version_string is a valid semver. If so, returns that semver. Raises an error otherwise. :param str version_string: A pantsbuild.pants version which affects some deprecated entity. :param str version_description: A string used in exception messages to describe what the ...
def process_ssh(self, data, name): """ Processes SSH keys :param data: :param name: :return: """ if data is None or len(data) == 0: return ret = [] try: lines = [x.strip() for x in data.split(b'\n')] for idx, li...
Processes SSH keys :param data: :param name: :return:
def groupby_field(records, field_name, skip_none=True): """ Given a list of objects, group them into a dictionary by the unique values of a given field name. """ return apply_groupby( records, lambda obj: getattr(obj, field_name), skip_none=skip_none)
Given a list of objects, group them into a dictionary by the unique values of a given field name.
def parse(response): """Parse a postdata-style response format from the API into usable data""" """Split a a=1b=2c=3 string into a dictionary of pairs""" tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]} # The odd dummy parameter is of no use to us if '...
Parse a postdata-style response format from the API into usable data
def _createMagConversionDict(): """ loads magnitude_conversion.dat which is table A% 1995ApJS..101..117K """ magnitude_conversion_filepath = resource_stream(__name__, 'data/magnitude_conversion.dat') raw_table = np.loadtxt(magnitude_conversion_filepath, '|S5') magDict = {} for row in raw_table:...
loads magnitude_conversion.dat which is table A% 1995ApJS..101..117K
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): ...
Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub): """Helper function used by Constraint and Model""" if lb is None and ub is None: raise Exception("Free constraint ...") elif lb is None: sense = '<' rhs = float(ub) range_value = 0. elif ub is None: ...
Helper function used by Constraint and Model
def call(node: Node, key: str, value: Any): """Calls node or node instance method""" value = _to_list(value) if not value or not isinstance(value[-1], dict): value.append({}) args = value[0:-1] kwargs = value[-1] node.__dict__[key](*args, **kwargs)
Calls node or node instance method
def second_order_score(y, mean, scale, shape, skewness): """ GAS t Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the t dis...
GAS t Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the t distribution scale : float scale parameter for the ...
def _deserialize_v1(self, deserialized): '''Deserialize a JSON macaroon in v1 format. @param serialized the macaroon in v1 JSON format. @return the macaroon object. ''' from pymacaroons.macaroon import Macaroon, MACAROON_V1 from pymacaroons.caveat import Caveat ...
Deserialize a JSON macaroon in v1 format. @param serialized the macaroon in v1 JSON format. @return the macaroon object.
def angle(self, other): """Return the angle to the vector other""" return math.acos(self.dot(other) / (self.magnitude() * other.magnitude()))
Return the angle to the vector other
def mat_to_laplacian(mat, normalized): """ Converts a sparse or dence adjacency matrix to Laplacian. Parameters ---------- mat : obj Input adjacency matrix. If it is a Laplacian matrix already, return it. normalized : bool Whether to use normalized Laplacian. Normali...
Converts a sparse or dence adjacency matrix to Laplacian. Parameters ---------- mat : obj Input adjacency matrix. If it is a Laplacian matrix already, return it. normalized : bool Whether to use normalized Laplacian. Normalized and unnormalized Laplacians capture different p...
def _break_line(self, line_source, point_size): """ Return a (line, remainder) pair where *line* is the longest line in *line_source* that will fit in this fitter's width and *remainder* is a |_LineSource| object containing the text following the break point. """ lines = ...
Return a (line, remainder) pair where *line* is the longest line in *line_source* that will fit in this fitter's width and *remainder* is a |_LineSource| object containing the text following the break point.
def emailclients(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the email clients used to open your emails. This is only recorded when open tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/opens/emailclients", tag=tag, fromdat...
Gets an overview of the email clients used to open your emails. This is only recorded when open tracking is enabled for that email.
def __insert_frond_LF(d_w, d_u, dfs_data): """Encapsulates the process of inserting a frond uw into the left side frond group.""" # --Add the frond to the left side dfs_data['LF'].append( (d_w, d_u) ) dfs_data['FG']['l'] += 1 dfs_data['last_inserted_side'] = 'LF'
Encapsulates the process of inserting a frond uw into the left side frond group.
async def read(self, n=None): """Read all content """ if self._streamed: return b'' buffer = [] async for body in self: buffer.append(body) return b''.join(buffer)
Read all content
def dftphotom(cfg): """Run the discrete-Fourier-transform photometry algorithm. See the module-level documentation and the output of ``casatask dftphotom --help`` for help. All of the algorithm configuration is specified in the *cfg* argument, which is an instance of :class:`Config`. """ tb = ...
Run the discrete-Fourier-transform photometry algorithm. See the module-level documentation and the output of ``casatask dftphotom --help`` for help. All of the algorithm configuration is specified in the *cfg* argument, which is an instance of :class:`Config`.
def on_bus(self, bus_idx): """ Return the indices of elements on the given buses for shunt-connected elements :param bus_idx: idx of the buses to which the elements are connected :return: idx of elements connected to bus_idx """ assert hasattr(self, 'bus') ...
Return the indices of elements on the given buses for shunt-connected elements :param bus_idx: idx of the buses to which the elements are connected :return: idx of elements connected to bus_idx
def fifo(rst, clk, full, we, din, empty, re, dout, afull=None, aempty=None, afull_th=None, aempty_th=None, ovf=None, udf=None, count=None, count_max=None, depth=None, width=None): """ Synchronous FIFO Input interface: full, we, din Output interface: empty, re, dout It s possible to se...
Synchronous FIFO Input interface: full, we, din Output interface: empty, re, dout It s possible to set din and dout to None. Then the fifo width will be 0 and the fifo will contain no storage. Extra interface: afull (o) - almost full flag, asserted when the number of ...
def change_color(color): """Change the color of the currently selected objects. *color* is represented as a string. Otherwise color can be passed as an rgba tuple of values between 0, 255 Reset the color by passing *color=None*. You can call this function interactively by using:: chan...
Change the color of the currently selected objects. *color* is represented as a string. Otherwise color can be passed as an rgba tuple of values between 0, 255 Reset the color by passing *color=None*. You can call this function interactively by using:: change_color.interactive() ...
def stop_gradient(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a copy of the input fluent with stop_gradient at tensor level. Args: x: The input fluent. Returns: A TensorFluent that stops backpropagation of gradient computations. ''' scope = x.s...
Returns a copy of the input fluent with stop_gradient at tensor level. Args: x: The input fluent. Returns: A TensorFluent that stops backpropagation of gradient computations.
def select_inputs(self, amount): '''Maximize transaction priority. Select the oldest inputs, that are sufficient to cover the spent amount. Then, remove any unneeded inputs, starting with the smallest in value. Returns sum of amounts of inputs selected''' sorted_txin = sorted(self.in...
Maximize transaction priority. Select the oldest inputs, that are sufficient to cover the spent amount. Then, remove any unneeded inputs, starting with the smallest in value. Returns sum of amounts of inputs selected
def acquire(self, *, raise_on_failure=True): """Attempt to acquire a slot under this rate limiter. Parameters: raise_on_failure(bool): Whether or not failures should raise an exception. If this is false, the context manager will instead return a boolean value represen...
Attempt to acquire a slot under this rate limiter. Parameters: raise_on_failure(bool): Whether or not failures should raise an exception. If this is false, the context manager will instead return a boolean value representing whether or not the rate limit slot was ...
def pr_num(self): """Return the PR number or None if not on a PR""" result = get_pr_num(repo=self.repo) if result is None: result = get_travis_pr_num() return result
Return the PR number or None if not on a PR
def data64_send(self, type, len, data, force_mavlink1=False): ''' Data packet, size 64 type : data type (uint8_t) len : data length (uint8_t) data : raw data (uint8_t) ...
Data packet, size 64 type : data type (uint8_t) len : data length (uint8_t) data : raw data (uint8_t)
def expandPath(self, path): """ Follows the path and expand all nodes along the way. Returns (item, index) tuple of the last node in the path (the leaf node). This can be reused e.g. to select it. """ iiPath = self.model().findItemAndIndexPath(path) for (item, ind...
Follows the path and expand all nodes along the way. Returns (item, index) tuple of the last node in the path (the leaf node). This can be reused e.g. to select it.
def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder...
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder", where that decoder logic lives in the ``TransitionFunction``. This method trims the output ...
def register(self, es, append=None, modulo=None): """register a `CMAEvolutionStrategy` instance for logging, ``append=True`` appends to previous data logged under the same name, by default previous data are overwritten. """ if not isinstance(es, CMAEvolutionStrategy): ...
register a `CMAEvolutionStrategy` instance for logging, ``append=True`` appends to previous data logged under the same name, by default previous data are overwritten.
def cleanup_bundle(): """Deletes files used for creating bundle. * vendored/* * bundle.zip """ paths = ['./vendored', './bundle.zip'] for path in paths: if os.path.exists(path): log.debug("Deleting %s..." % path) if os.path.isdir(path): shu...
Deletes files used for creating bundle. * vendored/* * bundle.zip
def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ ret = "{'class': 'NetworkTopologyStrategy'" for dc, repl_factor in sorted(self.dc_replication_factors.items()): ...
Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement.
def task(__decorated__=None, **Config): r"""A decorator to make tasks out of functions. Config: * name (str): The name of the task. Defaults to __decorated__.__name__. * desc (str): The description of the task (optional). * alias (str): The alias for the task (optional). """ if isinstance(__decorat...
r"""A decorator to make tasks out of functions. Config: * name (str): The name of the task. Defaults to __decorated__.__name__. * desc (str): The description of the task (optional). * alias (str): The alias for the task (optional).
def to_internal_value(self, value): """Convert to integer id.""" natural_key = value.split("_") content_type = ContentType.objects.get_by_natural_key(*natural_key) return content_type.id
Convert to integer id.
def prepare_headers(table, bound_columns): """ :type bound_columns: list of BoundColumn """ if table.request is None: return for column in bound_columns: if column.sortable: params = table.request.GET.copy() param_path = _with_path_prefix(table, 'order') ...
:type bound_columns: list of BoundColumn
def mimeType(self): """The official MIME type for this document, guessed from the extensions of the :py:attr:`openxmllib.document.Document.filename` attribute, as opposed to the :py:attr:`openxmllib.document.Document.mime_type` attribute. :return: ``application/xxx`` for this fi...
The official MIME type for this document, guessed from the extensions of the :py:attr:`openxmllib.document.Document.filename` attribute, as opposed to the :py:attr:`openxmllib.document.Document.mime_type` attribute. :return: ``application/xxx`` for this file
def _make_dir(self, client_kwargs): """ Make a directory. args: client_kwargs (dict): Client arguments. """ with _handle_azure_exception(): # Directory if 'directory_name' in client_kwargs: return self.client.create_directory( ...
Make a directory. args: client_kwargs (dict): Client arguments.
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimit...
Convert a sequence of bpe words into sentence.
def _set_stp(self, v, load=False): """ Setter method for stp, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/stp (container) If this variable is read-only (config: false) in the source YANG file, then _set_stp is considered as a private method. Backends ...
Setter method for stp, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/stp (container) If this variable is read-only (config: false) in the source YANG file, then _set_stp is considered as a private method. Backends looking to populate this variable should do...
async def handle_player_update(self, state: "node.PlayerState"): """ Handles player updates from lavalink. Parameters ---------- state : websocket.PlayerState """ if state.position > self.position: self._is_playing = True self.position = state...
Handles player updates from lavalink. Parameters ---------- state : websocket.PlayerState
def _get_local_fields(self, model): "Return the names of all locally defined fields on the model class." local = [f for f in model._meta.fields] m2m = [f for f in model._meta.many_to_many] fields = local + m2m names = tuple([x.name for x in fields]) return { ...
Return the names of all locally defined fields on the model class.
def _fit_full(self=self, X=X, n_components=6): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round...
Fit the model by computing full SVD on X
def best(cls): """ Select the best ScriptWriter for this environment. """ if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'): return WindowsScriptWriter.best() else: return cls
Select the best ScriptWriter for this environment.
def write(domain, key, value, type='string', user=None): ''' Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.write com.apple.CrashReporter DialogType Server salt '*' macdefaults.write NSGlobalDomain ApplePersistence True type=bool domain ...
Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.write com.apple.CrashReporter DialogType Server salt '*' macdefaults.write NSGlobalDomain ApplePersistence True type=bool domain The name of the domain to write to key The key of th...
def post(self, url, postParameters=None, urlParameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if urlParameters: url = url + "?" + self.getParameters(urlParameters) headers = {'Authorization':'GoogleLogin auth=%s' % self....
Convenience method for requesting to google with proper cookies/params.
def _add_history(self, redo_func, redo_kwargs, undo_func, undo_kwargs, **kwargs): """ Add a new log (undo/redoable) to this history context :parameter str redo_func: function to redo the action, must be a method of :class:`Bundle` :parameter dict redo_kw...
Add a new log (undo/redoable) to this history context :parameter str redo_func: function to redo the action, must be a method of :class:`Bundle` :parameter dict redo_kwargs: kwargs to pass to the redo_func. Each item must be serializable (float or str, not objects) :par...
def is_docstring(tokens, previous_logical): """Return found docstring 'A docstring is a string literal that occurs as the first statement in a module, function, class,' http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring """ for token_type, text, start, _, _ in tokens: if token...
Return found docstring 'A docstring is a string literal that occurs as the first statement in a module, function, class,' http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
def _query_by_installer(self, table_name): """ Query for download data broken down by installer, for one day. :param table_name: table name to query against :type table_name: str :return: dict of download information by installer; keys are project name, values are a di...
Query for download data broken down by installer, for one day. :param table_name: table name to query against :type table_name: str :return: dict of download information by installer; keys are project name, values are a dict of installer names to dicts of installer version t...
def set_entry(key, value): """ Set a configuration entry :param key: key name :param value: value for this key :raises KeyError: if key is not str """ if type(key) != str: raise KeyError('key must be str') _config[key] = value
Set a configuration entry :param key: key name :param value: value for this key :raises KeyError: if key is not str
def _is_control(self, char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.start...
Checks whether `chars` is a control character.
async def items(self, *, dc=None, watch=None, consistency=None): """Provides a listing of all prepared queries Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query ...
Provides a listing of all prepared queries Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Blocking): Do a blocking query consistency (Consistency): Force consistency Returns: ...
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile...
Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext
def setup(app): """ Setup for Sphinx extension. :param app: Sphinx application context. """ app.info('adding remote-include directive...', nonl=True) app.add_directive('remote-include', RemoteInclude) app.info(' done') return { 'version': __version__, 'parallel_read_safe...
Setup for Sphinx extension. :param app: Sphinx application context.
def compute_rewards(self, scores): """ Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same. """ # get the k + 1 best scores in descending order bes...
Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same.
def update(self, id=None, new_data={}, **kwargs): """Update an object on the server. Args: id: ID of the object to update (can be None if not required) new_data: the update data for the object **kwargs: Extra options to send to the server (e.g. sudo) Returns...
Update an object on the server. Args: id: ID of the object to update (can be None if not required) new_data: the update data for the object **kwargs: Extra options to send to the server (e.g. sudo) Returns: dict: The new object data (*not* a RESTObject) ...
def to_FIB(self, other): """ Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to u...
Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to use for model comparison.
def valueof(records, key): """Extract the value corresponding to the given key in all the dictionaries >>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'}, ... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}] >>> valueof(bands, 'singe...
Extract the value corresponding to the given key in all the dictionaries >>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'}, ... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}] >>> valueof(bands, 'singer') ['Robert Plant', 'James He...
def _StartProfiling(self, configuration): """Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration. """ if not configuration: return if configuration.HaveProfileMemoryGuppy(): self._guppy_memory_profiler = profilers.GuppyMemoryProfiler( ...
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration.
def detect(self, filename, offset, standalone=False): """Verifies NTFS filesystem signature. Returns: bool: True if filesystem signature at offset 0x03 \ matches 'NTFS ', False otherwise. """ r = RawStruct( filename=filename, offset=off...
Verifies NTFS filesystem signature. Returns: bool: True if filesystem signature at offset 0x03 \ matches 'NTFS ', False otherwise.
def build_from_issue_comment(gh_token, body): """Create a WebhookMetadata from a comment added to an issue. """ if body["action"] in ["created", "edited"]: github_con = Github(gh_token) repo = github_con.get_repo(body['repository']['full_name']) issue = repo.get_issue(body['issue']['...
Create a WebhookMetadata from a comment added to an issue.
def upsert(self, dataset_identifier, payload, content_type="json"): ''' Insert, update or delete data to/from an existing dataset. Currently supports json and csv file objects. See here for the upsert documentation: http://dev.socrata.com/publishers/upsert.html ''' ...
Insert, update or delete data to/from an existing dataset. Currently supports json and csv file objects. See here for the upsert documentation: http://dev.socrata.com/publishers/upsert.html
def derived_sequence(graph): """ Compute the derived sequence of the graph G The intervals of G are collapsed into nodes, intervals of these nodes are built, and the process is repeated iteratively until we obtain a single node (if the graph is not irreducible) """ deriv_seq = [graph] de...
Compute the derived sequence of the graph G The intervals of G are collapsed into nodes, intervals of these nodes are built, and the process is repeated iteratively until we obtain a single node (if the graph is not irreducible)
def configure(self, *args, **kwargs): """Configure the Application through a varied number of sources of different types. This function chains multiple possible configuration methods together in order to just "make it work". You can pass multiple configuration sources in to the ...
Configure the Application through a varied number of sources of different types. This function chains multiple possible configuration methods together in order to just "make it work". You can pass multiple configuration sources in to the method and each one will be tried in a sane fashi...
def datedif(ctx, start_date, end_date, unit): """ Calculates the number of days, months, or years between two dates. """ start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: ...
Calculates the number of days, months, or years between two dates.
def add_letter_to_axis(ax, let, col, x, y, height): """Add 'let' with position x,y and height height to matplotlib axis 'ax'. """ if len(let) == 2: colors = [col, "white"] elif len(let) == 1: colors = [col] else: raise ValueError("3 or more Polygons are not supported") f...
Add 'let' with position x,y and height height to matplotlib axis 'ax'.
def res_phi_pie(pst,logger=None, **kwargs): """plot current phi components as a pie chart. Parameters ---------- pst : pyemu.Pst logger : pyemu.Logger kwargs : dict accepts 'include_zero' as a flag to include phi groups with only zero-weight obs (not sure why anyone would do thi...
plot current phi components as a pie chart. Parameters ---------- pst : pyemu.Pst logger : pyemu.Logger kwargs : dict accepts 'include_zero' as a flag to include phi groups with only zero-weight obs (not sure why anyone would do this, but whatevs). Returns ------- ...
def atlas_renderer(layout, coverage_layer, output_path, file_format): """Extract composition using atlas generation. :param layout: QGIS Print Layout object used for producing the report. :type layout: qgis.core.QgsPrintLayout :param coverage_layer: Coverage Layer used for atlas map. :type coverag...
Extract composition using atlas generation. :param layout: QGIS Print Layout object used for producing the report. :type layout: qgis.core.QgsPrintLayout :param coverage_layer: Coverage Layer used for atlas map. :type coverage_layer: QgsMapLayer :param output_path: The output path of the product....