code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def calculate(self, T, method): r'''Method to calculate surface tension of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at whi...
r'''Method to calculate surface tension of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate surface tension, [K] ...
def update_org_users(cls, module): """ Adds the `user` field to the organization user model and the link to the specific organization model. """ try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("user") except FieldDoesNotExist: cls....
Adds the `user` field to the organization user model and the link to the specific organization model.
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): """ Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_mi...
Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_min (bool): True to find local minimum else maximum, otherwise find local maximum. min_dist (float): The minimum distance (in Angstrom) that ...
def get_dashboard_tags(self, id, **kwargs): # noqa: E501 """Get all tags associated with a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api....
Get all tags associated with a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_dashboard_tags(id, async_req=True) >>> result = thread.ge...
def regular_generic_msg(hostname, result, oneline, caption): ''' output on the result of a module run that is not command ''' if not oneline: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True)) else: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(...
output on the result of a module run that is not command
def plot_networkx(network, plot_throats=True, labels=None, colors=None, scale=10): r''' Returns a pretty 2d plot for 2d OpenPNM networks. Parameters ---------- network : OpenPNM Network object plot_throats : boolean Plots throats as well as pores, if True. labels...
r''' Returns a pretty 2d plot for 2d OpenPNM networks. Parameters ---------- network : OpenPNM Network object plot_throats : boolean Plots throats as well as pores, if True. labels : list List of OpenPNM labels colors : list List of corresponding colors to the giv...
def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def =...
Run the pruned and frozen inference graph.
def contourInside(self, otherContour): """ Determine if ``otherContour`` is in the black or white of this contour. >>> contour.contourInside(otherContour) True ``contour`` must be a :class:`BaseContour`. """ otherContour = normalizers.normalizeContour(ot...
Determine if ``otherContour`` is in the black or white of this contour. >>> contour.contourInside(otherContour) True ``contour`` must be a :class:`BaseContour`.
def has_causal_in_edges(graph: BELGraph, node: BaseEntity) -> bool: """Return true if the node contains any in_edges that are causal.""" return any( data[RELATION] in CAUSAL_RELATIONS for _, _, data in graph.in_edges(node, data=True) )
Return true if the node contains any in_edges that are causal.
def to_representation(self, instance): """Modified to_representation method. Optionally may cache objects. Arguments: instance: A model instance or data object. Returns: Instance ID if the serializer is meant to represent its ID. Otherwise, a tagged data dict...
Modified to_representation method. Optionally may cache objects. Arguments: instance: A model instance or data object. Returns: Instance ID if the serializer is meant to represent its ID. Otherwise, a tagged data dict representation.
def _compose_pair(self, role, base): ''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname...
composes onto base by applying the role
def mail_handler(self, punchline=None, add_meta=False, add_settings=True, *args, **kwargs): ''' :param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: ...
:param punchline: Adds a punchline before further text :param add_meta: Appends current meta to the mail :param add_settings: Appends current settings to the mail :returns: A new mail handler .. seealso:: :ref:`tools_mail`
def read_flags_from_files(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that...
Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. ...
def _computeInferenceMode(self, feedforwardInput, lateralInputs): """ Inference mode: if there is some feedforward activity, perform spatial pooling on it to recognize previously known objects, then use lateral activity to activate a subset of the cells with feedforward support. If there is no feedf...
Inference mode: if there is some feedforward activity, perform spatial pooling on it to recognize previously known objects, then use lateral activity to activate a subset of the cells with feedforward support. If there is no feedforward activity, use lateral activity to activate a subset of the previous...
def write_cron_file(user, path): ''' Writes the contents of a file to a user's crontab CLI Example: .. code-block:: bash salt '*' cron.write_cron_file root /tmp/new_cron .. versionchanged:: 2015.8.9 .. note:: Some OS' do not support specifying user via the `crontab` command...
Writes the contents of a file to a user's crontab CLI Example: .. code-block:: bash salt '*' cron.write_cron_file root /tmp/new_cron .. versionchanged:: 2015.8.9 .. note:: Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
def to_yellow(self, on: bool=False): """ Change the LED to yellow (on or off) :param on: True or False :return: None """ self._on = on if on: self._load_new(led_yellow_on) if self._toggle_on_click: self._canvas.bind('<Butto...
Change the LED to yellow (on or off) :param on: True or False :return: None
def fitness(self, width, height): """ In guillotine algorithm case, returns the min of the fitness of all free sections, for the given dimension, both normal and rotated (if rotation enabled.) """ assert(width > 0 and height > 0) # Get best fitness section. ...
In guillotine algorithm case, returns the min of the fitness of all free sections, for the given dimension, both normal and rotated (if rotation enabled.)
def _add_ideal_atomic_weights_(elemental_array): """ Uses elements.json to find the molar mass of the element in question, and then multiplies that by the occurances of the element. Adds the "weight" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionarie...
Uses elements.json to find the molar mass of the element in question, and then multiplies that by the occurances of the element. Adds the "weight" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionaries containing information about the elements in the system ...
def _get_SConscript_filenames(self, ls, kw): """ Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is...
Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is a list of exports.
def suffix(transformers, default=None): """Returns a different transformer depending on the suffix at the end of the requested URL. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[suffix]': transformation_action, ...
Returns a different transformer depending on the suffix at the end of the requested URL. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[suffix]': transformation_action, ... }
def visit_str(self, node, _): """Regex rule for quoted string allowing escaped quotes inside. Arguments --------- node : parsimonious.nodes.Node. _ (children) : list, unused Result ------ str The wanted string, with quoted characters unquoted...
Regex rule for quoted string allowing escaped quotes inside. Arguments --------- node : parsimonious.nodes.Node. _ (children) : list, unused Result ------ str The wanted string, with quoted characters unquoted. Example ------- ...
def get_pyof_version(module_fullname): """Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow ver...
Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow version, on the format 'v0x0?' if any. Or None ...
def delete_assets(self, service_id, url=None, all=False): """Delete CDN assets Arguments: service_id: The ID of the service to delete from. url: The URL at which to delete assets all: When True, delete all assets associated with the service_id. You cannot specifiy both ...
Delete CDN assets Arguments: service_id: The ID of the service to delete from. url: The URL at which to delete assets all: When True, delete all assets associated with the service_id. You cannot specifiy both url and all.
def predictions(self, route=''): """ Yields predicted bus ETAs for this stop. You can specify a route identifier for ETAs specific to one route, or leave `route` blank (done by default) to get information on all arriving busses. """ apiresponse = self.api.predictions...
Yields predicted bus ETAs for this stop. You can specify a route identifier for ETAs specific to one route, or leave `route` blank (done by default) to get information on all arriving busses.
def _get_pdf_list(self, input_pdfs): """ Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths ...
Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths
def _cond_s(self, word, suffix_len): """Return Lovins' condition S. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met """ retur...
Return Lovins' condition S. Parameters ---------- word : str Word to check suffix_len : int Suffix length Returns ------- bool True if condition is met
def generate_sbi_config(num_pbs: int = 3, project: str = 'sip', programme_block: str = 'sip_demos', pb_config: Union[dict, List[dict]] = None, workflow_config: Union[dict, List[dict]] = None, register...
Generate a SBI configuration dictionary. Args: num_pbs (int, optional): Number of Processing Blocks (default = 3) project (str, optional): Project to associate the SBI with. programme_block (str, optional): SBI programme block pb_config (dict, List[dict], optional): PB configuration...
async def fetch(self, n, *, timeout=None): r"""Return the next *n* rows as a list of :class:`Record` objects. :param float timeout: Optional timeout value in seconds. :return: A list of :class:`Record` instances. """ self._check_ready() if n <= 0: raise exce...
r"""Return the next *n* rows as a list of :class:`Record` objects. :param float timeout: Optional timeout value in seconds. :return: A list of :class:`Record` instances.
def dependencyOrder(aMap, aList = None): """ Given descriptions of dependencies in aMap and an optional list of items in aList if not aList, aList = aMap.keys() Returns a list containing each element of aList and all its precursors so that every precursor of any element in the returned list is seen before tha...
Given descriptions of dependencies in aMap and an optional list of items in aList if not aList, aList = aMap.keys() Returns a list containing each element of aList and all its precursors so that every precursor of any element in the returned list is seen before that dependent element. If aMap contains cycles, s...
def on_menu(self, event): '''handle menu selections''' state = self.state ret = self.menu.find_selected(event) if ret is None: return ret.call_handler() state.child_pipe_send.send(ret)
handle menu selections
def authenticate(self, *args, **kwargs): ''' Authenticate the user agains LDAP ''' # Get config username = kwargs.get("username", None) password = kwargs.get("password", None) # Check user in Active Directory (authorization == None if can not connect to Active D...
Authenticate the user agains LDAP
def _create_tree(self, endpoint=None, index=0): """ This will return a string of the endpoint tree structure :param endpoint: Endpoint's Current path of the source :param index: int number of tabs to space over :return: str """ tab = '' # '\t' * index ret...
This will return a string of the endpoint tree structure :param endpoint: Endpoint's Current path of the source :param index: int number of tabs to space over :return: str
def build_params(self, params={}): """ build a params dictionary with current editId and packageName. use optional params parameter to merge additional params into resulting dictionary. """ z = params.copy() z.update({'editId': self.edit_id, 'packageName': self.p...
build a params dictionary with current editId and packageName. use optional params parameter to merge additional params into resulting dictionary.
def connect(self, host, port=1883, keepalive=60, bind_address=""): """Connect to a remote broker. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 888...
Connect to a remote broker. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you are using tls_set() the port may need providing. k...
def update_config(self, config_dict, config_file): """Update the content and reference of the config :param dict config_dict: The new configuration :param str config_file: The new file reference """ config_path = path.dirname(config_file) self.config.config_file_path = c...
Update the content and reference of the config :param dict config_dict: The new configuration :param str config_file: The new file reference
def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str): """ Download the latest prices """ if help: click.echo(ctx.get_help()) ctx.exit() app = PriceDbApplication() app.logger = logger if currency: currency = currency.strip() currency ...
Download the latest prices
def token(self): """ Returns the next LexToken. Returns None when all tokens have been exhausted. """ if self.tokens_queue: self.last_token = self.tokens_queue.pop(0) else: r = self.lex.token() if isinstance(r, MultiToken): ...
Returns the next LexToken. Returns None when all tokens have been exhausted.
def set_simple_func(self, func, args=()): """Set the model function to use a simple but somewhat inefficient calling convention. The function should obey the following convention:: def func(param0, param1, ..., paramN, *args): modeled_data = { do something using the...
Set the model function to use a simple but somewhat inefficient calling convention. The function should obey the following convention:: def func(param0, param1, ..., paramN, *args): modeled_data = { do something using the parameters } return modeled_data ...
def methodcall(self, methodname, localobject, Params=None, **params): """ **Deprecated:** Low-level method used by the :meth:`~pywbem.WBEMConnection.InvokeMethod` method of this class. *Deprecated since pywbem 0.12.* Calling this function directly has been deprecated and will i...
**Deprecated:** Low-level method used by the :meth:`~pywbem.WBEMConnection.InvokeMethod` method of this class. *Deprecated since pywbem 0.12.* Calling this function directly has been deprecated and will issue a :term:`DeprecationWarning`. Users should call :meth:`~pywbem.WBEMCo...
def get_time_server(): ''' Display the currently set network time server. :return: the network time server :rtype: str CLI Example: .. code-block:: bash salt '*' timezone.get_time_server ''' ret = salt.utils.mac_utils.execute_return_result( 'systemsetup -getnetworktim...
Display the currently set network time server. :return: the network time server :rtype: str CLI Example: .. code-block:: bash salt '*' timezone.get_time_server
def get(self, key): """ Returns the value for the specified key, or None if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** ...
Returns the value for the specified key, or None if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** :param key: (object), the specified...
def kill(self, detach=False): """This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace....
This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace.disconnect` methods so that you c...
def _list_tenants(self, admin): """ Returns either a list of all tenants (admin=True), or the tenant for the currently-authenticated user (admin=False). """ resp, resp_body = self.method_get("tenants", admin=admin) if 200 <= resp.status_code < 300: tenants = r...
Returns either a list of all tenants (admin=True), or the tenant for the currently-authenticated user (admin=False).
def allzeros(msg): """check if the data bits are all zeros Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ d = hex2bin(data(msg)) if bin2int(d) > 0: return False else: return True
check if the data bits are all zeros Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
def diff_move(self,v,new_comm): """ Calculate the difference in the quality function if node ``v`` is moved to community ``new_comm``. Parameters ---------- v The node to move. new_comm The community to move to. Returns ------- float Difference in quality functio...
Calculate the difference in the quality function if node ``v`` is moved to community ``new_comm``. Parameters ---------- v The node to move. new_comm The community to move to. Returns ------- float Difference in quality function. Notes ----- The differen...
def request_anime(aid: int) -> 'Anime': """Make an anime API request.""" anime_info = alib.request_anime(_CLIENT, aid) return Anime._make(anime_info)
Make an anime API request.
def configure_hipchat_logger( self, hipchat_webhook=None, log_level='ERROR', log_format=ReportingFormats.PRETTY_PRINT.value, custom_args='' ): """logger for sending messages to HipChat. Easy way to alert humans of issues Note: ...
logger for sending messages to HipChat. Easy way to alert humans of issues Note: Will try to overwrite minimum log level to enable requested log_level Will warn and not attach hipchat logger if missing webhook key Learn more about webhooks: https://yak.crowdstrike.com/addon...
def c_getprocs(self): """Get the getprocs of the module.""" getprocs = [] for name, dummy_args in self.funcs: if name == 'GetProcAddress': if callable(self.opts.hash_func): continue getter = 'get_proc_by_string' elif sel...
Get the getprocs of the module.
def synthesize(self, duration, tick_frequency): """ Synthesize periodic "ticks", generated from white noise and an envelope Args: duration (numpy.timedelta64): The total duration of the sound to be synthesized tick_frequency (numpy.timedelta64): The frequ...
Synthesize periodic "ticks", generated from white noise and an envelope Args: duration (numpy.timedelta64): The total duration of the sound to be synthesized tick_frequency (numpy.timedelta64): The frequency of the ticking sound
def _read(self, limit=1000): '''Return all the responses read''' # It's important to know that it may return no responses or multiple # responses. It depends on how the buffering works out. First, read from # the socket for sock in self.socket(): if sock is None: ...
Return all the responses read
def right_margin(self, margin): '''Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter ''' if margin >=...
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
def renderHTTP(self, context): """ Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS. """ if getattr(self.wrappedResource, 'needsSecure', False): ...
Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS.
def item(self, item, option=None, **kw): """ Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the co...
Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by `kw`. :param ...
def getnodes(fnods, up=None, verbose=False): """ Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0),...
Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0), (-2.0, 0.0, -2.0), (-2.0, 2.0, 0.0), (0.0, 2.0, -2.0), (...
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
def extract_minors_from_setup_py(filename_setup_py): '''Extract supported python minor versions from setup.py and return them as a list of str. Return example: ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6'] ''' # eg: minors_str = '2.6\n2.7\n3.3\n3.4\n3.5\n3.6' minors_str = fabric.api.local...
Extract supported python minor versions from setup.py and return them as a list of str. Return example: ['2.6', '2.7', '3.3', '3.4', '3.5', '3.6']
def read_stream(self, file: IO, data_stream: DataStream) -> Reply: '''Read from the data stream. Args: file: A destination file object or a stream writer. data_stream: The stream of which to read from. Coroutine. Returns: Reply: The final reply. ...
Read from the data stream. Args: file: A destination file object or a stream writer. data_stream: The stream of which to read from. Coroutine. Returns: Reply: The final reply.
def make_key(self, *parts): """Generate a namespaced key for the given path.""" separator = getattr(self.model_class, 'index_separator', '.') parts = map(decode, parts) return '%s%s' % (self._base_key, separator.join(map(str, parts)))
Generate a namespaced key for the given path.
def as_df(): """Return a dataframe of isotopes.""" records = [] for sym, ele in vars(_this).items(): if sym not in ["Element", "Isotope"] and not sym.startswith("_"): for k, v in vars(ele).items(): if k.startswith("_") and k[1].isdigit(): records.appen...
Return a dataframe of isotopes.
def create_user(resource_root, username, password, roles): """ Create a user. @param resource_root: The root Resource object @param username: Username @param password: Password @param roles: List of roles for the user. This should be [] or ['ROLE_USER'] for a regular user, ['ROLE_ADMIN'] fo...
Create a user. @param resource_root: The root Resource object @param username: Username @param password: Password @param roles: List of roles for the user. This should be [] or ['ROLE_USER'] for a regular user, ['ROLE_ADMIN'] for an admin, or ['ROLE_LIMITED'] for a limited admin...
def set_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """ Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=['slug'])
Create a slug for each Work already in the DB.
def handle(self, site=None, **options): """ Export pages in JSON format. Site may be specified by id or domain. Default: export pages from the current site specified by settings.SITE_ID. """ if options['all_sites']: monkeypatch_remove_pages_site_restrictions() ...
Export pages in JSON format. Site may be specified by id or domain. Default: export pages from the current site specified by settings.SITE_ID.
def acquire(self, blocking=True): """ Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False. """ slee...
Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False.
def get(_class, api, rt): """ Return a Route object for route `rt` using API instance `api`. """ if not _class.all_routes: _class.all_routes = _class.update_list(api, api.routes()['route']) return _class.all_routes[str(rt)]
Return a Route object for route `rt` using API instance `api`.
def tear_down(self): """ Tears down all temp files and directories. """ while len(self._temp_directories) > 0: directory = self._temp_directories.pop() shutil.rmtree(directory, ignore_errors=True) while len(self._temp_files) > 0: file = self._t...
Tears down all temp files and directories.
def sorted_dependencies(dist, reverse=False): """ Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, ...
Extract all underlying dependencies from a distribution sorted topologically. Uses depth-first algorithm. See more here: Args: dist (Dist): Distribution to extract dependencies from. reverse (bool): If True, place dependencies in reverse order. Returns: ...
def camelcase_to_underline(param_dict): """ 将驼峰命名的参数字典键转换为下划线参数 :param: * param_dict: (dict) 请求参数字典 :return: * temp_dict: (dict) 转换后的参数字典 举例如下:: print('--- transform_hump_to_underline demo---') hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right...
将驼峰命名的参数字典键转换为下划线参数 :param: * param_dict: (dict) 请求参数字典 :return: * temp_dict: (dict) 转换后的参数字典 举例如下:: print('--- transform_hump_to_underline demo---') hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right_name': 'name'} underline_param_dict = trans...
def insert (self, properties, value): """ Associate value with properties. """ assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
Associate value with properties.
def save_users(users, path=settings.LOGIN_FILE): """ Save dictionary with user data to passwd file (default :attr:`ftp.settings.LOGIN_FILE`). Args: users (dict): dictionary with user data. For details look at dict returned from :func:`load_users`. path (str, defaul...
Save dictionary with user data to passwd file (default :attr:`ftp.settings.LOGIN_FILE`). Args: users (dict): dictionary with user data. For details look at dict returned from :func:`load_users`. path (str, default settings.LOGIN_FILE): path of the file, where the ...
def score_large_straight_yatzy(dice: List[int]) -> int: """ Large straight scoring according to yatzy rules """ dice_set = set(dice) if _are_two_sets_equal({2, 3, 4, 5, 6}, dice_set): return sum(dice) return 0
Large straight scoring according to yatzy rules
def dehydrate(self, comp, broker): """ Saves a component in the given broker to the file system. """ if not self.meta_data: raise Exception("Hydration meta_path not set. Can't dehydrate.") if not self.created: fs.ensure_path(self.meta_data, mode=0o770) ...
Saves a component in the given broker to the file system.
def collections(context): """Show all collections in the database""" LOG.info("Running scout view collections") adapter = context.obj['adapter'] for collection_name in adapter.collections(): click.echo(collection_name)
Show all collections in the database
def special_typechecking(value, msg): """ Special Typechecking not available via protocol itself :param value: <dict> :param msg: <proto object> :return: <bool> """ result = True if msg.DESCRIPTOR.name == TARGET: result &= special_target_typecheck(value) elif msg.DESCRIPTOR.n...
Special Typechecking not available via protocol itself :param value: <dict> :param msg: <proto object> :return: <bool>
def buildData(self, key, default=None): """ Returns the build information for the given key. :param key | <str> default | <variant> :return <variant> """ return self._buildData.get(nativestring(key), default)
Returns the build information for the given key. :param key | <str> default | <variant> :return <variant>
def create_snapshot_chart(self, filename=''): """ Create chart that depicts the memory allocation over time apportioned to the tracked classes. """ try: from pylab import figure, title, xlabel, ylabel, plot, fill, legend, savefig import matplotlib.mlab as ...
Create chart that depicts the memory allocation over time apportioned to the tracked classes.
def invoke_hook_bolt_execute(self, heron_tuple, execute_latency_ns): """invoke task hooks for every time bolt processes a tuple :type heron_tuple: HeronTuple :param heron_tuple: tuple that is executed :type execute_latency_ns: float :param execute_latency_ns: execute latency in nano seconds """...
invoke task hooks for every time bolt processes a tuple :type heron_tuple: HeronTuple :param heron_tuple: tuple that is executed :type execute_latency_ns: float :param execute_latency_ns: execute latency in nano seconds
def parse_env_var(s): """Parse an environment variable string Returns a key-value tuple Apply the same logic as `docker run -e`: "If the operator names an environment variable without specifying a value, then the current value of the named variable is propagated into the container's environmen...
Parse an environment variable string Returns a key-value tuple Apply the same logic as `docker run -e`: "If the operator names an environment variable without specifying a value, then the current value of the named variable is propagated into the container's environment
def run(self): """ Process all callbacks, until `stop()` is called. Intended to run in its own thread. """ while True: msg = self._queue.get() if msg is _SHUTDOWN: break event, args, kwargs = msg self._logger('<< %s'...
Process all callbacks, until `stop()` is called. Intended to run in its own thread.
def execute(opts, data, func, args, kwargs): ''' Splay a salt function call execution time across minions over a number of seconds (default: 300) .. note:: You *probably* want to use --async here and look up the job results later. If you're dead set on getting the output from the CLI co...
Splay a salt function call execution time across minions over a number of seconds (default: 300) .. note:: You *probably* want to use --async here and look up the job results later. If you're dead set on getting the output from the CLI command, then make sure to set the timeout (with th...
def export(self, location): """ Export the Bazaar repository at the url to the destination location """ temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) if os.path.exists(location): # Remove the location to make sure Bazaar can export it co...
Export the Bazaar repository at the url to the destination location
def connected_component(self, ident): '''Return a connected component generator for ``ident``. ``ident`` may be a ``content_id`` or a ``(content_id, subtopic_id)``. Given an ``ident``, return the corresponding connected component by following all positive transitivity relations...
Return a connected component generator for ``ident``. ``ident`` may be a ``content_id`` or a ``(content_id, subtopic_id)``. Given an ``ident``, return the corresponding connected component by following all positive transitivity relationships. For example, if ``(a, b, 1)`` is a...
def notifications_dismiss(self, id): """ Deletes a single notification """ id = self.__unpack_id(id) params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/notifications/dismiss', params)
Deletes a single notification
def output(context, id): """output(context, id) Show a job output. >>> dcictl job-output [OPTIONS] :param string id: ID of the job to show [required] """ colors = { 'pre-run': '\x1b[6;30;44m', 'running': '\x1b[6;30;42m', 'post-run': '\x1b[6;30;44m', 'failure':...
output(context, id) Show a job output. >>> dcictl job-output [OPTIONS] :param string id: ID of the job to show [required]
def save(self): """ Back up current editor state. """ e = self.editor self._style = e.current_style self._show_line_numbers = e.show_line_numbers self._highlight_search = e.highlight_search self._show_ruler = e.show_ruler self._relative_number = e...
Back up current editor state.
def save_to_path(self, file_path, chunk_size=DOWNLOAD_FILE_CHUNK_SIZE): """ Save the contents of the remote file to a local path. :param file_path: str: file path :param chunk_size: chunk size used to write local file """ response = self._get_download_response() w...
Save the contents of the remote file to a local path. :param file_path: str: file path :param chunk_size: chunk size used to write local file
def ari(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1): """Adjusted Rand Index (ARI) for frame clustering segmentation evaluation. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') ...
Adjusted Rand Index (ARI) for frame clustering segmentation evaluation. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> # Trim or pad the estimate ...
def save(self): # pylint: disable=arguments-differ """ Save the model with the found EnterpriseCustomerUser. """ course_id = self.validated_data['course_id'] __, created = models.EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=self.enterpr...
Save the model with the found EnterpriseCustomerUser.
def set_axis_color(axis, color, alpha=None): """Sets the spine color of all sides of an axis (top, right, bottom, left).""" for side in ('top', 'right', 'bottom', 'left'): spine = axis.spines[side] spine.set_color(color) if alpha is not None: spine.set_alpha(alpha)
Sets the spine color of all sides of an axis (top, right, bottom, left).
def lzs (inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist)
def list(self): """Lists the jobs on the server. """ queue = self._get_queue() if queue is None: raise QueueDoesntExist output = self.check_output('%s' % shell_escape(queue / 'commands/list')) job_id, info = None, None ...
Lists the jobs on the server.
def deconv_rl(data, h, Niter=10, mode_conv="fft", log_iter=False): """ richardson lucy deconvolution of data with psf h using spatial convolutions (h should be small then) mode_conv = "fft" or "spatial" """ if isinstance(data, np.ndarray): mode_data = "np" elif isinstance(data, OCLArra...
richardson lucy deconvolution of data with psf h using spatial convolutions (h should be small then) mode_conv = "fft" or "spatial"
def _render_conditions(conditions): """Render the conditions part of a query. Parameters ---------- conditions : list A list of dictionary items to filter a table. Returns ------- str A string that represents the "where" part of a query See Also -------- render...
Render the conditions part of a query. Parameters ---------- conditions : list A list of dictionary items to filter a table. Returns ------- str A string that represents the "where" part of a query See Also -------- render_query : Further clarification of `conditio...
def _pdf(self, **kwargs): """ Returns the pdf at the given angles. Parameters ---------- \**kwargs: The keyword arguments should specify the value for each angle, using the names of the polar and azimuthal angles as the keywords. Unrecognized ...
Returns the pdf at the given angles. Parameters ---------- \**kwargs: The keyword arguments should specify the value for each angle, using the names of the polar and azimuthal angles as the keywords. Unrecognized arguments are ignored. Returns ...
def createStateText(self): '''Creates the mode and arm state text.''' self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,'UNKNOWN',color='grey',size=1.5*self.fontSize,ha='left',va='top') self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foregr...
Creates the mode and arm state text.
def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
Remove artifacts from a biom table using SortMeRNA Parameters ---------- table : str name of the biom table file fasta_filename : str the fasta file containing all the sequences of the biom table Returns ------- tmp_files : list of str The temp files created during ...
def run(self): """ Start the servers """ route("/")(self.serve) if self.config.html: route("/<filepath:path>")(self.custom_html) if self.config.fuzz_web: self.request_checker.start() self.httpd.start() self.httpsd.start()
Start the servers
def value(self): """ Covariance matrix. Returns ------- K : ndarray s⋅XXᵀ. """ X = self.X return self.scale * (X @ X.T)
Covariance matrix. Returns ------- K : ndarray s⋅XXᵀ.
def get_header(self): """Get the header value from the response. :return: a future contains the deserialized value of header """ raw_header = yield get_arg(self, 1) if not self.serializer: raise tornado.gen.Return(raw_header) else: header = self.s...
Get the header value from the response. :return: a future contains the deserialized value of header
def evaluate_inkml(inkml_file_path): """Evaluate an InkML file. Parameters ---------- inkml_file_path : string path to an InkML file Returns ------- dictionary The dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionarie...
Evaluate an InkML file. Parameters ---------- inkml_file_path : string path to an InkML file Returns ------- dictionary The dictionary contains the keys 'filename' and 'results', where 'results' itself is a list of dictionaries. Each of the results has the keys ...
def set_instance(self, env, instance, previous_instance, cim_class): """Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the p...
Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList fr...