code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _make_pkh_address(pubkey_hash, witness=False, cashaddr=True): ''' bytes, bool -> str ''' addr_bytes = bytearray() if riemann.network.CASHADDR_P2PKH is not None and cashaddr: addr_bytes.extend(riemann.network.CASHADDR_P2PKH) addr_bytes.extend(pubkey_hash) return riemann.ne...
bytes, bool -> str
def get_report(self, value): """Return provided field Python value formatted for use in report filter""" if self.multiselect: value = value or [] children = [] for child in value: children.append(self.cast_to_report(child)) return childre...
Return provided field Python value formatted for use in report filter
def request(self, persist_id=None): """Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation. """ node = new_ele("cancel-comm...
Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation.
def plot_spectra_overlapped(ss, title=None, setup=_default_setup): """ Plots one or more spectra in the same plot. Args: ss: list of Spectrum objects title=None: window title setup: PlotSpectrumSetup object """ plt.figure() draw_spectra_overlapped(ss, title, setup) plt.sh...
Plots one or more spectra in the same plot. Args: ss: list of Spectrum objects title=None: window title setup: PlotSpectrumSetup object
def attr_case_name(self, name): """Returns preserved case name for case insensitive value of name. Checks first within standard attributes. If not found there, checks attributes for higher order data structures. If not found, returns supplied name as it is available for use. Int...
Returns preserved case name for case insensitive value of name. Checks first within standard attributes. If not found there, checks attributes for higher order data structures. If not found, returns supplied name as it is available for use. Intended to be used to help ensure tha...
def mmapFile(self, addr, size, perms, filename, offset=0): """ Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :pa...
Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :param size: the contents of a file mapping are initialized using C{size} bytes st...
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None): """ TensorFlow implementation of the foward derivative / Jacobian :param x: the input placeholder :param grads: the list of TF gradients returned by jacobian_graph() :param target: the target misclassification class :param X: numpy...
TensorFlow implementation of the foward derivative / Jacobian :param x: the input placeholder :param grads: the list of TF gradients returned by jacobian_graph() :param target: the target misclassification class :param X: numpy array with sample input :param nb_features: the number of features in the input ...
def set_key(self, key): """Init.""" key_len = len(key) if key_len not in [16, 24, 32]: # XXX: add padding? raise KeyError("key must be 16, 24 or 32 bytes") if key_len % 4: # XXX: add padding? raise KeyError("key not a multiple of 4") ...
Init.
def _edges_classify_intersection9(): """The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`. """ edges1 = ( bezier.Curve.from_nodes( np.asfortranarray([[32.0, 30.0], [20.0, 25.0]]) ), bezier.Curve.from_nodes( ...
The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`.
def interpolate(self, factor, minLayer, maxLayer, round=True, suppressError=True): """ Interpolate all possible data in the layer. :: >>> layer.interpolate(0.5, otherLayer1, otherLayer2) >>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False)...
Interpolate all possible data in the layer. :: >>> layer.interpolate(0.5, otherLayer1, otherLayer2) >>> layer.interpolate((0.5, 2.0), otherLayer1, otherLayer2, round=False) The interpolation occurs on a 0 to 1.0 range where **minLayer** is located at 0 and **maxLayer** is locat...
def true_num_reactions(model, custom_spont_id=None): """Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions a...
Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions associated with a gene
def mongodump(mongo_user, mongo_password, mongo_dump_directory_path, database=None, silent=False): """ Runs mongodump using the provided credentials on the running mongod process. WARNING: This function will delete the contents of the provided directory before it runs. """ ...
Runs mongodump using the provided credentials on the running mongod process. WARNING: This function will delete the contents of the provided directory before it runs.
def sanitize_capabilities(caps): """ Sanitize the capabilities we pass to Selenic so that they can be consumed by Browserstack. :param caps: The capabilities passed to Selenic. This dictionary is modified. :returns: The sanitized capabilities. """ platform = caps["platform"] upper...
Sanitize the capabilities we pass to Selenic so that they can be consumed by Browserstack. :param caps: The capabilities passed to Selenic. This dictionary is modified. :returns: The sanitized capabilities.
def choose_parent_view(self, request): """ Instantiates a class-based view to provide a view that allows a parent page to be chosen for a new object, where the assigned model extends Wagtail's Page model, and there is more than one potential parent for new instances. The view cla...
Instantiates a class-based view to provide a view that allows a parent page to be chosen for a new object, where the assigned model extends Wagtail's Page model, and there is more than one potential parent for new instances. The view class used can be overridden by changing the 'choose_p...
def get_or_create(cls, filter_key=None, with_status=False, **kwargs): """ Convenience method to retrieve an Element or create if it does not exist. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. ...
Convenience method to retrieve an Element or create if it does not exist. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Any keyword arguments passed except the optional filter_key will be used in a ...
def process_service_check_result(self, service, return_code, plugin_output): """Process service check result Format of the line that triggers function call:: PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output> :param service: service to process ...
Process service check result Format of the line that triggers function call:: PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output> :param service: service to process check to :type service: alignak.objects.service.Service :param return_co...
def grouper(iterable, n, fillvalue=None): """Collect data into fixed-length chunks or blocks. >>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] """ if isinstance(iterable, int): warnings.warn( "grouper expects iterable as first par...
Collect data into fixed-length chunks or blocks. >>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
def readline(self, raise_exception=False): """Read a line and return it. If "raise_exception" is set, raise _ConnectionDeadError if the read fails, otherwise return an empty string. """ buf = self.buffer if self.socket: recv = self.socket.recv else: ...
Read a line and return it. If "raise_exception" is set, raise _ConnectionDeadError if the read fails, otherwise return an empty string.
def get_path_variables(**kwargs): """ Get the base variables for any view to route to. Currently gets: - `enterprise_uuid` - the UUID of the enterprise customer. - `course_run_id` - the ID of the course, if applicable. - `program_uuid` - the UUID of the program, if appli...
Get the base variables for any view to route to. Currently gets: - `enterprise_uuid` - the UUID of the enterprise customer. - `course_run_id` - the ID of the course, if applicable. - `program_uuid` - the UUID of the program, if applicable.
def use_comparative_vault_view(self): """The returns from the lookup methods may omit or translate elements based on this session, such as authorization, and not result in an error. This view is used when greater interoperability is desired at the expense of precision. *compliance: man...
The returns from the lookup methods may omit or translate elements based on this session, such as authorization, and not result in an error. This view is used when greater interoperability is desired at the expense of precision. *compliance: mandatory -- This method is must be implemented.*
def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """ # We ...
Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual.
def list_listeners(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_listeners for a project.""" return self.list('listeners', self.lbaas_listeners_path, retrieve_all, **_params)
Fetches a list of all lbaas_listeners for a project.
def add_service(self, name, long_name, preregistered=False, notify=True): """Add a service to the list of tracked services. Args: name (string): A unique short service name for the service long_name (string): A longer, user friendly name for the service preregistered...
Add a service to the list of tracked services. Args: name (string): A unique short service name for the service long_name (string): A longer, user friendly name for the service preregistered (bool): Whether this service is an expected preregistered service. ...
def libvlc_media_player_set_media(p_mi, p_md): '''Set the media that will be used by the media_player. If any, previous md will be released. @param p_mi: the Media Player. @param p_md: the Media. Afterwards the p_md can be safely destroyed. ''' f = _Cfunctions.get('libvlc_media_player_set_media'...
Set the media that will be used by the media_player. If any, previous md will be released. @param p_mi: the Media Player. @param p_md: the Media. Afterwards the p_md can be safely destroyed.
def enable_thread_safety(self): """Enable thread-safety features. Must be called before start(). """ if self.threadsafe: return # Already done! if self._running.isSet(): raise RuntimeError('Cannot enable thread safety after start')...
Enable thread-safety features. Must be called before start().
def init_tree(self, tree_alias, context): """Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param str|unicode tree_alias: :param Context context: :rtype: tuple """ request = co...
Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param str|unicode tree_alias: :param Context context: :rtype: tuple
def views_show_many(self, ids=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#list-views-by-id" api_path = "/api/v2/views/show_many.json" api_query = {} if "query" in kwargs.keys(): api_query.update(kwargs["query"]) del kwargs["query"] ...
https://developer.zendesk.com/rest_api/docs/core/views#list-views-by-id
def open_icmp_firewall(host): """Temporarily open the ICMP firewall. Tricks Windows into allowing ICMP packets for a short period of time (~ 1 minute)""" # We call ping with a timeout of 1ms: will return instantly with open(os.devnull, 'wb') as DEVNULL: return subprocess.Popen("ping -4 -w 1 -n 1...
Temporarily open the ICMP firewall. Tricks Windows into allowing ICMP packets for a short period of time (~ 1 minute)
def load_and_parse(self): """Load and parse archives in a list of projects. Returns a dict that maps unique ids onto ParsedNodes""" archives = [] to_return = {} for name, project in self.all_projects.items(): archives = archives + self.parse_archives_from_project...
Load and parse archives in a list of projects. Returns a dict that maps unique ids onto ParsedNodes
def download(directory, filename): """Download (and unzip) a file from the MNIST dataset if not already done.""" filepath = os.path.join(directory, filename) if tf.gfile.Exists(filepath): return filepath if not tf.gfile.Exists(directory): tf.gfile.MakeDirs(directory) url = 'http://yann.lecun.com/exdb/...
Download (and unzip) a file from the MNIST dataset if not already done.
def list_metrics(ctx): """List the available metrics.""" config = ctx.obj["CONFIG"] if not exists(config): handle_no_cache(ctx) from wily.commands.list_metrics import list_metrics list_metrics()
List the available metrics.
def plot(self, origin=(0, 0), ax=None, fill=False, **kwargs): """ Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes` instance. Parameters ---------- origin : array_like, optional The ``(x, y)`` position of the origin of the displayed i...
Plot the `BoundingBox` on a matplotlib `~matplotlib.axes.Axes` instance. Parameters ---------- origin : array_like, optional The ``(x, y)`` position of the origin of the displayed image. ax : `matplotlib.axes.Axes` instance, optional If `None...
def return_or_raise(cls, response, expected_status_code): """Check for ``expected_status_code``.""" try: if response.status_code in expected_status_code: return response except TypeError: if response.status_code == expected_status_code: ret...
Check for ``expected_status_code``.
def create(self, start_date, end_date, include_subaccounts=values.unset, status_callback=values.unset, status_callback_method=values.unset): """ Create a new FeedbackSummaryInstance :param date start_date: Only include feedback given on or after this date :param date end_...
Create a new FeedbackSummaryInstance :param date start_date: Only include feedback given on or after this date :param date end_date: Only include feedback given on or before this date :param bool include_subaccounts: `true` includes feedback from the specified account and its subaccounts ...
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths.
def get_collection(self, name): '''get a collection, if it exists, otherwise return None. ''' from sregistry.database.models import Collection return Collection.query.filter(Collection.name == name).first()
get a collection, if it exists, otherwise return None.
def GetRootKey(self): """Retrieves the root key. Returns: WinRegistryKey: Windows Registry root key or None if not available. """ regf_key = self._regf_file.get_root_key() if not regf_key: return None return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix)
Retrieves the root key. Returns: WinRegistryKey: Windows Registry root key or None if not available.
async def request(self, method, url=None, *, path='', retries=1, connection_timeout=60, **kwargs): ''' This is the template for all of the `http method` methods for the Session. Args: method (str): A http method, such as 'GET' or 'POST'. url...
This is the template for all of the `http method` methods for the Session. Args: method (str): A http method, such as 'GET' or 'POST'. url (str): The url the request should be made to. path (str): An optional kw-arg for use in Session method calls, fo...
def get_pgid(path, follow_symlinks=True): ''' Return the id of the primary group that owns a given file (Windows only) This function will return the rarely used primary group of a file. This generally has no bearing on permissions unless intentionally configured and is most commonly used to provide...
Return the id of the primary group that owns a given file (Windows only) This function will return the rarely used primary group of a file. This generally has no bearing on permissions unless intentionally configured and is most commonly used to provide Unix compatibility (e.g. Services For Unix, NFS s...
def execute(self, args): """Execute a registered hook based on args[0]""" _run_atstart() hook_name = os.path.basename(args[0]) if hook_name in self._hooks: try: self._hooks[hook_name]() except SystemExit as x: if x.code is None or x...
Execute a registered hook based on args[0]
def get_graph_data(self, graph, benchmark): """ Iterator over graph data sets Yields ------ param_idx Flat index to parameter permutations for parameterized benchmarks. None if benchmark is not parameterized. entry_name Name for the da...
Iterator over graph data sets Yields ------ param_idx Flat index to parameter permutations for parameterized benchmarks. None if benchmark is not parameterized. entry_name Name for the data set. If benchmark is non-parameterized, this is the ...
def pop_all(self, priority=None): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ output = [] with self.lock: if not priority: priority = self.highest_entry() if priority: output = list(self.queue[priority].queue) ...
NON-BLOCKING POP ALL IN QUEUE, IF ANY
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label): """ Creates an LTI cookieless session. Returns the new session id""" self._de...
Creates an LTI cookieless session. Returns the new session id
def _SetColour(self, value_list): """Sets row's colour attributes to a list of values in terminal.SGR.""" if value_list is None: self._color = None return colors = [] for color in value_list: if color in terminal.SGR: colors.append(colo...
Sets row's colour attributes to a list of values in terminal.SGR.
def n_chunks(self): """ rough estimate of how many chunks will be processed """ return self._data_source.n_chunks(self.chunksize, stride=self.stride, skip=self.skip)
rough estimate of how many chunks will be processed
def equivalence_transform(compound, from_positions, to_positions, add_bond=True): """Computes an affine transformation that maps the from_positions to the respective to_positions, and applies this transformation to the compound. Parameters ---------- compound : mb.Compound The Compound to b...
Computes an affine transformation that maps the from_positions to the respective to_positions, and applies this transformation to the compound. Parameters ---------- compound : mb.Compound The Compound to be transformed. from_positions : np.ndarray, shape=(n, 3), dtype=float Origina...
def _get_all_files(filename_regex, path, base_dir, excluded_paths=None, excluded_filename_regex=None): """Get all files for processing. This starts iterating from `base_dir` and checks for all files that look like `filename_regex` ...
Get all files for processing. This starts iterating from `base_dir` and checks for all files that look like `filename_regex` under `path` regex excluding all paths under the `excluded_paths` list, whether they are files or folders. `excluded_paths` are explicit paths, not regex. `excluded_filename_...
def make_function_value_private(self, value, value_type, function): """ Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config """ # remove...
Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config
def write(self, h, txt='', link=''): "Output text in flowing mode" txt = self.normalize_text(txt) cw=self.current_font['cw'] w=self.w-self.r_margin-self.x wmax=(w-2*self.c_margin)*1000.0/self.font_size s=txt.replace("\r",'') nb=len(s) sep=-1 i=0 ...
Output text in flowing mode
def unique_iter(src, key=None): """Yield unique elements from the iterable, *src*, based on *key*, in the order in which they first appeared in *src*. >>> repetitious = [1, 2, 3] * 10 >>> list(unique_iter(repetitious)) [1, 2, 3] By default, *key* is the object itself, but *key* can either be a...
Yield unique elements from the iterable, *src*, based on *key*, in the order in which they first appeared in *src*. >>> repetitious = [1, 2, 3] * 10 >>> list(unique_iter(repetitious)) [1, 2, 3] By default, *key* is the object itself, but *key* can either be a callable or, for convenience, a st...
def to_boulderio(infile, outfile): '''Converts input sequence file into a "Boulder-IO format", as used by primer3''' seq_reader = sequences.file_reader(infile) f_out = utils.open_file_write(outfile) for sequence in seq_reader: print("SEQUENCE_ID=" + sequence.id, file=f_out) print("SEQUE...
Converts input sequence file into a "Boulder-IO format", as used by primer3
def _set_cluster(self, v, load=False): """ Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container) If this variable is read-only (config: false) in the source YANG file, then _set_cluster is considered as a private method. Backends looking to populate this variable sho...
Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container) If this variable is read-only (config: false) in the source YANG file, then _set_cluster is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cluster() di...
def optional(name, default) -> 'Wildcard': """Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. ...
Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. default: The default value of the wil...
def train(self, jsondocs, model_dir): """ Train a NER model using given documents. Each word in the documents must have a "label" attribute, which denote the named entities in the documents. Parameters ---------- jsondocs: list of JSON-style documents. ...
Train a NER model using given documents. Each word in the documents must have a "label" attribute, which denote the named entities in the documents. Parameters ---------- jsondocs: list of JSON-style documents. The documents used for training the CRF...
def extend_peaks(self, prop_thresh=50): """Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created. prop_thresh is the cent range within which the peak in the other octave is expected to be present, i.e., only if ...
Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created. prop_thresh is the cent range within which the peak in the other octave is expected to be present, i.e., only if there is a peak within this cent range in ...
def mach2tas(Mach, H): """Mach number to True Airspeed""" a = vsound(H) Vtas = Mach*a return Vtas
Mach number to True Airspeed
def deploy(verbose, app): """Deploy app using Heroku to MTurk.""" # Load psiTurk configuration. config = PsiturkConfig() config.load_config() # Set the mode. config.set("Experiment Configuration", "mode", "deploy") config.set("Server Parameters", "logfile", "-") # Ensure that psiTurk i...
Deploy app using Heroku to MTurk.
def reduce(self, dimensions=[], function=None, spreadfn=None, **reductions): """Applies reduction along the specified dimension(s). Allows reducing the values along one or more key dimension with the supplied function. Supports two signatures: Reducing with a list of dimensions, e.g.: ...
Applies reduction along the specified dimension(s). Allows reducing the values along one or more key dimension with the supplied function. Supports two signatures: Reducing with a list of dimensions, e.g.: ds.reduce(['x'], np.mean) Defining a reduction using keywords, e.g...
def all_files(models=[]): r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb ...
r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb test.weights.e5.lstm1000....
def verifyUpdatewcs(fname): """ Verify the existence of WCSNAME in the file. If it is not present, report this to the user and raise an exception. Returns True if WCSNAME was found in all SCI extensions. """ updated = True numsci,extname = count_sci_extensions(fname) for n in range(1,n...
Verify the existence of WCSNAME in the file. If it is not present, report this to the user and raise an exception. Returns True if WCSNAME was found in all SCI extensions.
def make_action(self, fn, schema_parser, meta): """ Make resource's method an action Validate input, output by schema in meta. If no input schema, call fn without params. If no output schema, will not validate return value. Args: fn: resource's method ...
Make resource's method an action Validate input, output by schema in meta. If no input schema, call fn without params. If no output schema, will not validate return value. Args: fn: resource's method schema_parser: for parsing schema in meta meta: me...
def get_platform(): """Get the current platform data. Returns a dictionary with keys: `os_name`, `os_bits` """ platform_data = { 'os_name': None, 'os_bits': None } os_name = platform.system() normalize_os = { 'Windows': 'windows', 'Linux': 'linux', 'Da...
Get the current platform data. Returns a dictionary with keys: `os_name`, `os_bits`
def index(self, value, start=0, end=None): """Return the index of value between start and end. By default, the entire setlist is searched. This runs in O(1) Args: value: The value to find the index of start (int): The index to start searching at (defaults to 0) end (int): The index to stop searching...
Return the index of value between start and end. By default, the entire setlist is searched. This runs in O(1) Args: value: The value to find the index of start (int): The index to start searching at (defaults to 0) end (int): The index to stop searching at (defaults to the end of the list) Returns:...
def fromDataFrameRDD(cls, rdd, sql_ctx): """Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.""" result = DataFrame(None, sql_ctx) return result.from_rdd_of_dataframes(rdd)
Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.
def load_vm_uuid_by_name(self, si, vcenter_data_model, vm_name): """ Returns the vm uuid :param si: Service instance to the vcenter :param vcenter_data_model: vcenter data model :param vm_name: the vm name :return: str uuid """ path = VMLocation.combine([v...
Returns the vm uuid :param si: Service instance to the vcenter :param vcenter_data_model: vcenter data model :param vm_name: the vm name :return: str uuid
def do_wordwrap(s, width=79, break_long_words=True): """ Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `w...
Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`.
def upgrade_plan_list(self, subid, params=None): ''' /v1/server/upgrade_plan_list GET - account Retrieve a list of the VPSPLANIDs for which a virtual machine can be upgraded. An empty response array means that there are currently no upgrades available. Link: https://www....
/v1/server/upgrade_plan_list GET - account Retrieve a list of the VPSPLANIDs for which a virtual machine can be upgraded. An empty response array means that there are currently no upgrades available. Link: https://www.vultr.com/api/#server_upgrade_plan_list
def _GetDataStreams(self): """Retrieves the data streams. Returns: list[DataStream]: data streams. """ if self._data_streams is None: if self._directory is None: self._directory = self._GetDirectory() self._data_streams = [] # It is assumed that directory and link file...
Retrieves the data streams. Returns: list[DataStream]: data streams.
def set_options_values(self, options, parse=False, strict=False): """ Set the options from a dict of values (in string). :param option_values: the values of options (in format `{"opt_name": "new_value"}`) :type option_values: dict :param parse: whether to parse the given value ...
Set the options from a dict of values (in string). :param option_values: the values of options (in format `{"opt_name": "new_value"}`) :type option_values: dict :param parse: whether to parse the given value :type parse: bool :param strict: if True the given `option_valu...
def write_reaction(self, value_dict): con = self.connection or self._connect() self._initialize(con) cur = con.cursor() ase_ids = value_dict['ase_ids'] energy_corrections = value_dict.get('energy_corrections', {}) key_list = get_key_list(start_index=1) values = ...
Write to reaction_system tables
def kill_current_session(ctx: Context_T) -> None: """ Force kill current session of the given context, despite whether it is running or not. :param ctx: message context """ ctx_id = context_id(ctx) if ctx_id in _sessions: del _sessions[ctx_id]
Force kill current session of the given context, despite whether it is running or not. :param ctx: message context
def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None: """Register a function to be called after parsing user input but before running the command""" self._validate_postparsing_callable(func) self._postparsing_hooks.append(func)
Register a function to be called after parsing user input but before running the command
def feed(self, pred, label): """ Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. """ assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_ne...
Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size.
def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, p...
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
def fft_coefficient(self, x, param=None): """ As in tsfresh `fft_coefficient <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\ feature_calculators.py#L852>`_ \ Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real in...
As in tsfresh `fft_coefficient <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\ feature_calculators.py#L852>`_ \ Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast \ fourier transformation algorithm ...
def handle_stdin_request(self, timeout=0.1): """ Method to capture raw_input """ msg_rep = self.km.stdin_channel.get_msg(timeout=timeout) # in case any iopub came while we were waiting: self.handle_iopub() if self.session_id == msg_rep["parent_header"].get("session"): ...
Method to capture raw_input
def modify_content(request, page_id, content_type, language_id): """Modify the content of a page.""" page = get_object_or_404(Page, pk=page_id) perm = request.user.has_perm('pages.change_page') if perm and request.method == 'POST': content = request.POST.get('content', False) if not cont...
Modify the content of a page.
def query_by_postid(postid, limit=5): ''' Query history of certian records. ''' recs = TabPostHist.select().where( TabPostHist.post_id == postid ).order_by( TabPostHist.time_update.desc() ).limit(limit) return recs
Query history of certian records.
def dump_viewset(viewset_class, root_folder, folder_fn=lambda i: ".", sample_size=None): """ Dump the contents of a rest-api queryset to a folder structure. :param viewset_class: A rest-api viewset to iterate through :param root_folder: The root folder to write results to. :param folder_fn: A funct...
Dump the contents of a rest-api queryset to a folder structure. :param viewset_class: A rest-api viewset to iterate through :param root_folder: The root folder to write results to. :param folder_fn: A function to generate a subfolder name for the instance. :param sample_size: Number of items to process...
def sdiv(a, b): """Safe division: if a == b == 0, sdiv(a, b) == 1""" if len(a) != len(b): raise ValueError('Argument a and b does not have the same length') idx = 0 ret = matrix(0, (len(a), 1), 'd') for m, n in zip(a, b): try: ret[idx] = m / n except ZeroDivisionE...
Safe division: if a == b == 0, sdiv(a, b) == 1
def stepper_step(self, motor_speed, number_of_steps): """ Move a stepper motor for the number of steps at the specified speed This is a FirmataPlus feature. :param motor_speed: 21 bits of data to set motor speed :param number_of_steps: 14 bits for number of steps & direction ...
Move a stepper motor for the number of steps at the specified speed This is a FirmataPlus feature. :param motor_speed: 21 bits of data to set motor speed :param number_of_steps: 14 bits for number of steps & direction positive is forward, negative is reverse
def absolute(requestContext, seriesList): """ Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.thread...
Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.threads.busy)
def _create_gates(self, inputs, memory): """Create input and forget gates for this step using `inputs` and `memory`. Args: inputs: Tensor input. memory: The current state of memory. Returns: input_gate: A LSTM-like insert gate. forget_gate: A LSTM-like forget gate. """ # We...
Create input and forget gates for this step using `inputs` and `memory`. Args: inputs: Tensor input. memory: The current state of memory. Returns: input_gate: A LSTM-like insert gate. forget_gate: A LSTM-like forget gate.
def light2mass_interpol(lens_light_model_list, kwargs_lens_light, numPix=100, deltaPix=0.05, subgrid_res=5, center_x=0, center_y=0): """ takes a lens light model and turns it numerically in a lens model (with all lensmodel quantities computed on a grid). Then provides an interpolated grid for th...
takes a lens light model and turns it numerically in a lens model (with all lensmodel quantities computed on a grid). Then provides an interpolated grid for the quantities. :param kwargs_lens_light: lens light keyword argument list :param numPix: number of pixels per axis for the return interpo...
def get_queue(cls, name, priority=0, **fields_if_new): """ Get, or create, and return the wanted queue. If the queue is created, fields in fields_if_new will be set for the new queue. """ queue_kwargs = {'name': name, 'priority': priority} retries = 0 whil...
Get, or create, and return the wanted queue. If the queue is created, fields in fields_if_new will be set for the new queue.
def destroy(self): """Close the connection, and close any associated CBS authentication session. """ try: self.lock() _logger.debug("Unlocked connection %r to close.", self.container_id) self._close() finally: self.release() ...
Close the connection, and close any associated CBS authentication session.
def _fill_levenshtein_table(self, first, second, update_func, add_pred, clear_pred, threshold=None): """ Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[...
Функция, динамически заполняющая таблицу costs стоимости трансдукций, costs[i][j] --- минимальная стоимость трансдукции, переводящей first[:i] в second[:j] Аргументы: ---------- first, second : string Верхний и нижний элементы трансдукции update_func : callab...
def helioX(self,*args,**kwargs): """ NAME: helioX PURPOSE: return Heliocentric Galactic rectangular x-coordinate (aka "X") INPUT: t - (optional) time at which to get X (can be Quantity) obs=[X,Y,Z] - (optional) position of observer ...
NAME: helioX PURPOSE: return Heliocentric Galactic rectangular x-coordinate (aka "X") INPUT: t - (optional) time at which to get X (can be Quantity) obs=[X,Y,Z] - (optional) position of observer in the Galactocentric frame ...
def processors(self): """The list of all processors (preprocessors, compilers, postprocessors) used to build asset. """ return self.preprocessors + list(reversed(self.compilers)) + self.postprocessors
The list of all processors (preprocessors, compilers, postprocessors) used to build asset.
def decode(string, base): """ Given a string (string) and a numeric base (base), decode the string into an integer. Returns the integer """ base = int(base) code_string = get_code_string(base) result = 0 if base == 16: string = string.lower() while len(string) > 0: ...
Given a string (string) and a numeric base (base), decode the string into an integer. Returns the integer
def get_github_login(self, user, rol, commit_hash, repo): """ rol: author or committer """ login = None try: login = self.github_logins[user] except KeyError: # Get the login from github API GITHUB_API_URL = "https://api.github.com" commit_...
rol: author or committer
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_admin_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "outp...
Auto Generated Code
def execute(mp): """ Example process for testing. Inputs: ------- file1 raster file Parameters: ----------- Output: ------- np.ndarray """ # Reading and writing data works like this: with mp.open("file1", resampling="bilinear") as raster_file: if ra...
Example process for testing. Inputs: ------- file1 raster file Parameters: ----------- Output: ------- np.ndarray
def hide_routemap_holder_route_map_content_match_metric_metric_rmm(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.SubElem...
Auto Generated Code
def create_from_tuples(self, tuples, **args): """ Creates from a list of (subj,subj_name,obj) tuples """ amap = {} subject_label_map = {} for a in tuples: subj = a[0] subject_label_map[subj] = a[1] if subj not in amap: a...
Creates from a list of (subj,subj_name,obj) tuples
def prepare_queues(queues, lock): """Replaces queue._put() method in order to notify the waiting Condition.""" for queue in queues: queue._pebble_lock = lock with queue.mutex: queue._pebble_old_method = queue._put queue._put = MethodType(new_method, queue)
Replaces queue._put() method in order to notify the waiting Condition.
def _BuildMessageFromTypeName(type_name, descriptor_pool): """Returns a protobuf message instance. Args: type_name: Fully-qualified protobuf message type name string. descriptor_pool: DescriptorPool instance. Returns: A Message instance of type matching type_name, or None if the a Descriptor wa...
Returns a protobuf message instance. Args: type_name: Fully-qualified protobuf message type name string. descriptor_pool: DescriptorPool instance. Returns: A Message instance of type matching type_name, or None if the a Descriptor wasn't found matching type_name.
def add_arguments(self, parser): """Command line arguments for Django 1.8+""" # Add the underlying test command arguments first test_command = TestCommand() test_command.add_arguments(parser) for option in OPTIONS: parser.add_argument(*option[0], **option[1])
Command line arguments for Django 1.8+
def load(self): """Load a file in text mode""" self.meta.resolved_path = self.find_data(self.meta.path) if not self.meta.resolved_path: raise ImproperlyConfigured("Data file '{}' not found".format(self.meta.path)) print("Loading:", self.meta.path) with ope...
Load a file in text mode
def fit(self, X, y, groups=None, **fit_params): # type: (...) -> PermutationImportance """Compute ``feature_importances_`` attribute and optionally fit the base estimator. Parameters ---------- X : array-like of shape (n_samples, n_features) The training inpu...
Compute ``feature_importances_`` attribute and optionally fit the base estimator. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like, shape (n_samples,) The target values (integers that corres...