code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def __view_add_actions(self): """ Sets the **Components_Manager_Ui_treeView** actions. """ self.Components_Manager_Ui_treeView.addAction(self.__engine.actions_manager.register_action( "Actions|Umbra|Components|factory.ComponentsManagerUi|Activate Component(s)", s...
Sets the **Components_Manager_Ui_treeView** actions.
def name(self): """ The name for the window as displayed in the title bar and status bar. """ # Name, explicitely set for the pane. if self.chosen_name: return self.chosen_name else: # Name from the process running inside the pane. name...
The name for the window as displayed in the title bar and status bar.
def support_scripting(self): """ Returns True if scripting is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time. """ if not hasattr(self, '_support_scripting'): try: self._...
Returns True if scripting is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time.
def add_node(self, id, label=None, type='CLASS', meta=None): """ Add a new node to the ontology """ g = self.get_graph() if meta is None: meta={} g.add_node(id, label=label, type=type, meta=meta)
Add a new node to the ontology
def moment1(self): """The first time delay weighted statistical moment of the instantaneous unit hydrograph.""" delays, response = self.delay_response_series return statstools.calc_mean_time(delays, response)
The first time delay weighted statistical moment of the instantaneous unit hydrograph.
def nl_msg_in_handler_debug(msg, arg): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114.""" ofd = arg or _LOGGER.debug ofd('-- Debug: Received Message:') nl_msg_dump(msg, ofd) return NL_OK
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114.
def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields): """ Assemble the concatenated metadata dfs together. For example, if horizontally concatenating, the concatenated metadata dfs are the column metadata dfs. Both indices are sorted. Args: concated_meta_dfs (list of pa...
Assemble the concatenated metadata dfs together. For example, if horizontally concatenating, the concatenated metadata dfs are the column metadata dfs. Both indices are sorted. Args: concated_meta_dfs (list of pandas dfs) Returns: all_concated_meta_df_sorted (pandas df)
def check_length_of_initial_values(self, init_values): """ Ensures that the initial values are of the correct length. """ # Figure out how many shape parameters we should have and how many # index coefficients we should have num_nests = self.rows_to_nests.shape[1] ...
Ensures that the initial values are of the correct length.
def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' ...
Return the template class object from agiven name.
def train(*tf_records: "Records to train on"): """Train on examples.""" tf.logging.set_verbosity(tf.logging.INFO) estimator = dual_net.get_estimator() effective_batch_size = FLAGS.train_batch_size if FLAGS.use_tpu: effective_batch_size *= FLAGS.num_tpu_cores if FLAGS.use_tpu: i...
Train on examples.
def _set_value(self, new_value): """Sets the current value of the parameter, ensuring that it is within the allowed range.""" if self.min_value is not None and new_value < self.min_value: raise SettingOutOfBounds( "Trying to set parameter {0} = {1}, which is less than the m...
Sets the current value of the parameter, ensuring that it is within the allowed range.
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False): """Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name ...
Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name model_version: depoyed model version cloud: bool. If False, does local prediction and ...
def _get_styles(self, style_urls, asset_url_path): """ Gets the content of the given list of style URLs and inlines assets. """ styles = [] for style_url in style_urls: urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format( asset_url_path.rstrip(...
Gets the content of the given list of style URLs and inlines assets.
def pv_absent(name): ''' Ensure that a Physical Device is not being used by lvm name The device name to initialize. ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if not __salt__['lvm.pvdisplay'](name, quiet=True): ret['c...
Ensure that a Physical Device is not being used by lvm name The device name to initialize.
def make_venv(self, dj_version): """Creates a virtual environment for a given Django version. :param str dj_version: :rtype: str :return: path to created virtual env """ venv_path = self._get_venv_path(dj_version) self.logger.info('Creating virtual environment fo...
Creates a virtual environment for a given Django version. :param str dj_version: :rtype: str :return: path to created virtual env
def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """ wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
Returns the value of the HTTP header identified by `name`.
def execute(self, request): """Execute a request and return a response""" url = request.uri if request.parameters: url += '?' + urlencode(request.parameters) if request.headers: headers = dict(self._headers, **request.headers) else: headers = ...
Execute a request and return a response
def convex_hull_image(image): '''Given a binary image, return an image of the convex hull''' labels = image.astype(int) points, counts = convex_hull(labels, np.array([1])) output = np.zeros(image.shape, int) for i in range(counts[0]): inext = (i+1) % counts[0] draw_line(output, point...
Given a binary image, return an image of the convex hull
def set_speed(self, value): ''' set total axes movement speed in mm/second''' self._combined_speed = float(value) speed_per_min = int(self._combined_speed * SEC_PER_MIN) command = GCODES['SET_SPEED'] + str(speed_per_min) log.debug("set_speed: {}".format(command)) self._se...
set total axes movement speed in mm/second
def dict_to_etree(d, root): u"""Converts a dict to lxml.etree object. >>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS <Element root at 0x...> :param dict d: dict representing the XML tree :param etree.Element root: XML node which will...
u"""Converts a dict to lxml.etree object. >>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS <Element root at 0x...> :param dict d: dict representing the XML tree :param etree.Element root: XML node which will be assigned the resulting tree ...
def main(args=sys.argv[1:]): """Extract text from a file. Commands: extract - extract text from path check - make sure all deps are installed Usage: fulltext extract [-v] [-f] <path>... fulltext check [-t] Options: -f, --file Open file first. ...
Extract text from a file. Commands: extract - extract text from path check - make sure all deps are installed Usage: fulltext extract [-v] [-f] <path>... fulltext check [-t] Options: -f, --file Open file first. -t, --title Check deps fo...
def multi_curve_fit(xs, ys, verbose): """ fit multiple functions to the x, y data, return the best fit """ #functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal} functions = { exponential: p0_exponential, reciprocal: p0_reciproc...
fit multiple functions to the x, y data, return the best fit
def get_channel_id(turn_context: TurnContext) -> str: """Get the Channel Id from the current Activity on the Turn Context. Args: turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from. Returns: str: The Channel Id from the Turn Context's...
Get the Channel Id from the current Activity on the Turn Context. Args: turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from. Returns: str: The Channel Id from the Turn Context's Activity.
def _get_desired_pkg(name, desired): ''' Helper function that retrieves and nicely formats the desired pkg (and version if specified) so that helpful information can be printed in the comment for the state. ''' if not desired[name] or desired[name].startswith(('<', '>', '=')): oper = '' ...
Helper function that retrieves and nicely formats the desired pkg (and version if specified) so that helpful information can be printed in the comment for the state.
def enrich_relations(rdf, enrich_mappings, use_narrower, use_transitive): """Enrich the SKOS relations according to SKOS semantics, including subproperties of broader and symmetric related properties. If use_narrower is True, include inverse narrower relations for all broader relations. If use_narrower ...
Enrich the SKOS relations according to SKOS semantics, including subproperties of broader and symmetric related properties. If use_narrower is True, include inverse narrower relations for all broader relations. If use_narrower is False, instead remove all narrower relations, replacing them with inverse ...
def show_taghistory(): """Show history of all known repo/tags for image""" if not nav: sys.exit(1) ecode = 0 try: result = nav.get_taghistory() if result: anchore_utils.print_result(config, result) except: anchore_print_err("operation failed") ...
Show history of all known repo/tags for image
def toFilter(self, property): """ Convert this range to a Filter with a tests having a given property. """ if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le: # equivalent to == return Filter(style.SelectorAttributeTest(property, '=', self.lef...
Convert this range to a Filter with a tests having a given property.
def _set_get_vnetwork_hosts(self, v, load=False): """ Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_vnetwork_hosts is considered as a private method. B...
Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_vnetwork_hosts is considered as a private method. Backends looking to populate this variable should do so via...
def get_instruction(self, idx, off=None): """ Get a particular instruction by using (default) the index of the address if specified :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of the instruction :t...
Get a particular instruction by using (default) the index of the address if specified :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of the instruction :type off: int :rtype: an :class:`Instruction` object
def get_params_type(descriptor): """ Return the parameters type of a descriptor (e.g (IC)V) """ params = descriptor.split(')')[0][1:].split() if params: return [param for param in params] return []
Return the parameters type of a descriptor (e.g (IC)V)
def _repr_html_(self): """ Return a html representation for a particular DataFrame. Mainly for IPython notebook. """ if self._info_repr(): buf = StringIO("") self.info(buf=buf) # need to escape the <class>, should be the first line. ...
Return a html representation for a particular DataFrame. Mainly for IPython notebook.
def _init_edges_relationships(rel2src2dsts, rel2dst2srcs): """Get the directed edges from GO term to GO term using relationships.""" edge_rel2fromto = {} relationships = set(rel2src2dsts).union(rel2dst2srcs) for reltype in relationships: edge_from_to = [] if relty...
Get the directed edges from GO term to GO term using relationships.
def log_calls(function): ''' Decorator that logs function calls in their self.log ''' def wrapper(self,*args,**kwargs): self.log.log(group=function.__name__,message='Enter') function(self,*args,**kwargs) self.log.log(group=function.__name__,message='Exit') return wrapper
Decorator that logs function calls in their self.log
def line_break(s, length=76): """ 将字符串分割成一行一行 :param s: :param length: :return: """ x = '\n'.join(s[pos:pos + length] for pos in range(0, len(s), length)) return x
将字符串分割成一行一行 :param s: :param length: :return:
def run_sex_check(in_prefix, in_type, out_prefix, base_dir, options): """Runs step6 (sexcheck). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options ...
Runs step6 (sexcheck). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :type in_prefix: str :type in_type: str :type out_prefix...
def restore(name=None, **kwargs): ''' Make sure that the system contains the packages and repos from a frozen state. Read the list of packages and repositories from the freeze file, and compare it with the current list of packages and repos. If there is any difference, all the missing packages ...
Make sure that the system contains the packages and repos from a frozen state. Read the list of packages and repositories from the freeze file, and compare it with the current list of packages and repos. If there is any difference, all the missing packages are repos will be installed, and all the e...
def onReactionRemoved( self, mid=None, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None, ): """ Called when the client is listening, and somebody removes reaction from a message :param mid: Message ID, that user reac...
Called when the client is listening, and somebody removes reaction from a message :param mid: Message ID, that user reacted to :param author_id: The ID of the person who removed reaction :param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads` :param thread_type...
def mimeData( self, items ): """ Returns the mime data for dragging for this instance. :param items | [<QTableWidgetItem>, ..] """ func = self.dataCollector() if ( func ): return func(self, items) return super(XTableWidget, s...
Returns the mime data for dragging for this instance. :param items | [<QTableWidgetItem>, ..]
def messages(self): """ Access the messages :returns: twilio.rest.messaging.v1.session.message.MessageList :rtype: twilio.rest.messaging.v1.session.message.MessageList """ if self._messages is None: self._messages = MessageList(self._version, session_sid=self...
Access the messages :returns: twilio.rest.messaging.v1.session.message.MessageList :rtype: twilio.rest.messaging.v1.session.message.MessageList
def copy(self): """Return a copy where the float usage is hard-coded to mimic the behavior of the real os.stat_result. """ stat_result = copy(self) stat_result.use_float = self.use_float return stat_result
Return a copy where the float usage is hard-coded to mimic the behavior of the real os.stat_result.
def delete_all_objects(self, nms, async_=False): """ Deletes all objects from this container. By default the call will block until all objects have been deleted. By passing True for the 'async_' parameter, this method will not block, and instead return an object that can be used...
Deletes all objects from this container. By default the call will block until all objects have been deleted. By passing True for the 'async_' parameter, this method will not block, and instead return an object that can be used to follow the progress of the deletion. When deletion is com...
def remove(self, key, value): """ Transactional implementation of :func:`MultiMap.remove(key, value) <hazelcast.proxy.multi_map.MultiMap.remove>` :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: ...
Transactional implementation of :func:`MultiMap.remove(key, value) <hazelcast.proxy.multi_map.MultiMap.remove>` :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return:
def create_build_paths(context: Context): """ Creates directories needed for build outputs """ paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path] for path in filter(None, paths): os.makedirs(path, exist_ok=True)
Creates directories needed for build outputs
def lines2mecab(lines, **kwargs): ''' Use mecab to parse many lines ''' sents = [] for line in lines: sent = txt2mecab(line, **kwargs) sents.append(sent) return sents
Use mecab to parse many lines
def aggregate(self, block_size): ''' geo.aggregate(block_size) Returns copy of raster aggregated to smaller resolution, by adding cells. ''' raster2 = block_reduce(self.raster, block_size, func=np.ma.sum) geot = self.geot geot = (geot[0], block_size[0] * geot[1],...
geo.aggregate(block_size) Returns copy of raster aggregated to smaller resolution, by adding cells.
def list_port_fwd(zone, permanent=True): ''' List port forwarding .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.list_port_fwd public ''' ret = [] cmd = '--zone={0} --list-forward-ports'.format(zone) if permanent: cmd += ' --perm...
List port forwarding .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.list_port_fwd public
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port): """Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a series product self-feedback. """ _, block_index = rhs.index_in_block(in_port) rest = tuple(rest) bs = rhs.block_structure (nbefore, nblock, nafter) = ...
Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a series product self-feedback.
def configure_logging(level): """ Configure global log level to given one :param level: Level (INFO | DEBUG | WARN | ERROR) :return: """ global logging_level logging_level = logging.ERROR if "info" == level.lower(): logging_level = logging.INFO elif "warn" == level.lower(): ...
Configure global log level to given one :param level: Level (INFO | DEBUG | WARN | ERROR) :return:
def _get_grammar_errors(self,pos,text,tokens): """ Internal function to get the number of grammar errors in given text pos - part of speech tagged text (list) text - normal text (list) tokens - list of lists of tokenized text """ word_counts = [max(len(t),1) for t...
Internal function to get the number of grammar errors in given text pos - part of speech tagged text (list) text - normal text (list) tokens - list of lists of tokenized text
def render_xml_to_string(template, input, params=None): """ Transforms ``input`` using ``template``, which should be an xslt. :param template: an xslt template name. :param input: an string that contains xml :param params: A dictionary containing xslt parameters. Use :func:`~easymode.xslt.prepa...
Transforms ``input`` using ``template``, which should be an xslt. :param template: an xslt template name. :param input: an string that contains xml :param params: A dictionary containing xslt parameters. Use :func:`~easymode.xslt.prepare_string_param`\ on strings you want to pass in. :rtype...
def load_locale(locale, icu=False): """ Return data of locale :param locale: :return: """ if locale not in locales: raise NotImplementedError("The locale '%s' is not supported" % locale) if locale not in __locale_caches: mod = __import__(__name__, fromlist=[locale], level=0) ...
Return data of locale :param locale: :return:
def _compute_f3(self, C, mag): """ Compute f3 term (eq.6, page 106) NOTE: In the original manuscript, for the case 5.8 < mag < c1, the term in the numerator '(mag - 5.8)' is missing, while is present in the software used for creating the verification tables """ i...
Compute f3 term (eq.6, page 106) NOTE: In the original manuscript, for the case 5.8 < mag < c1, the term in the numerator '(mag - 5.8)' is missing, while is present in the software used for creating the verification tables
def size(self): """Total number of grid points.""" # Since np.prod(()) == 1.0 we need to handle that by ourselves return (0 if self.shape == () else int(np.prod(self.shape, dtype='int64')))
Total number of grid points.
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
A page with number of services and layers faceted on domains.
def data_vector_from_blurred_mapping_matrix_and_data(blurred_mapping_matrix, image_1d, noise_map_1d): """Compute the hyper vector *D* from a blurred mapping matrix *f* and the 1D image *d* and 1D noise-map *\sigma* \ (see Warren & Dye 2003). Parameters ----------- blurred_mapping_matrix : ndarr...
Compute the hyper vector *D* from a blurred mapping matrix *f* and the 1D image *d* and 1D noise-map *\sigma* \ (see Warren & Dye 2003). Parameters ----------- blurred_mapping_matrix : ndarray The matrix representing the blurred mappings between sub-grid pixels and pixelization pixels. ...
def dump(self): """Return dictionary with current statistical information""" data = dict( # Sessions sessions_active=self.sess_active, # Connections connections_active=self.conn_active, connections_ps=self.conn_ps.last_average, # ...
Return dictionary with current statistical information
def DeserializeTX(buffer): """ Deserialize the stream into a Transaction object. Args: buffer (BytesIO): stream to deserialize the Transaction from. Returns: neo.Core.TX.Transaction: """ mstream = MemoryStream(buffer) reader = BinaryReade...
Deserialize the stream into a Transaction object. Args: buffer (BytesIO): stream to deserialize the Transaction from. Returns: neo.Core.TX.Transaction:
def reserve(self, location=None, force=False, wait_for_up=True, timeout=80): """ Reserve port and optionally wait for port to come up. :param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration. :param force: whether to revoke existing reserva...
Reserve port and optionally wait for port to come up. :param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration. :param force: whether to revoke existing reservation (True) or not (False). :param wait_for_up: True - wait for port to come up, ...
def enable_contactgroup_svc_notifications(self, contactgroup): """Enable service notifications for a contactgroup Format of the line that triggers function call:: ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name> :param contactgroup: contactgroup to enable :type contact...
Enable service notifications for a contactgroup Format of the line that triggers function call:: ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name> :param contactgroup: contactgroup to enable :type contactgroup: alignak.objects.contactgroup.Contactgroup :return: None
def read_dependencies(filename): """Read in the dependencies from the virtualenv requirements file. """ dependencies = [] filepath = os.path.join('requirements', filename) with open(filepath, 'r') as stream: for line in stream: package = line.strip().split('#')[0].strip() ...
Read in the dependencies from the virtualenv requirements file.
def run(self): ''' run all patterns in the playbook ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): ...
run all patterns in the playbook
def write(self, handle): """Write metadata to handle.""" handle.write(u"\t".join(self.columns)) handle.write(u"\n") for row in self.rows: row.write(handle)
Write metadata to handle.
def read(self): """ Read one character from buffer. :Returns: Current character or None if end of buffer is reached """ if self._current >= len(self._data): return None self._current += 1 return self._data[self._current - 1]
Read one character from buffer. :Returns: Current character or None if end of buffer is reached
def pool_function(args): """ A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the ...
A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the verification was ended succes...
def pixel_to_q(self, row: float, column: float): """Return the q coordinates of a given pixel. Inputs: row: float the row (vertical) coordinate of the pixel column: float the column (horizontal) coordinate of the pixel Coordinates are 0-b...
Return the q coordinates of a given pixel. Inputs: row: float the row (vertical) coordinate of the pixel column: float the column (horizontal) coordinate of the pixel Coordinates are 0-based and calculated from the top left corner.
def collapse(self, msgpos): """collapse message at given position""" MT = self._tree[msgpos] MT.collapse(MT.root) self.focus_selected_message()
collapse message at given position
def _cas_2(self): ''' Longitude overlap (2 images). ''' lonc_left = self._format_lon(self.lonm) lonc_right = self._format_lon(self.lonM) latc = self._format_lat(self.latm) print(lonc_left, lonc_right, self.lonm, self.lonM) img_name_left = self._format_name_map(lonc_left...
Longitude overlap (2 images).
def _make_return_edges(self): """ For each returning function, create return edges in self.graph. :return: None """ for func_addr, func in self.functions.items(): if func.returning is False: continue # get the node on CFG if ...
For each returning function, create return edges in self.graph. :return: None
def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd...
Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task()
def dict_table(cls, d, order=None, header=None, sort_keys=True, show_none="", max_width=40): """prints a pretty table from an dict of dicts :param d: A a dict with dicts of the same type. ...
prints a pretty table from an dict of dicts :param d: A a dict with dicts of the same type. Each key will be a column :param order: The order in which the columns are printed. The order is specified by the key names of the dict. :param header: The Hea...
def edge_betweenness_bin(G): ''' Edge betweenness centrality is the fraction of all shortest paths in the network that contain a given edge. Edges with high values of betweenness centrality participate in a large number of shortest paths. Parameters ---------- A : NxN np.ndarray bin...
Edge betweenness centrality is the fraction of all shortest paths in the network that contain a given edge. Edges with high values of betweenness centrality participate in a large number of shortest paths. Parameters ---------- A : NxN np.ndarray binary directed/undirected connection matrix...
def check(self, src_tgt, actual_deps): """Check for missing deps. See docstring for _compute_missing_deps for details. """ if self._check_missing_direct_deps or self._check_unnecessary_deps: missing_file_deps, missing_direct_tgt_deps = \ self._compute_missing_deps(src_tgt, actual_deps) ...
Check for missing deps. See docstring for _compute_missing_deps for details.
def returner(ret): ''' Send an slack message with the data ''' _options = _get_options(ret) channel = _options.get('channel') username = _options.get('username') as_user = _options.get('as_user') api_key = _options.get('api_key') changes = _options.get('changes') only_show_fail...
Send an slack message with the data
async def rows(self, offs, size=None, iden=None): ''' Yield a number of raw items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number of items to yield. Yields: ((ind...
Yield a number of raw items from the CryoTank starting at a given offset. Args: offs (int): The index of the desired datum (starts at 0) size (int): The max number of items to yield. Yields: ((indx, bytes)): Index and msgpacked bytes.
def sponsor_image_url(sponsor, name): """Returns the corresponding url from the sponsors images""" if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url retu...
Returns the corresponding url from the sponsors images
def get_auth(self): """ This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: """ url = self.h_url + self.server + ":" + self.port auth = requests.auth.HTTPDigestAuth(self.username,self.password) auth_url...
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return:
def run_job(self, section_id, session=None): # type: (Text, Optional[Session]) -> None """Run a job as described in the section named ``section_id``. Raises: KeyError: when the section could not be found. """ if not self.parser.has_section(section_id): r...
Run a job as described in the section named ``section_id``. Raises: KeyError: when the section could not be found.
def parse_events(content, start=None, end=None, default_span=timedelta(days=7)): """ Query the events occurring in a given time range. :param content: iCal URL/file content as String :param start: start date for search, default today :param end: end date for search :param default_span: default ...
Query the events occurring in a given time range. :param content: iCal URL/file content as String :param start: start date for search, default today :param end: end date for search :param default_span: default query length (one week) :return: events as list
def send(self, *args, **kwargs): """Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns.""" conn = SMTP(*args, **kw...
Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns.
def displayText(self, value, blank='', joiner=', '): """ Returns the display text for the value associated with the inputted text. This will result in a comma separated list of labels for the value, or the blank text provided if no text is found. :param val...
Returns the display text for the value associated with the inputted text. This will result in a comma separated list of labels for the value, or the blank text provided if no text is found. :param value | <variant> blank | <str> jo...
def _kmp_construct_next(self, pattern): """the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern.""" next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP] ...
the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern.
def open_addnew_win(self, *args, **kwargs): """Open a new window so the use can choose to add new reftracks :returns: None :rtype: None :raises: NotImplementedError """ if self.reftrackadderwin: self.reftrackadderwin.close() self.reftrackadderwin = Re...
Open a new window so the use can choose to add new reftracks :returns: None :rtype: None :raises: NotImplementedError
def delete_nsg(access_token, subscription_id, resource_group, nsg_name): '''Delete network security group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str):...
Delete network security group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the NSG. Returns: HTTP response.
def load_datafile(self, name, search_path=None, **kwargs): """ find datafile and load them from codec """ if not search_path: search_path = self.define_dir self.debug_msg('loading datafile %s from %s' % (name, str(search_path))) return codec.load_datafile(nam...
find datafile and load them from codec
def stopContext(self, context): """Clear the database if so configured for this """ # Use pymongo directly to drop all collections of created db if ((self.clear_context['module'] and inspect.ismodule(context)) or (self.clear_context['class'] and inspect.isclass(context))): ...
Clear the database if so configured for this
def copy_ssh_keys_to_host(self, host, password=None, no_add_host=False, known_hosts=DEFAULT_KNOWN_HOSTS): """ Copy the SSH keys to the given host. :param host: the `Host` object to copy the SSH keys to. :param password: the SSH password for the given host. :param no_add_host: if...
Copy the SSH keys to the given host. :param host: the `Host` object to copy the SSH keys to. :param password: the SSH password for the given host. :param no_add_host: if the host is not in the known_hosts file, write an error instead of adding it to the known_hosts. ...
def is_admin(self): """Is the user a system administrator""" return self.role == self.roles.administrator.value and self.state == State.approved
Is the user a system administrator
def add_sma(self,periods=20,column=None,name='', str=None,**kwargs): """ Add Simple Moving Average (SMA) study to QuantFigure.studies Parameters: periods : int or list(int) Number of periods column :string Defines the data column name that contains the data over which the study will be ap...
Add Simple Moving Average (SMA) study to QuantFigure.studies Parameters: periods : int or list(int) Number of periods column :string Defines the data column name that contains the data over which the study will be applied. Default: 'close' name : string Name given to the study str :...
def dmrs_tikz_dependency(xs, **kwargs): """ Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs. DMRSs use the `tikz-dependency` package for visualization. """ def link_label(link): return '{}/{}'.format(link.rargname or '', link.post) def label_edge(link): if link...
Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs. DMRSs use the `tikz-dependency` package for visualization.
def update_reflexrules_workflow_state(portal): """ Updates Reflex Rules' inactive_state, otherwise they don't have it by default. :param portal: Portal object :return: None """ wf_tool = getToolByName(portal, 'portal_workflow') logger.info("Updating Reflex Rules' 'inactive_state's...") ...
Updates Reflex Rules' inactive_state, otherwise they don't have it by default. :param portal: Portal object :return: None
def callback(self, request, **kwargs): """ Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template """ access_token = Pocket.get_access_token(consumer_ke...
Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template
def name(self): ''' Returns the name of the current :py:class:`Detrender` subclass. ''' if self.cadence == 'lc': return self.__class__.__name__ else: return '%s.sc' % self.__class__.__name__
Returns the name of the current :py:class:`Detrender` subclass.
def getStates(self): """Get all :class:`rtcclient.models.State` objects of this workitem :return: a :class:`list` contains all the :class:`rtcclient.models.State` objects :rtype: list """ cust_attr = (self.raw_data.get("rtc_cm:state") .get("...
Get all :class:`rtcclient.models.State` objects of this workitem :return: a :class:`list` contains all the :class:`rtcclient.models.State` objects :rtype: list
def parents(self, resources): """ Split the path in name and get parents """ if self.docname == 'index': # The root has no parents return [] parents = [] parent = resources.get(self.parent) while parent is not None: parents.append(parent) ...
Split the path in name and get parents
def send_workflow(self): """ With the workflow instance and the task invitation is assigned a role. """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance select_role = self.input['form']['select_role'] if wfi.cur...
With the workflow instance and the task invitation is assigned a role.
def uriref_matches_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool: """ Compare :py:class:`rdflib.URIRef` value with :py:class:`ShExJ.IRIREF` value """ return str(v1) == str(v2)
Compare :py:class:`rdflib.URIRef` value with :py:class:`ShExJ.IRIREF` value
async def load_cache(self, archive: bool = False) -> int: """ Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :re...
Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :return: cache load event timestamp (epoch seconds)
def _check_fields(self, x, y): """ Check x and y fields parameters and initialize """ if x is None: if self.x is None: self.err( self._check_fields, "X field is not set: please specify a parameter") return x = self.x if y is None: if self.y is None: self.err( self._check_fi...
Check x and y fields parameters and initialize
def validate(self, value, validator): """Validates and returns the value. If the value does not validate against the schema, SchemaValidationError will be raised. :param value: A value to validate (usually a dict). :param validator: An instance of a jsonschema validator class, ...
Validates and returns the value. If the value does not validate against the schema, SchemaValidationError will be raised. :param value: A value to validate (usually a dict). :param validator: An instance of a jsonschema validator class, as created by Schema.get_validator()....
def _get_goroot(self, goids_all, namespace): """Get the top GO for the set of goids_all.""" root_goid = self.consts.NAMESPACE2GO[namespace] if root_goid in goids_all: return root_goid root_goids = set() for goid in goids_all: goterm = self.gosubdag.go2obj[...
Get the top GO for the set of goids_all.