positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def send(self, from_, to, subject, text='', html='', cc=[], bcc=[], headers={}, attachments=[]): """ Send an email. """ if isinstance(to, string_types): raise TypeError('"to" parameter must be enumerable') if text == '' and html == '': raise V...
Send an email.
def plot_paired(data=None, dv=None, within=None, subject=None, order=None, boxplot=True, figsize=(4, 4), dpi=100, ax=None, colors=['green', 'grey', 'indianred'], pointplot_kwargs={'scale': .6, 'markers': '.'}, boxplot_kwargs={'color': 'lightslategrey', 'wi...
Paired plot. Parameters ---------- data : pandas DataFrame Long-format dataFrame. dv : string Name of column containing the dependant variable. within : string Name of column containing the within-subject factor. Note that ``within`` must have exactly two within-subj...
def activate_right(self, token): """Make a copy of the received token and call `_activate_right`.""" watchers.MATCHER.debug( "Node <%s> activated right with token %r", self, token) return self._activate_right(token.copy())
Make a copy of the received token and call `_activate_right`.
def dskstl(keywrd, dpval): """ Set the value of a specified DSK tolerance or margin parameter. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html :param keywrd: Code specifying parameter to set. :type keywrd: int :param dpval: Value of parameter. :type dpval: f...
Set the value of a specified DSK tolerance or margin parameter. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html :param keywrd: Code specifying parameter to set. :type keywrd: int :param dpval: Value of parameter. :type dpval: float :return:
def container_to_etree(obj, parent=None, to_str=None, **options): """ Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: ...
Convert a dict-like object to XML ElementTree. :param obj: Container instance to convert to :param parent: XML ElementTree parent node object or None :param to_str: Callable to convert value to string or None :param options: Keyword options, - tags: Dict of tags for special nodes to keep XML i...
def set_node_attr(self, name, attr, value): ''' API: set_node_attr(self, name, attr) Description: Sets attr attribute of node named name to value. Input: name: Name of node. attr: Attribute of node to set. Pre: Graph should have this no...
API: set_node_attr(self, name, attr) Description: Sets attr attribute of node named name to value. Input: name: Name of node. attr: Attribute of node to set. Pre: Graph should have this node. Post: Node attribute will be updated.
def recreate_article_body(self): ''' Handles case where article body contained page or image. Assumes all articles and images have been created. ''' for foreign_id, body in iteritems(self.record_keeper.article_bodies): try: local_page_id = self.record...
Handles case where article body contained page or image. Assumes all articles and images have been created.
def surfacemass(self,R,romberg=False,nsigma=None,relative=False): """ NAME: surfacemass PURPOSE: calculate the surface-mass at R by marginalizing over velocity INPUT: R - radius at which to calculate the surfacemass density (can be Quantity) ...
NAME: surfacemass PURPOSE: calculate the surface-mass at R by marginalizing over velocity INPUT: R - radius at which to calculate the surfacemass density (can be Quantity) OPTIONAL INPUT: nsigma - number of sigma to integrate the velocities over...
def msvs_parse_version(s): """ Split a Visual Studio version, which may in fact be something like '7.0Exp', into is version number (returned as a float) and trailing "suite" portion. """ num, suite = version_re.match(s).groups() return float(num), suite
Split a Visual Studio version, which may in fact be something like '7.0Exp', into is version number (returned as a float) and trailing "suite" portion.
def _get_raw_objects(self): """ Helper function to populate the first page of raw objects for this tag. This has the side effect of creating the ``_raw_objects`` attribute of this object. """ if not hasattr(self, '_raw_objects'): result = self._client.get(type...
Helper function to populate the first page of raw objects for this tag. This has the side effect of creating the ``_raw_objects`` attribute of this object.
def handle_authenticated_user(self, response): """ Handles the ULogin response if user is already authenticated """ current_user = get_user(self.request) ulogin, registered = ULoginUser.objects.get_or_create( uid=response['uid'], network=response[...
Handles the ULogin response if user is already authenticated
def parse_cli_args(): """parse args from the CLI and return a dict""" parser = argparse.ArgumentParser(description='2048 in your terminal') parser.add_argument('--mode', dest='mode', type=str, default=None, help='colors mode (dark or light)') parser.add_argument('--az', dest='azm...
parse args from the CLI and return a dict
def serve(self, app, conf): """ A very simple approach for a WSGI server. """ if self.args.reload: try: self.watch_and_spawn(conf) except ImportError: print('The `--reload` option requires `watchdog` to be ' '...
A very simple approach for a WSGI server.
def c_metadata(api, args, verbose=False): """ Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal. """ obj = api.get_object(args['<URL>'].split('/')[-1]) if not set_metadata(args['<JSON>'], obj): return jso...
Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal.
def key_file_public(self): '''str: path to the public key that will be uploaded to the cloud provider (by default looks for a ``.pub`` file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory) ''' if not hasattr(self, '_key_file_publ...
str: path to the public key that will be uploaded to the cloud provider (by default looks for a ``.pub`` file with name :attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh`` directory)
def read(self, size=None): """Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remain...
Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: byte...
def services(self): """ Gets the services object which will provide the ArcGIS Server's admin information about services and folders. """ if self._resources is None: self.__init() if "services" in self._resources: url = self._url + "/services" ...
Gets the services object which will provide the ArcGIS Server's admin information about services and folders.
def ssh(self, *args, **kwargs): ''' Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`. :return: Returns the result from the salt-ssh command ''' ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts, ...
Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`. :return: Returns the result from the salt-ssh command
def p_let_arr_substr_in_args3(p): """ statement : LET ARRAY_ID LP arguments COMMA TO RP EQ expr | ARRAY_ID LP arguments COMMA TO RP EQ expr """ i = 2 if p[1].upper() == 'LET' else 1 id_ = p[i] arg_list = p[i + 2] substr = (make_number(0, lineno=p.lineno(i + 4)), ...
statement : LET ARRAY_ID LP arguments COMMA TO RP EQ expr | ARRAY_ID LP arguments COMMA TO RP EQ expr
def infer(self, data, initial_proposal=None, full_output=False,**kwargs): """ Infer the model parameters, given the data. auto_convergence=True, walkers=100, burn=2000, sample=2000, minimum_sample=2000, convergence_check_frequency=1000, a=2.0, threads=1, """ # ...
Infer the model parameters, given the data. auto_convergence=True, walkers=100, burn=2000, sample=2000, minimum_sample=2000, convergence_check_frequency=1000, a=2.0, threads=1,
def access_keys(opts): ''' A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root. ''' # TODO: Need a way to get all available users for systems not supported by pwd module. # For now users pattern matching will not work for publisher_acl. ...
A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root.
def compare(self, vertex0, vertex1, subject_graph): """Returns true when the two vertices are of the same kind""" return ( self.pattern_graph.vertex_fingerprints[vertex0] == subject_graph.vertex_fingerprints[vertex1] ).all()
Returns true when the two vertices are of the same kind
def resolve_metric_as_tuple(metric): """ Resolve metric key to a given target. :param metric: the metric name. :type metric: ``str`` :rtype: :class:`Metric` """ if "." in metric: _, metric = metric.split(".") r = [ (operator, match) for operator, match in ALL_METRICS ...
Resolve metric key to a given target. :param metric: the metric name. :type metric: ``str`` :rtype: :class:`Metric`
def delete_variable(self, key): """Deletes a global variable :param key: the key of the global variable to be deleted :raises exceptions.AttributeError: if the global variable does not exist """ key = str(key) if self.is_locked(key): raise RuntimeError("Glob...
Deletes a global variable :param key: the key of the global variable to be deleted :raises exceptions.AttributeError: if the global variable does not exist
def classify_file(f): """Examine the column names to determine which type of file this is. Return a tuple: retvalue[0] = "file is non-parameterized" retvalue[1] = "file contains error column" """ cols=f[1].columns if len(cols) == 2: #Then we must have a simple file return (Tr...
Examine the column names to determine which type of file this is. Return a tuple: retvalue[0] = "file is non-parameterized" retvalue[1] = "file contains error column"
def do_open(self, args): """Open resource by number, resource name or alias: open 3""" if not args: print('A resource name must be specified.') return if self.current: print('You can only open one resource at a time. Please close the current one first.') ...
Open resource by number, resource name or alias: open 3
def configure_visual_baseline(self): """Configure baseline directory""" # Get baseline name baseline_name = self.config.get_optional('VisualTests', 'baseline_name', '{Driver_type}') for section in self.config.sections(): for option in self.config.options(section): ...
Configure baseline directory
def lock(name, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): ''' Block state execution until you are abl...
Block state execution until you are able to get the lock (or hit the timeout)
def _update_fobj(self): """Updates fobj from GUI. Opposite of _update_gui().""" # print("PPPPPPPPPPPPPPPPPPPRINTANDO O STACK") # traceback.print_stack() emsg, flag_error = "", False fieldname = None try: self._before_update_fobj() ...
Updates fobj from GUI. Opposite of _update_gui().
def query_most_pic(num, kind='1'): ''' Query most pics. ''' return TabPost.select().where( (TabPost.kind == kind) & (TabPost.logo != "") ).order_by(TabPost.view_count.desc()).limit(num)
Query most pics.
def full_match(self, other): """Find the mapping between vertex indexes in self and other. This also works on disconnected graphs. Derived classes should just implement get_vertex_string and get_edge_string to make this method aware of the different nature of certain vertices. ...
Find the mapping between vertex indexes in self and other. This also works on disconnected graphs. Derived classes should just implement get_vertex_string and get_edge_string to make this method aware of the different nature of certain vertices. In case molecules, this would...
def save(self, directory, parameters='all'): """ Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_m...
Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_mag_pu` for more information. * `currents.csv` ...
def _get_service_state(service_id: str): """Get the Service state object for the specified id.""" LOG.debug('Getting state of service %s', service_id) services = get_service_id_list() service_ids = [s for s in services if service_id in s] if len(service_ids) != 1: ret...
Get the Service state object for the specified id.
def do(self, changes, task_handle=taskhandle.NullTaskHandle()): """Perform the change and add it to the `self.undo_list` Note that uninteresting changes (changes to ignored files) will not be appended to `self.undo_list`. """ try: self.current_change = changes ...
Perform the change and add it to the `self.undo_list` Note that uninteresting changes (changes to ignored files) will not be appended to `self.undo_list`.
def stopObserver(self): """ Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically. """ self._observer.isStopped = True self._observer.isRunning = False
Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically.
def create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') user...
Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string.
def positions(self, word): """ Returns a list of positions where the word can be hyphenated. E.g. for the dutch word 'lettergrepen' this method returns the list [3, 6, 9]. Each position is a 'data int' (dint) with a data attribute. If the data attribute is not None, it c...
Returns a list of positions where the word can be hyphenated. E.g. for the dutch word 'lettergrepen' this method returns the list [3, 6, 9]. Each position is a 'data int' (dint) with a data attribute. If the data attribute is not None, it contains a tuple with information about ...
def _start_refresh_timer(self): """Start the Vim timer. """ if not self._timer: self._timer = self._vim.eval( "timer_start({}, 'EnTick', {{'repeat': -1}})" .format(REFRESH_TIMER) )
Start the Vim timer.
def loo(data, pointwise=False, reff=None, scale="deviance"): """Pareto-smoothed importance sampling leave-one-out cross-validation. Calculates leave-one-out (LOO) cross-validation for out of sample predictive model fit, following Vehtari et al. (2017). Cross-validation is computed using Pareto-smoothed ...
Pareto-smoothed importance sampling leave-one-out cross-validation. Calculates leave-one-out (LOO) cross-validation for out of sample predictive model fit, following Vehtari et al. (2017). Cross-validation is computed using Pareto-smoothed importance sampling (PSIS). Parameters ---------- data...
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] in ['event', 'update'] and self.proxy_is_active: handler = getattr(self.proxy, 'set_' + change['name'], None) if handler is not None: handler...
An observer which sends the state change to the proxy.
def edit(self, config={}, events=[], add_events=[], rm_events=[], active=True): """Edit this hook. :param dict config: (optional), key-value pairs of settings for this hook :param list events: (optional), which events should this be triggered for :pa...
Edit this hook. :param dict config: (optional), key-value pairs of settings for this hook :param list events: (optional), which events should this be triggered for :param list add_events: (optional), events to be added to the list of events that this hook trig...
def rsa_base64_encrypt(self, plain, b64=True): """ 使用公钥加密 ``可见数据`` - 由于rsa公钥加密相对耗时, 多用来 ``加密数据量小`` 的数据 .. note:: 1. 使用aes加密数据 2. 然后rsa用来加密aes加密数据时使用的key :param plain: :type plain: :param b64: :type b64: :return: ...
使用公钥加密 ``可见数据`` - 由于rsa公钥加密相对耗时, 多用来 ``加密数据量小`` 的数据 .. note:: 1. 使用aes加密数据 2. 然后rsa用来加密aes加密数据时使用的key :param plain: :type plain: :param b64: :type b64: :return: :rtype:
def django_include(context, template_name, **kwargs): ''' Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2...
Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2.1/topics/templates/. The current context is sent to the incl...
def _add_bad_rc(self, rc, result): """ Sets an error with a bad return code. Handles 'quiet' logic :param rc: The error code """ if not rc: return self.all_ok = False if rc == C.LCB_KEY_ENOENT and self._quiet: return try: ...
Sets an error with a bad return code. Handles 'quiet' logic :param rc: The error code
def finditer(self, expr): """Return an iterator over all matches in `expr` Iterate over all :class:`MatchDict` results of matches for any matching (sub-)expressions in `expr`. The order of the matches conforms to the equivalent matched expressions returned by :meth:`findall`. ""...
Return an iterator over all matches in `expr` Iterate over all :class:`MatchDict` results of matches for any matching (sub-)expressions in `expr`. The order of the matches conforms to the equivalent matched expressions returned by :meth:`findall`.
def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0): """Execute a command on the command-line. :param str,list command: The command to run :param bool shell: Whether or not to use the shell. This is optional; if ``command`` is a basestring, shell will be set to True, otherw...
Execute a command on the command-line. :param str,list command: The command to run :param bool shell: Whether or not to use the shell. This is optional; if ``command`` is a basestring, shell will be set to True, otherwise it will be false. You can override this behavior by setting this paramet...
async def _query_json( self, path, method="GET", *, params=None, data=None, headers=None, timeout=None ): """ A shorthand of _query() that treats the input as JSON. """ if headers is None: headers = {} headers["content-type"] = "application/json" i...
A shorthand of _query() that treats the input as JSON.
def module_for_loader(fxn): """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then _...
Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set the first argume...
def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001): """ Optimise value of x using levenberg-marquardt """ x_new = x x_old = x-1 # dummy value f_old = f(x_new, a, c) while np.abs(x_new - x_old).sum() > tolerance: x_old = x_new x_tmp = levenberg_marquardt...
Optimise value of x using levenberg-marquardt
def _parse_table( self, parent_name=None ): # type: (Optional[str]) -> Tuple[Key, Union[Table, AoT]] """ Parses a table element. """ if self._current != "[": raise self.parse_error( InternalParserError, "_parse_table() called on non-bracket charac...
Parses a table element.
def inputs_valid(self, outputs=None): """Validates the Inputs in the Transaction against given Outputs. Note: Given a `CREATE` Transaction is passed, dummy values for Outputs are submitted for validation that evaluate parts of the validation-c...
Validates the Inputs in the Transaction against given Outputs. Note: Given a `CREATE` Transaction is passed, dummy values for Outputs are submitted for validation that evaluate parts of the validation-checks to `True`. Args: ...
def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): """ Create a multi-GPU model similar to the basic cnn in the tutorials. """ model = make_basic_cnn() layers = model.layers model = MLPnGPU(nb_classes, layers, input_shape) return model
Create a multi-GPU model similar to the basic cnn in the tutorials.
def case_stmt_handle(self, loc, tokens): """Process case blocks.""" if len(tokens) == 2: item, cases = tokens default = None elif len(tokens) == 3: item, cases, default = tokens else: raise CoconutInternalException("invalid case tokens", to...
Process case blocks.
def bed(args): """ %prog bed frgscffile Convert the frgscf posmap file to bed format. """ p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) frgscffile, = args bedfile = frgscffile.rsplit(".", 1)[0] + ".bed" fw...
%prog bed frgscffile Convert the frgscf posmap file to bed format.
def exception( # type: ignore self, msg, *args, exc_info=True, **kwargs ) -> Task: """ Convenience method for logging an ERROR with exception information. """ return self.error(msg, *args, exc_info=exc_info, **kwargs)
Convenience method for logging an ERROR with exception information.
def validate_read_preference_tags(name, value): """Parse readPreferenceTags if passed as a client kwarg. """ if not isinstance(value, list): value = [value] tag_sets = [] for tag_set in value: if tag_set == '': tag_sets.append({}) continue try: ...
Parse readPreferenceTags if passed as a client kwarg.
def output_buffer_size(self, output_buffer_size_b): """output_buffer_size (nsqd 0.2.21+) the size in bytes of the buffer nsqd will use when writing to this client. Valid range: 64 <= output_buffer_size <= configured_max (-1 disables output buffering) --max-output-buffer-size ...
output_buffer_size (nsqd 0.2.21+) the size in bytes of the buffer nsqd will use when writing to this client. Valid range: 64 <= output_buffer_size <= configured_max (-1 disables output buffering) --max-output-buffer-size (nsqd flag) controls the max Defaults to 16kb
def patch(self, id_or_uri, operation, path, value, timeout=-1, custom_headers=None): """ Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: P...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: Patch operation path: Path value: Value timeout: Timeout in seconds. W...
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries): ''' Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word...
Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`:
def start_capture(self, port_number, output_file, data_link_type="DLT_EN10MB"): """ Starts a packet capture. :param port_number: allocated port number :param output_file: PCAP destination file for the capture :param data_link_type: PCAP data link type (DLT_*), default is DLT_EN1...
Starts a packet capture. :param port_number: allocated port number :param output_file: PCAP destination file for the capture :param data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB
def eval(self, x): """This method returns the evaluation of the function with input x :param x: this is the input as a Long """ aes = AES.new(self.key, AES.MODE_CFB, "\0" * AES.block_size) while True: nonce = 0 data = KeyedPRF.pad(SHA256.new(str(x + nonce...
This method returns the evaluation of the function with input x :param x: this is the input as a Long
def parseExtensionArgs(self, args, strict=False): """Parse the provider authentication policy arguments into the internal state of this object @param args: unqualified provider authentication policy arguments @param strict: Whether to raise an exception when bad data is ...
Parse the provider authentication policy arguments into the internal state of this object @param args: unqualified provider authentication policy arguments @param strict: Whether to raise an exception when bad data is encountered @returns: None. The data is par...
def list_migration_issues_courses(self, course_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id...
List migration issues. Returns paginated migration issues
def unindent(self): """ Un-indents text at cursor position. """ _logger().debug('unindent') cursor = self.editor.textCursor() _logger().debug('cursor has selection %r', cursor.hasSelection()) if cursor.hasSelection(): cursor.beginEditBlock() ...
Un-indents text at cursor position.
def fn_kwargs(callable): """Returns a dict with the kwargs from the provided function. Example >>> def x(a, b=0, *args, **kwargs): pass >>> func_kwargs(x) == { 'b': 0 } """ fn = get_fn(callable) (args, _, _, defaults) = _inspect.getargspec(fn) if defaults is None: return { } ...
Returns a dict with the kwargs from the provided function. Example >>> def x(a, b=0, *args, **kwargs): pass >>> func_kwargs(x) == { 'b': 0 }
def update_or_create(cls, append_lists=True, with_status=False, **kwargs): """ Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor value...
Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor values :raises FetchElementFailed: Reason for retrieval failure
def segment(self, *args): """Segment one or more datasets with this subword field. Arguments: Positional arguments: Dataset objects or other indexable mutable sequences to segment. If a Dataset object is provided, all columns corresponding to this field are u...
Segment one or more datasets with this subword field. Arguments: Positional arguments: Dataset objects or other indexable mutable sequences to segment. If a Dataset object is provided, all columns corresponding to this field are used; individual colum...
def get_uppermost_library_root_state(self): """Find state_copy of uppermost LibraryState Method checks if there is a parent library root state and assigns it to be the current library root state till there is no further parent library root state. """ library_root_state = self.g...
Find state_copy of uppermost LibraryState Method checks if there is a parent library root state and assigns it to be the current library root state till there is no further parent library root state.
def _set_igmp_snooping_state(self, v, load=False): """ Setter method for igmp_snooping_state, mapped from YANG variable /igmp_snooping_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmp_snooping_state is considered as a private method. Backends lo...
Setter method for igmp_snooping_state, mapped from YANG variable /igmp_snooping_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmp_snooping_state is considered as a private method. Backends looking to populate this variable should do so via calling th...
def get_file(self): """ Load data into a file and return file path. :return: path to file as string """ content = self._load() if not content: return None filename = "temporary_file.bin" with open(filename, "wb") as file_name: file...
Load data into a file and return file path. :return: path to file as string
def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): """ Mostly equivalent to `tf.layers.batch_normalization`, but difference...
Mostly equivalent to `tf.layers.batch_normalization`, but difference in the following: 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from `Tow...
def create_location_relationship(manager, location_handle_id, other_handle_id, rel_type): """ Makes relationship between the two nodes and returns the relationship. If a relationship is not possible NoRelationshipPossible exception is raised. """ other_meta_type = get_node_meta_type(manager, oth...
Makes relationship between the two nodes and returns the relationship. If a relationship is not possible NoRelationshipPossible exception is raised.
def validip(ip, defaultaddr="0.0.0.0", defaultport=8080): """Returns `(ip_address, port)` from string `ip_addr_port`""" addr = defaultaddr port = defaultport ip = ip.split(":", 1) if len(ip) == 1: if not ip[0]: pass elif validipaddr(ip[0]): addr = ip[0] ...
Returns `(ip_address, port)` from string `ip_addr_port`
def get_firmware_manifest(self, manifest_id): """Get manifest with provided manifest_id. :param str manifest_id: ID of manifest to retrieve (Required) :return: FirmwareManifest """ api = self._get_api(update_service.DefaultApi) return FirmwareManifest(api.firmware_manife...
Get manifest with provided manifest_id. :param str manifest_id: ID of manifest to retrieve (Required) :return: FirmwareManifest
def _python_to_lua(pval): """ Convert Python object(s) into Lua object(s), as at times Python object(s) are not compatible with Lua functions """ import lua if pval is None: # Python None --> Lua None return lua.eval("") if isinstance(pval,...
Convert Python object(s) into Lua object(s), as at times Python object(s) are not compatible with Lua functions
def build_GTK_KDE(self): """Build the Key Data Encapsulation for GTK KeyID: 0 Ref: 802.11i p81 """ return b''.join([ b'\xdd', # Type KDE chb(len(self.gtk_full) + 6), b'\x00\x0f\xac', # OUI b'\x01', # GTK KDE b'\x00\x0...
Build the Key Data Encapsulation for GTK KeyID: 0 Ref: 802.11i p81
def _visit_shape_te(self, te: ShExJ.tripleExpr, visit_center: _VisitorCenter) -> None: """ Visit a triple expression that was reached through a shape. This, in turn, is used to visit additional shapes that are referenced by a TripleConstraint :param te: Triple expression reached through ...
Visit a triple expression that was reached through a shape. This, in turn, is used to visit additional shapes that are referenced by a TripleConstraint :param te: Triple expression reached through a Shape.expression :param visit_center: context used in shape visitor
def get_exclusions(path): """ Generates exclusion patterns from a ``.dockerignore`` file located in the given path. Returns ``None`` if the file does not exist. :param path: Path to look up the ``.dockerignore`` in. :type path: unicode | str :return: List of patterns, that can be passed into :f...
Generates exclusion patterns from a ``.dockerignore`` file located in the given path. Returns ``None`` if the file does not exist. :param path: Path to look up the ``.dockerignore`` in. :type path: unicode | str :return: List of patterns, that can be passed into :func:`get_filter_func`. :rtype: lis...
def set(self, key: Any, value: Any) -> None: """ Sets the value of a key to a supplied value """ if key is not None: self[key] = value
Sets the value of a key to a supplied value
def gen_row_lines(self, row, style, inner_widths, height): r"""Combine cells in row and group them into lines with vertical borders. Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append newline character to the end of joined line. ...
r"""Combine cells in row and group them into lines with vertical borders. Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append newline character to the end of joined line. In: ['Row One Column One', 'Two', 'Three'] Out:...
def _process_download(self, url): """ See if an URL is a suitable download for a project. If it is, register information in the result dictionary (for _get_project) about the specific version it's for. Note that the return value isn't actually used other than as a boolean ...
See if an URL is a suitable download for a project. If it is, register information in the result dictionary (for _get_project) about the specific version it's for. Note that the return value isn't actually used other than as a boolean value.
def get_route_templates(self): """ Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml represents an externally exposed port. """ def _get_published_ports(service_config): result = [] for port in s...
Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml represents an externally exposed port.
def add_custom_metadata(self, key, value, meta_type=None): """ Add custom metadata to the Video. meta_type is required for XML API. """ self.metadata.append({'key': key, 'value': value, 'type': meta_type})
Add custom metadata to the Video. meta_type is required for XML API.
def login(self, user, password, exe_path, comm_password=None, **kwargs): """ 登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 ...
登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return:
def calc_distance(lng1, lat1, lng2, lat2): """Calc distance (km) by geo-coordinates. @:param lng1: first coordinate.lng @:param lat1: first coordinate.lat @:param lng2: second coordinate.lng @:param lat2: second coordinate.lat @:return distance: km """ ra = 6378.140 ...
Calc distance (km) by geo-coordinates. @:param lng1: first coordinate.lng @:param lat1: first coordinate.lat @:param lng2: second coordinate.lng @:param lat2: second coordinate.lat @:return distance: km
def render(self, context): """ Render the tag, with extra context layer. """ extra_context = self.context_expr.resolve(context) if not isinstance(extra_context, dict): raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.") with c...
Render the tag, with extra context layer.
def _compute_u(K): """ Estimate an approximation of the ratio of stationary over empirical distribution from the basis. Parameters: ----------- K0, ndarray(M+1, M+1), time-lagged correlation matrix for the whitened and padded data set. Returns: -------- u : ndarray(M,) co...
Estimate an approximation of the ratio of stationary over empirical distribution from the basis. Parameters: ----------- K0, ndarray(M+1, M+1), time-lagged correlation matrix for the whitened and padded data set. Returns: -------- u : ndarray(M,) coefficients of the ratio station...
def load_data(self, path): """Load isoelastics from a text file The text file is loaded with `numpy.loadtxt` and must have three columns, representing the two data columns and the elastic modulus with units defined in `definitions.py`. The file header must have a section definin...
Load isoelastics from a text file The text file is loaded with `numpy.loadtxt` and must have three columns, representing the two data columns and the elastic modulus with units defined in `definitions.py`. The file header must have a section defining meta data of the content lik...
def is_unicode_string(string): """ Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool """ if string is None: ...
Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool
def main(): """ Generate sequences.""" parser = OptionParser(conflict_handler="resolve") parser.add_option('--humanTRA', '--human_T_alpha', action='store_true', dest='humanTRA', default=False, help='use default human TRA model (T cell alpha chain)') parser.add_option('--humanTRB', '--human_T_beta', ac...
Generate sequences.
def flag_all(self, thresh_dict=None, include=None, exclude=None): ''' Returns indices of (rows, columns) that satisfy flag() on any diagnostic. Uses user-provided thresholds in thresh_dict/ Args: thresh_dict (dict): dictionary of diagnostic->threshold functions i...
Returns indices of (rows, columns) that satisfy flag() on any diagnostic. Uses user-provided thresholds in thresh_dict/ Args: thresh_dict (dict): dictionary of diagnostic->threshold functions include (list): optional sublist of diagnostics to flag exclude (list): opt...
def create_attributes(klass, attributes, previous_object=None): """Attributes for space creation.""" if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': at...
Attributes for space creation.
def merge_parts(self, version_id=None, **kwargs): """Merge parts into object version.""" self.file.update_checksum(**kwargs) with db.session.begin_nested(): obj = ObjectVersion.create( self.bucket, self.key, _file_id=self.file_id, ...
Merge parts into object version.
def whitespace_around_comma(logical_line): r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2) """ line = logical_line for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line): fou...
r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2)
def _remove(self, client_kwargs): """ Remove an object. args: client_kwargs (dict): Client arguments. """ with _handle_client_error(): # Object if 'Key' in client_kwargs: return self.client.delete_object(**client_kwargs) ...
Remove an object. args: client_kwargs (dict): Client arguments.
def read_hyperparameters(): # type: () -> dict """Read the hyperparameters from /opt/ml/input/config/hyperparameters.json. For more information about hyperparameters.json: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html#your-algorithms-training-algo-running-container-hyp...
Read the hyperparameters from /opt/ml/input/config/hyperparameters.json. For more information about hyperparameters.json: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html#your-algorithms-training-algo-running-container-hyperparameters Returns: (dict[string, objec...
def get_transformed_feature_indices(features, stats): """Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})] """ feature_indices = [] index_start = 1 for name, transform in sorted(six.iteritems(features)): tr...
Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})]
def _find_bck(self, chunk): """ Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head and all other metadata are unaltered by this function. """ cur = self.free_head_chunk if cur is None: return None ...
Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head and all other metadata are unaltered by this function.
def file_rows(self, fo): """Return the lines in the file as a list. fo is the open file object.""" rows = [] for i in range(NUMROWS): line = fo.readline() if not line: break rows += [line] return rows
Return the lines in the file as a list. fo is the open file object.
def flair(self, r, name, text, css_class): """Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/flair`` ...
Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/flair`` :param r: name of subreddit :param name: n...