code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def find_copy_constructor(type_): """ Returns reference to copy constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the copy constructor """ copy_ = type_.constructors( lambda x: is_copy_constructor(x), ...
Returns reference to copy constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the copy constructor
def get_stock_basicinfo(self, market, stock_type=SecurityType.STOCK, code_list=None): """ 获取指定市场中特定类型的股票基本信息 :param market: 市场类型,futuquant.common.constant.Market :param stock_type: 股票类型, futuquant.common.constant.SecurityType :param code_list: 如果不为None,应该是股票code的iterable类型,将只返回指定...
获取指定市场中特定类型的股票基本信息 :param market: 市场类型,futuquant.common.constant.Market :param stock_type: 股票类型, futuquant.common.constant.SecurityType :param code_list: 如果不为None,应该是股票code的iterable类型,将只返回指定的股票信息 :return: (ret_code, content) ret_code 等于RET_OK时, content为Pandas.DataFrame数据,...
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ admin_metadata = self.get_admin_metadata() uuid = admin_metad...
Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed
def remove_relation(post_id, tag_id): ''' Delete the record of post 2 tag. ''' entry = TabPost2Tag.delete().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == tag_id) ) entry.execute() MCategory.update_count(tag_id)
Delete the record of post 2 tag.
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new results.
def correlation(s, o): """ correlation coefficient input: s: simulated o: observed output: correlation: correlation coefficient """ # s,o = filter_nan(s,o) if s.size == 0: corr = np.NaN else: corr = np.corrcoef(o, s)[0, 1] retur...
correlation coefficient input: s: simulated o: observed output: correlation: correlation coefficient
def on_delete(resc, req, resp, rid): # pylint: disable=unused-argument """ Delete the single item Upon a successful deletion an empty bodied 204 is returned. """ signals.pre_req.send(resc.model) signals.pre_req_delete.send(resc.model) model = find(resc.model, rid) goldman.sess.store....
Delete the single item Upon a successful deletion an empty bodied 204 is returned.
def store_many_vectors(self, hash_name, bucket_keys, vs, data): """ Store a batch of vectors. Stores vector and JSON-serializable data in bucket with specified key. """ if data is None: data = itertools.repeat(data) for v, k, d in zip(vs, bucket_keys, data): ...
Store a batch of vectors. Stores vector and JSON-serializable data in bucket with specified key.
def extract_paths(self, paths, ignore_nopath): """ Extract the given paths from the domain Attempt to extract all files defined in ``paths`` with the method defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`, if it fails, and `guestfs` is available it will try ex...
Extract the given paths from the domain Attempt to extract all files defined in ``paths`` with the method defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`, if it fails, and `guestfs` is available it will try extracting the files with guestfs. Args: ...
def get_default_query_from_module(module): """ Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module. """ if isinstance(module, types.ModuleType): return module.__dict__.get(_SQL_MODULE_LAST, No...
Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module.
def has_equal_ast(state, incorrect_msg=None, code=None, exact=True, append=None): """Test whether abstract syntax trees match between the student and solution code. ``has_equal_ast()`` can be used in two ways: * As a robust version of ``has_code()``. By setting ``code``, you can look for the AST represent...
Test whether abstract syntax trees match between the student and solution code. ``has_equal_ast()`` can be used in two ways: * As a robust version of ``has_code()``. By setting ``code``, you can look for the AST representation of ``code`` in the student's submission. But be aware that ``a`` and ``a = 1`...
def runGetOutput(cmd, raiseOnFailure=False, encoding=sys.getdefaultencoding()): ''' runGetOutput - Simply runs a command and returns the output as a string. Use #runGetResults if you need something more complex. @param cmd <str/list> - String of command and arguments, or list of command...
runGetOutput - Simply runs a command and returns the output as a string. Use #runGetResults if you need something more complex. @param cmd <str/list> - String of command and arguments, or list of command and arguments If cmd is a string, the command will be executed as if ran exactly as wr...
def python_type(self): """Return the python type for the row, possibly getting it from a valuetype reference """ from ambry.valuetype import resolve_value_type if self.valuetype and resolve_value_type(self.valuetype): return resolve_value_type(self.valuetype)._pythontype e...
Return the python type for the row, possibly getting it from a valuetype reference
def run(self, schedule_type, lookup_id, **kwargs): """ Loads Schedule linked to provided lookup """ log = self.get_logger(**kwargs) log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id)) task_run = QueueTaskRun() task_run.task_id = self.request.id or uuid4() ...
Loads Schedule linked to provided lookup
def _make_meta(self, tracker_url, root_name, private, progress): """ Create torrent dict. """ # Calculate piece size if self._fifo: # TODO we need to add a (command line) param, probably for total data size # for now, always 1MB piece_size_exp = 20 ...
Create torrent dict.
def start_runs( logdir, steps, run_name, thresholds, mask_every_other_prediction=False): """Generate a PR curve with precision and recall evenly weighted. Arguments: logdir: The directory into which to store all the runs' data. steps: The number of steps to run for. run_name: The na...
Generate a PR curve with precision and recall evenly weighted. Arguments: logdir: The directory into which to store all the runs' data. steps: The number of steps to run for. run_name: The name of the run. thresholds: The number of thresholds to use for PR curves. mask_every_other_prediction: Whe...
def assign_edge_colors_and_widths(self): """ Resolve conflict of 'node_color' and 'node_style['fill'] args which are redundant. Default is node_style.fill unless user entered node_color. To enter multiple colors user must use node_color not style fill. Either way, we build a lis...
Resolve conflict of 'node_color' and 'node_style['fill'] args which are redundant. Default is node_style.fill unless user entered node_color. To enter multiple colors user must use node_color not style fill. Either way, we build a list of colors to pass to Drawing.node_colors which is ...
def visit_tryexcept(self, node): """return an astroid.TryExcept node as string""" trys = ["try:\n%s" % self._stmt_list(node.body)] for handler in node.handlers: trys.append(handler.accept(self)) if node.orelse: trys.append("else:\n%s" % self._stmt_list(node.orelse...
return an astroid.TryExcept node as string
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[ObjectValue, "DataNode"]: """Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node. """ keys = self.parse_keys(sn) ...
Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
def clientConnected(self, proto): """ Called when a client connects to the bus. This method assigns the new connection a unique bus name. """ proto.uniqueName = ':1.%d' % (self.next_id,) self.next_id += 1 self.clients[proto.uniqueName] = proto
Called when a client connects to the bus. This method assigns the new connection a unique bus name.
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' ...
Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive).
def page_uri_handler(context, content, pargs, kwargs): """ Shortcode for getting the link to internal pages using the flask `url_for` method. Activate with 'shortcodes' template filter. Within the content use the chill page_uri shortcode: "[chill page_uri idofapage]". The argument is the 'uri' ...
Shortcode for getting the link to internal pages using the flask `url_for` method. Activate with 'shortcodes' template filter. Within the content use the chill page_uri shortcode: "[chill page_uri idofapage]". The argument is the 'uri' for a page that chill uses. Does not verify the link to see if...
def _grab_history(self): """Calculate the needed history/changelog changes Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them, check if the first one matches the version and whether it has a the current date. """ default_location = None config =...
Calculate the needed history/changelog changes Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them, check if the first one matches the version and whether it has a the current date.
def health(self, session=None): """ An endpoint helping check the health status of the Airflow instance, including metadatabase and scheduler. """ BJ = jobs.BaseJob payload = {} scheduler_health_check_threshold = timedelta(seconds=conf.getint('scheduler', ...
An endpoint helping check the health status of the Airflow instance, including metadatabase and scheduler.
def apply_projection(projection, value): """Apply projection.""" if isinstance(value, Sequence): # Apply projection to each item in the list. return [ apply_projection(projection, item) for item in value ] elif not isinstance(value, Mapping): # Non-dic...
Apply projection.
def find_neighbor_pores(self, pores, mode='union', flatten=True, include_input=False): r""" Returns a list of pores that are direct neighbors to the given pore(s) Parameters ---------- pores : array_like Indices of the pores whose neighbor...
r""" Returns a list of pores that are direct neighbors to the given pore(s) Parameters ---------- pores : array_like Indices of the pores whose neighbors are sought flatten : boolean If ``True`` (default) the returned result is a compressed array of ...
def get_overridden_calculated_entry(self): """Gets the calculated entry this entry overrides. return: (osid.grading.GradeEntry) - the calculated entry raise: IllegalState - ``overrides_calculated_entry()`` is ``false`` raise: OperationFailed - unable to complete reques...
Gets the calculated entry this entry overrides. return: (osid.grading.GradeEntry) - the calculated entry raise: IllegalState - ``overrides_calculated_entry()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must b...
def is_applicable(self, date_string, strip_timezone=False, settings=None): """ Check if the locale is applicable to translate date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :para...
Check if the locale is applicable to translate date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param strip_timezone: If True, timezone is stripped from date string. :type str...
def clipValue(self, value, minValue, maxValue): ''' Makes sure that value is within a specific range. If not, then the lower or upper bounds is returned ''' return min(max(value, minValue), maxValue)
Makes sure that value is within a specific range. If not, then the lower or upper bounds is returned
def fit_classifier(self, name, analytes, method, samples=None, subset=None, filt=True, sort_by=0, **kwargs): """ Create a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier. ...
Create a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier. analytes : str or iterable Which analytes the clustering algorithm should consider. method : str Which clustering al...
def nx_contracted_nodes(G, u, v, self_loops=True, inplace=False): """ copy of networkx function with inplace modification TODO: commit to networkx """ import itertools as it if G.is_directed(): in_edges = ((w, u, d) for w, x, d in G.in_edges(v, data=True) if self_loop...
copy of networkx function with inplace modification TODO: commit to networkx
def aoi(self, **kwargs): """ Subsets the Image by the given bounds Args: bbox (list): optional. A bounding box array [minx, miny, maxx, maxy] wkt (str): optional. A WKT geometry string geojson (str): optional. A GeoJSON geometry dictionary Returns: ...
Subsets the Image by the given bounds Args: bbox (list): optional. A bounding box array [minx, miny, maxx, maxy] wkt (str): optional. A WKT geometry string geojson (str): optional. A GeoJSON geometry dictionary Returns: image: an image instance of the sa...
def poly(self, return_coeffs=False): """returns the quadratic as a Polynomial object.""" p = self.bpoints() coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0]) if return_coeffs: return coeffs else: return np.poly1d(coeffs)
returns the quadratic as a Polynomial object.
def mosaic_inline(self, imagelist, bg_ref=None, trim_px=None, merge=False, allow_expand=True, expand_pad_deg=0.01, max_expand_pct=None, update_minmax=True, suppress_callback=False): """Drops new images into the current image (if there is room), ...
Drops new images into the current image (if there is room), relocating them according the WCS between the two images.
def exceptions(self): """ Returns a list of ParamDoc objects (with empty names) of the exception tags for the function. >>> comments = parse_comments_for_file('examples/module_closure.js') >>> fn1 = FunctionDoc(comments[1]) >>> fn1.exceptions[0].doc 'Another exce...
Returns a list of ParamDoc objects (with empty names) of the exception tags for the function. >>> comments = parse_comments_for_file('examples/module_closure.js') >>> fn1 = FunctionDoc(comments[1]) >>> fn1.exceptions[0].doc 'Another exception' >>> fn1.exceptions[1].doc ...
def copy_unit_properties(self, sorting, unit_ids=None): '''Copy unit properties from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the properties will be copied uni...
Copy unit properties from another sorting extractor to the current sorting extractor. Parameters ---------- sorting: SortingExtractor The sorting extractor from which the properties will be copied unit_ids: (array_like, int) The list (or single value) of ...
def iter_links(operations, page): """ Generate links for an iterable of operations on a starting page. """ for operation, ns, rule, func in operations: yield Link.for_( operation=operation, ns=ns, type=ns.subject_name, qs=page.to_items(), ...
Generate links for an iterable of operations on a starting page.
def resume_transfer_operation(self, operation_name): """ Resumes an transfer operation in Google Storage Transfer Service. :param operation_name: (Required) Name of the transfer operation. :type operation_name: str :rtype: None """ self.get_conn().transferOperati...
Resumes an transfer operation in Google Storage Transfer Service. :param operation_name: (Required) Name of the transfer operation. :type operation_name: str :rtype: None
def pid(self): """The pid of the process associated to the scheduler.""" try: return self._pid except AttributeError: self._pid = os.getpid() return self._pid
The pid of the process associated to the scheduler.
def get_unique_families(hkls): """ Returns unique families of Miller indices. Families must be permutations of each other. Args: hkls ([h, k, l]): List of Miller indices. Returns: {hkl: multiplicity}: A dict with unique hkl and multiplicity. """ # TODO: Definitely can be sp...
Returns unique families of Miller indices. Families must be permutations of each other. Args: hkls ([h, k, l]): List of Miller indices. Returns: {hkl: multiplicity}: A dict with unique hkl and multiplicity.
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#de...
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
def replace_word_tokens(string, language): """ Given a string and an ISO 639-2 language code, return the string with the words replaced with an operational equivalent. """ words = mathwords.word_groups_for_language(language) # Replace operator words with numeric operators operators = wo...
Given a string and an ISO 639-2 language code, return the string with the words replaced with an operational equivalent.
def console(self, ttynum=-1, stdinfd=0, stdoutfd=1, stderrfd=2, escape=1): """ Attach to console of running container. """ if not self.running: return False return _lxc.Container.console(self, ttynum, stdinfd, stdoutfd, stde...
Attach to console of running container.
def send(self,text): """Send a string to the PiLite, can be simple text or a $$$ command""" #print text self.s.write(text) time.sleep(0.001*len(text))
Send a string to the PiLite, can be simple text or a $$$ command
def add_json(self, json_obj, **kwargs): """Adds a json-serializable Python dict as a json file to IPFS. .. code-block:: python >>> c.add_json({'one': 1, 'two': 2, 'three': 3}) 'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob' Parameters ---------- json_o...
Adds a json-serializable Python dict as a json file to IPFS. .. code-block:: python >>> c.add_json({'one': 1, 'two': 2, 'three': 3}) 'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob' Parameters ---------- json_obj : dict A json-serializable Python di...
def load(obj, settings_module, identifier="py", silent=False, key=None): """Tries to import a python module""" mod, loaded_from = get_module(obj, settings_module, silent) if mod and loaded_from: obj.logger.debug("py_loader: {}".format(mod)) else: obj.logger.debug( "py_loader...
Tries to import a python module
def swap(self, fn, *args, **kwargs): ''' Given a mutator `fn`, calls `fn` with the atom's current state, `args`, and `kwargs`. The return value of this invocation becomes the new value of the atom. Returns the new value. :param fn: A function which will be passed the current sta...
Given a mutator `fn`, calls `fn` with the atom's current state, `args`, and `kwargs`. The return value of this invocation becomes the new value of the atom. Returns the new value. :param fn: A function which will be passed the current state. Should return a new state. This absolutel...
def set(self, obj, id, payload, action='', async=False): """ Function set Set an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @param action: specific action of an object ('power'...) @param payload: the d...
Function set Set an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @param action: specific action of an object ('power'...) @param payload: the dict of the payload @param async: should this request be async...
def profile_cancel(self, query_id, timeout=10): """ Cancel the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = Resul...
Cancel the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result
def OnExpandAll(self): """ expand all nodes """ root = self.tree.GetRootItem() fn = self.tree.Expand self.traverse(root, fn) self.tree.Expand(root)
expand all nodes
def onStart(self, event): """ Display the environment of a started container """ c = event.container print '+' * 5, 'started:', c kv = lambda s: s.split('=', 1) env = {k: v for (k, v) in (kv(s) for s in c.attrs['Config']['Env'])} print env
Display the environment of a started container
def fit(self, counts_df, val_set=None): """ Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to ...
Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to '.fit' might be modified inplace - if this is a ...
def use_app(backend_name=None, call_reuse=True): """ Get/create the default Application object It is safe to call this function multiple times, as long as backend_name is None or matches the already selected backend. Parameters ---------- backend_name : str | None The name of the backe...
Get/create the default Application object It is safe to call this function multiple times, as long as backend_name is None or matches the already selected backend. Parameters ---------- backend_name : str | None The name of the backend application to use. If not specified, Vispy tr...
def optimise_xy(xy, *args): """Return negative pore diameter for x and y coordinates optimisation.""" z, elements, coordinates = args window_com = np.array([xy[0], xy[1], z]) return -pore_diameter(elements, coordinates, com=window_com)[0]
Return negative pore diameter for x and y coordinates optimisation.
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.leapyear_observed = None else: self.leapyear_observed = vals[i] i += 1 if len(vals[i]) =...
Read values. Args: vals (list): list of strings representing values
def signin(request, auth_form=AuthenticationForm, template_name='userena/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combining...
Signin using email or username with password. Signs a user in by combining email/username with password. If the combination is correct and the user :func:`is_active` the :func:`redirect_signin_function` is called with the arguments ``REDIRECT_FIELD_NAME`` and an instance of the :class:`User` who is is ...
def refitPrefixes(self): """ Refit namespace qualification by replacing prefixes with explicit namespaces. Also purges prefix mapping table. @return: self @rtype: L{Element} """ for c in self.children: c.refitPrefixes() if self.prefix is not No...
Refit namespace qualification by replacing prefixes with explicit namespaces. Also purges prefix mapping table. @return: self @rtype: L{Element}
def switch(request, url): """ Set/clear boolean field value for model object """ app_label, model_name, object_id, field = url.split('/') try: # django >= 1.7 from django.apps import apps model = apps.get_model(app_label, model_name) except ImportError: # django <...
Set/clear boolean field value for model object
def _resolve(self, name): """ Resolve the given store :param name: The store to resolve :type name: str :rtype: Repository """ config = self._get_config(name) if not config: raise RuntimeError('Cache store [%s] is not defined.' % name) ...
Resolve the given store :param name: The store to resolve :type name: str :rtype: Repository
def add(self, defn): """Adds the given Packet Definition to this Telemetry Dictionary.""" if defn.name not in self: self[defn.name] = defn else: msg = "Duplicate packet name '%s'" % defn.name log.error(msg) raise util.YAMLError(msg)
Adds the given Packet Definition to this Telemetry Dictionary.
def downloadArchiveAction(self, request, queryset): ''' Download selected submissions as archive, for targeted correction. ''' output = io.BytesIO() z = zipfile.ZipFile(output, 'w') for sub in queryset: sub.add_to_zipfile(z) z.close() # go ba...
Download selected submissions as archive, for targeted correction.
def _dump_to_file(self, file): """dump to the file""" xmltodict.unparse(self.object(), file, pretty=True)
dump to the file
def evaluate_stacked_ensemble(path, ensemble_id): """Evaluates the ensemble and updates the database when finished/ Args: path (str): Path to Xcessiv notebook ensemble_id (str): Ensemble ID """ with functions.DBContextManager(path) as session: stacked_ensemble = session.query(m...
Evaluates the ensemble and updates the database when finished/ Args: path (str): Path to Xcessiv notebook ensemble_id (str): Ensemble ID
def list_objects(self, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users. """ if not bucket_name: bucket_name = self.bucket_...
This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users.
def spreadsheet(service, id): """Fetch and return spreadsheet meta data with Google sheets API.""" request = service.spreadsheets().get(spreadsheetId=id) try: response = request.execute() except apiclient.errors.HttpError as e: if e.resp.status == 404: raise KeyError(id) ...
Fetch and return spreadsheet meta data with Google sheets API.
def status_bar(python_input): """ Create the `Layout` for the status bar. """ TB = 'class:status-toolbar' @if_mousedown def toggle_paste_mode(mouse_event): python_input.paste_mode = not python_input.paste_mode @if_mousedown def enter_history(mouse_event): python_input.e...
Create the `Layout` for the status bar.
def handle_inittarget( state_change: ActionInitTarget, channel_state: NettingChannelState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[TargetTransferState]: """ Handles an ActionInitTarget state change. """ transfer = state_change.tran...
Handles an ActionInitTarget state change.
def create_secret(self, value, contributor, metadata=None, expires=None): """Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata dictionary (must be JSON serializable) :param...
Create a new secret, returning its handle. :param value: Secret value to store :param contributor: User owning the secret :param metadata: Optional metadata dictionary (must be JSON serializable) :param expires: Optional date/time of expiry (defaults to None, which means that ...
def inception_v3(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, de...
r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in ...
def call(method, *args, **kwargs): ''' Calls a specific method from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix :param method: specifies the name ...
Calls a specific method from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix :param method: specifies the name of the method to be called :param params: c...
def _parse_one_event(self): """Parse the stream buffer and return either a single event or None""" # WVA includes \r\n between messages which the parser doesn't like, so we # throw away any data before a opening brace try: open_brace_idx = self._buf.index('{') except ...
Parse the stream buffer and return either a single event or None
def extract_lookups(value): """Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any """ lookups = set() if isinstance(value, ...
Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any
def get_differing_atom_residue_ids(self, pdb_name, pdb_list): '''Returns a list of residues in pdb_name which differ from the pdbs corresponding to the names in pdb_list.''' assert(pdb_name in self.pdb_names) assert(set(pdb_list).intersection(set(self.pdb_names)) == set(pdb_list)) # the names i...
Returns a list of residues in pdb_name which differ from the pdbs corresponding to the names in pdb_list.
def _assertField(self, name): """Raise AttributeError when PacketHistory has no field with the given name. """ if name not in self._names: msg = 'PacketHistory "%s" has no field "%s"' values = self._defn.name, name raise AttributeError(msg % values)
Raise AttributeError when PacketHistory has no field with the given name.
def get_or_guess_labels(model, x, **kwargs): """ Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then ...
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then assume it's a targeted attack and use that as the l...
def get_sn(unit): """获取文本行的句子数量 Keyword arguments: unit -- 文本行 Return: sn -- 句数 """ sn = 0 match_re = re.findall(str(sentence_delimiters), unit) if match_re: string = ''.join(match_re) sn = len(string) return int(sn)
获取文本行的句子数量 Keyword arguments: unit -- 文本行 Return: sn -- 句数
def run(cmd_str,cwd='.',verbose=False): """ an OS agnostic function to execute a command line Parameters ---------- cmd_str : str the str to execute with os.system() cwd : str the directory to execute the command in verbose : bool flag to echo to stdout complete cmd st...
an OS agnostic function to execute a command line Parameters ---------- cmd_str : str the str to execute with os.system() cwd : str the directory to execute the command in verbose : bool flag to echo to stdout complete cmd str Note ---- uses platform to detect...
def parent(self): """ Return the parent device. """ if self._has_parent is None: _parent = self._ctx.backend.get_parent(self._ctx.dev) self._has_parent = _parent is not None if self._has_parent: self._parent = Device(_parent, self._ctx.backend) ...
Return the parent device.
def find_optimal_allocation(self, tokens): """ Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie :param tokens: tokens tokenize :type tokens: list of str :return: Optimal allocation of tokens to phrases :rtype: list of TokenTrie.Token ...
Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie :param tokens: tokens tokenize :type tokens: list of str :return: Optimal allocation of tokens to phrases :rtype: list of TokenTrie.Token
def attended_by(self, email): """ Check if user attended the event """ for attendee in self["attendees"] or []: if (attendee["email"] == email and attendee["responseStatus"] == "accepted"): return True return False
Check if user attended the event
def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3): """Read a string from the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Args: ...
Read a string from the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Args: * registeraddress (int): The slave register start address (use decimal numbers, not hex...
def get_dependencies(self): """Return dependencies, which should trigger updates of this model.""" # pylint: disable=no-member return super().get_dependencies() + [ Data.collection_set, Data.entity_set, Data.parents, ]
Return dependencies, which should trigger updates of this model.
def validate_auth_mechanism(option, value): """Validate the authMechanism URI option. """ # CRAM-MD5 is for server testing only. Undocumented, # unsupported, may be removed at any time. You have # been warned. if value not in MECHANISMS and value != 'CRAM-MD5': raise ValueError("%s must ...
Validate the authMechanism URI option.
def print_genl_msg(_, ofd, hdr, ops, payloadlen): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L831. Positional arguments: _ -- unused. ofd -- function to call with arguments similar to `logging.debug`. hdr -- Netlink message header (nlmsghdr class instance). ops -- cache oper...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L831. Positional arguments: _ -- unused. ofd -- function to call with arguments similar to `logging.debug`. hdr -- Netlink message header (nlmsghdr class instance). ops -- cache operations (nl_cache_ops class instance). payloadlen -- l...
def put(self, key): """Put and return the only unique identifier possible, its url """ self._consul_request('PUT', self._key_url(key['name']), json=key) return key['name']
Put and return the only unique identifier possible, its url
def _el_orb_tuple(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (`str`): The selected elements and orbitals in in the form: `"Sn.s.p,O"`. Returns: ...
Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (`str`): The selected elements and orbitals in in the form: `"Sn.s.p,O"`. Returns: A list of tuples specifying which...
def to_dict(self): '''Save this target component into a dictionary.''' d = {'componentId': self.component_id, 'instanceName': self.instance_name} props = [] for name in self.properties: p = {'name': name} if self.properties[name]: p...
Save this target component into a dictionary.
def stencils(self): """List of stencils.""" if not self._stencils: self._stencils = self.manifest['stencils'] return self._stencils
List of stencils.
def location(self, value): """(Deprecated) Set `Bucket.location` This can only be set at bucket **creation** time. See https://cloud.google.com/storage/docs/json_api/v1/buckets and https://cloud.google.com/storage/docs/bucket-locations .. warning:: Assignment to '...
(Deprecated) Set `Bucket.location` This can only be set at bucket **creation** time. See https://cloud.google.com/storage/docs/json_api/v1/buckets and https://cloud.google.com/storage/docs/bucket-locations .. warning:: Assignment to 'Bucket.location' is deprecated, as it ...
def _set_relative_pythonpath(self, value): """Set PYTHONPATH list relative paths""" self.pythonpath = [osp.abspath(osp.join(self.root_path, path)) for path in value]
Set PYTHONPATH list relative paths
def sysinfo2float(version_info=sys.version_info): """Convert a sys.versions_info-compatible list into a 'canonic' floating-point number which that can then be used to look up a magic number. Note that this can only be used for released version of C Python, not interim development versions, since we can...
Convert a sys.versions_info-compatible list into a 'canonic' floating-point number which that can then be used to look up a magic number. Note that this can only be used for released version of C Python, not interim development versions, since we can't represent that as a floating-point number. Fo...
def route_handler(context, content, pargs, kwargs): """ Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[ch...
Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[chill route /path/to/something/]" where the '[chill' and ']' a...
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ECDSA_LOW_Curve(key) if key not in ECDSA_LOW_Curve._member_map_: extend_enum(ECDSA_LOW_Curve, key, default) return ECDSA_LOW_Curve[key]
Backport support for original codes.
def get_certificate_json(self, certificate_uid): """ Returns certificate as json. Propagates KeyError if key isn't found :param certificate_uid: :return: """ if certificate_uid.startswith(URN_UUID_PREFIX): uid = certificate_uid[len(URN_UUID_PREFIX):] ...
Returns certificate as json. Propagates KeyError if key isn't found :param certificate_uid: :return:
def process_am1(self, am1): """ Due to the solving process involving multiple optimization levels to be treated individually, new soft clauses for the detected intrinsic AtMost1 constraints should be remembered. The method is a slightly modified version of ...
Due to the solving process involving multiple optimization levels to be treated individually, new soft clauses for the detected intrinsic AtMost1 constraints should be remembered. The method is a slightly modified version of the base method :func:`RC2.process_am1` taking ...
def raw_file(client, src, dest, opt): """Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded.""" path, key = path_pieces(src) resp = client.read(path) if not resp: client.revoke_self_token() raise aomi.excep...
Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded.
def _report_external_dependencies(self, sect, _, _dummy): """return a verbatim layout for displaying dependencies""" dep_info = _make_tree_defs(self._external_dependencies_info().items()) if not dep_info: raise EmptyReportError() tree_str = _repr_tree_defs(dep_info) s...
return a verbatim layout for displaying dependencies
def get_namespaces(namespace="", apiserver_url=None): ''' .. versionadded:: 2016.3.0 Get one or all kubernetes namespaces. If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example: .. code-block:: bash kubectl get namespaces -o...
.. versionadded:: 2016.3.0 Get one or all kubernetes namespaces. If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example: .. code-block:: bash kubectl get namespaces -o json In case namespace is set by user, the output will be si...
def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret ...
Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5
def hydrate_input_uploads(input_, input_schema, hydrate_values=True): """Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths. """ from resolwe.flow.managers import manager files = [] for field_schema, fields ...
Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths.