code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _init_multicast_socket(self): """ Init multicast socket :rtype: None """ self.debug("()") # Create a UDP socket self._multicast_socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) # Allow reuse of addresses ...
Init multicast socket :rtype: None
async def fastStreamedQuery(self, url, *, headers=None, verify=True): """ Send a GET request with short timeout, do not retry, and return streamed response. """ response = await self.session.get(url, headers=self._buildHeaders(headers), ...
Send a GET request with short timeout, do not retry, and return streamed response.
def _getOutputElegant(self, **kws): """ get results from elegant output according to the given keywords, input parameter format: key = sdds field name tuple, e.g.: available keywords are: - 'file': sdds fielname, file = test.sig - 'data': data array, data = (...
get results from elegant output according to the given keywords, input parameter format: key = sdds field name tuple, e.g.: available keywords are: - 'file': sdds fielname, file = test.sig - 'data': data array, data = ('s','Sx') - 'dump': h5file name, if...
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_indice, ngram_range=2) [[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2,...
def run(hostname=None, port=None, path=None, loop=None): """ The arguments are not all optional. Either a path or hostname+port should be specified; you have to specify one. """ if path: log.debug("Starting Opentrons server application on {}".format( path)) hostname, port...
The arguments are not all optional. Either a path or hostname+port should be specified; you have to specify one.
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None): """ Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ...
Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ---------- loan_id : int, optional Search for notes for a specific loan. Since a loan is broken up into a pool o...
def is_pyclustering_instance(model): """ Checks if the clustering.rst algorithm belongs to pyclustering :param model: the clustering.rst algorithm model :return: the truth value (Boolean) """ return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics])
Checks if the clustering.rst algorithm belongs to pyclustering :param model: the clustering.rst algorithm model :return: the truth value (Boolean)
def _execute_network_run(self, traj, network, network_dict, component_list, analyser_list, pre_run=False): """Generic `execute_network_run` function, handles experimental runs as well as pre-runs. See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and ...
Generic `execute_network_run` function, handles experimental runs as well as pre-runs. See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and :func:`~pypet.brian2.network.NetworkRunner.execute_network_pre_run`.
def _before_after(n_samples): """Get the number of samples before and after.""" if not isinstance(n_samples, (tuple, list)): before = n_samples // 2 after = n_samples - before else: assert len(n_samples) == 2 before, after = n_samples n_samples = before + after as...
Get the number of samples before and after.
def get_delete_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html delete link for the object.""" if text is None: text = 'Delete' return build_link(href=self.get_delete_url(), text=text, ...
Gets the html delete link for the object.
def get(self, time, interpolate='previous'): """Get the value of the time series, even in-between measured values. """ try: getter = self.getter_functions[interpolate] except KeyError: msg = ( "unknown value '{}' for interpolate, " ...
Get the value of the time series, even in-between measured values.
def spectrogram_image(mediafile, dpi=72, outdir=None, outfile=None): # TODO: Add some of the constants below as parameters """ Create spectrogram image from audio data. Return path to created image file. """ import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt imp...
Create spectrogram image from audio data. Return path to created image file.
def is_too_early_to_signup(self, now=None): """Return whether it is too early to sign up for the activity if it is a presign (48 hour logic is here).""" if now is None: now = datetime.datetime.now() activity_date = (datetime.datetime.combine(self.block.date, datetime.time(0,...
Return whether it is too early to sign up for the activity if it is a presign (48 hour logic is here).
def _getArgNames(spec): """ Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype...
Get the name of all arguments defined in a function signature. The name of * and ** arguments is normalized to "*args" and "**kwargs". :param ArgSpec spec: A function to interrogate for a signature. :return: The set of all argument names in `func`s signature. :rtype: Set[str]
def file_mode(self): """onefile, fpp, or both""" fms = self.attributes['file_mode'] eax = set() if isinstance(fms, six.string_types): fms = shlex.split(fms) for fm in fms: if fm == 'both': eax.add('fpp') eax.add('onefile') ...
onefile, fpp, or both
def _get_scale_and_shape_sim(self, transformed_lvs): """ Obtains model scale, shape, skewness latent variables for a 2d array of simulations. Parameters ---------- transformed_lvs : np.array Transformed latent variable vector (2d - with draws of each variable) ...
Obtains model scale, shape, skewness latent variables for a 2d array of simulations. Parameters ---------- transformed_lvs : np.array Transformed latent variable vector (2d - with draws of each variable) Returns ---------- - Tuple of np.arrays (each ...
def add_mea(mea_yaml_path): '''Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns ------- ''' path = os.path.abspath(mea_yaml_path) if path.endswith('.yaml') or path.endswith('.yml') and os.path.isfile(path): wit...
Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns -------
def matchremove_noun_endings(word): """Remove the noun and adverb word endings""" was_stemmed = False """common and proper noun and adjective word endings sorted by charlen, then alph""" noun_endings = ['arons', 'ains', 'aron', 'ment', 'ain', 'age', 'on', 'es', 'ée', 'ee', 'ie', 's'] for ending i...
Remove the noun and adverb word endings
def jsonify_error(message_or_exception, status_code=400): """Returns a JSON payload that indicates the request had an error.""" if isinstance(message_or_exception, Exception): message = '%s: %s' % ( message_or_exception.__class__.__name__, message_or_exception) else: message = me...
Returns a JSON payload that indicates the request had an error.
def interleaveblastresults(query, subject): """ Creates an interleaved string that resembles BLAST sequence comparisons :param query: Query sequence :param subject: Subject sequence :return: Properly formatted BLAST-like sequence comparison """ # Initialise string...
Creates an interleaved string that resembles BLAST sequence comparisons :param query: Query sequence :param subject: Subject sequence :return: Properly formatted BLAST-like sequence comparison
def pass_to_client(self, event, data, *args): """Passes data up to the client via a Queue(). :param event: :param data: :param args: :return: """ self.q.put((event, data, *args))
Passes data up to the client via a Queue(). :param event: :param data: :param args: :return:
def get_klass(self): """ Return the agnocomplete class to be used with the eventual query. """ # Extract the klass name from the URL arguments klass_name = self.kwargs.get('klass', None) klass = self.registry.get(klass_name, None) if not klass: raise H...
Return the agnocomplete class to be used with the eventual query.
def v_reference_leaf_leafref(ctx, stmt): """Verify that all leafrefs in a leaf or leaf-list have correct path""" if (hasattr(stmt, 'i_leafref') and stmt.i_leafref is not None and stmt.i_leafref_expanded is False): path_type_spec = stmt.i_leafref not_req_inst = not(path_type_spec...
Verify that all leafrefs in a leaf or leaf-list have correct path
def join(self): '''Utility function to wait all tasks to complete''' self.tasks.join() # Force each thread to break loop. for worker in self.workers: self.tasks.put(None) # Wait for all thread to terminate. for worker in self.workers: worker.join() worker.s3 = None
Utility function to wait all tasks to complete
def fundfeepool(ctx, symbol, amount, account): """ Fund the fee pool of an asset """ print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account))
Fund the fee pool of an asset
def fetch_file( download_url, filename=None, decompress=False, subdir=None, force=False, timeout=None, use_wget_if_available=False): """ Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (...
Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (unless `force` is True.) Parameters ---------- download_url : str Remote URL of file to download. filename : str, optional Local filename, used as cache key. If omitte...
def get_previous_price_list(self, currency, start_date, end_date): """ Get List of prices between two dates """ start = start_date.strftime('%Y-%m-%d') end = end_date.strftime('%Y-%m-%d') url = ( 'https://api.coindesk.com/v1/bpi/historical/close.json' ...
Get List of prices between two dates
def Kdiag(self, X): """I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$""" K_ff = np.ones(X.shape[0]) for ...
I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$
def generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" th...
Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072 if OpenSSL 1.0.0 or ne...
def power_law_anisotropy(self, r, kwargs_profile, kwargs_anisotropy, kwargs_light): """ equation (19) in Suyu+ 2010 :param r: :return: """ # first term theta_E = kwargs_profile['theta_E'] gamma = kwargs_profile['gamma'] r_ani = kwargs_anisotropy['r...
equation (19) in Suyu+ 2010 :param r: :return:
def set_attribute(library, session, attribute, attribute_state): """Sets the state of an attribute. Corresponds to viSetAttribute function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param attribute: Attribute fo...
Sets the state of an attribute. Corresponds to viSetAttribute function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param attribute: Attribute for which the state is to be modified. (Attributes.*) :param attribute...
def dict_encode(in_dict): """returns a new dictionary with encoded values useful for encoding http queries (python < 3)""" if _IS_PY2: out_dict = {} for k, v in list(in_dict.items()): if isinstance(v, unicode): v = v.encode('utf8') elif isinstance(v, str):...
returns a new dictionary with encoded values useful for encoding http queries (python < 3)
def get_avatar_upload_to(self, filename): """ Returns the path to upload the associated avatar to. """ dummy, ext = os.path.splitext(filename) return os.path.join( machina_settings.PROFILE_AVATAR_UPLOAD_TO, '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext...
Returns the path to upload the associated avatar to.
def get_data_mask_functions(is_micro): """ Returns the data mask functions. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) Table 10 — Data mask pattern generation conditions (page 50) =============== ===================== ===================================== QR Code Pattern...
Returns the data mask functions. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) Table 10 — Data mask pattern generation conditions (page 50) =============== ===================== ===================================== QR Code Pattern Micro QR Code Pattern Condition ========...
def update_by_external_id(self, api_objects): """ Update (PUT) one or more API objects by external_id. :param api_objects: """ if not isinstance(api_objects, collections.Iterable): api_objects = [api_objects] return CRUDRequest(self).put(api_objects, update_m...
Update (PUT) one or more API objects by external_id. :param api_objects:
def remove_section(file_name, section, separator='='): ''' Remove a section in an ini file. Returns the removed section as dictionary, or ``None`` if nothing was removed. API Example: .. code-block:: python import salt sc = salt.client.get_local_client() sc.cmd('target', '...
Remove a section in an ini file. Returns the removed section as dictionary, or ``None`` if nothing was removed. API Example: .. code-block:: python import salt sc = salt.client.get_local_client() sc.cmd('target', 'ini.remove_section', [path_to_ini_file, section_name...
def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictiona...
Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictionary to merge into b (DictUpperBound): dictionary to merge from merge_lists (bool): Whether to merge lists (True) o...
def get_python_path(venv_path): """ Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :return: `python` program path. """ # Get `bin` directory path bin_path = get_bin_path(venv_path) # Get `python` program path program_pa...
Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :return: `python` program path.
def _obj_display(obj, display=''): """Returns string representation of an object, either the default or based on the display template passed in. """ result = '' if not display: result = str(obj) else: template = Template(display) context = Context({'obj':obj}) res...
Returns string representation of an object, either the default or based on the display template passed in.
def send_message(self, user=None, message=None,channel=None): """ Todo connect """ self.transport.send_message(user=user, message=message, channel=channel)
Todo connect
def _gh(self, x): """ Evaluates the constraint function values. """ Pgen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u. Qgen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u. for i, gen in enumerate(self._gn): gen.p = Pgen[i] * self._base_m...
Evaluates the constraint function values.
def _get_proper_filename(file, kind, extension, date=None, possible_names=None): """Gets a proper filename for 'file', if this is a path. 'kind' should be the kind of the output file (photo, document...) 'extension' should be the extension to be added to the f...
Gets a proper filename for 'file', if this is a path. 'kind' should be the kind of the output file (photo, document...) 'extension' should be the extension to be added to the file if the filename doesn't have any yet 'date' should be when this file was originally...
def extract_nodes(soup, nodename, attr = None, value = None): """ Returns a list of tags (nodes) from the given soup matching the given nodename. If an optional attribute and value are given, these are used to filter the results further.""" tags = soup.find_all(nodename) if attr != None and valu...
Returns a list of tags (nodes) from the given soup matching the given nodename. If an optional attribute and value are given, these are used to filter the results further.
def register_factory(self, specification, factory, scope=None): """ Shortcut for creating and registering a :py:class:`wiring.providers.FactoryProvider`. """ self.register_provider( specification, FactoryProvider(factory, scope=scope) )
Shortcut for creating and registering a :py:class:`wiring.providers.FactoryProvider`.
def set_siren_volume(self, volume): """ :param volume: one of [low, medium, high] """ values = { "desired_state": { "siren_volume": volume } } response = self.api_interface.set_device_state(self, values) self._upda...
:param volume: one of [low, medium, high]
def create_schema(self): """Create all necessary tables""" cursor = self.cursor execute = cursor.execute execute('SHOW TABLES') tables = {table for table, in cursor} if 'gauged_data' not in tables: execute("""CREATE TABLE gauged_data ( namespac...
Create all necessary tables
def sync(args): """ Implement the 'greg sync' command """ import operator session = c.Session(args) if "all" in args["names"]: targetfeeds = session.list_feeds() else: targetfeeds = [] for name in args["names"]: if name not in session.feeds: ...
Implement the 'greg sync' command
def spline_interpolate(x_axis, y_axis, x_new_axis): """Interpolate a y = f(x) function using Spline interpolation algorithm, x_new_axis has to be in range of x_axis. `Spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_ is a popular interpolation method. Way more accurate than l...
Interpolate a y = f(x) function using Spline interpolation algorithm, x_new_axis has to be in range of x_axis. `Spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_ is a popular interpolation method. Way more accurate than linear interpolate in average
def read(self, size=None): # pylint: disable=missing-docstring """Read at most size bytes from this slice. Compared to other streams, there is one case where we may unexpectedly raise an exception on read: if the underlying stream is exhausted (i.e. returns no bytes on read), and the s...
Read at most size bytes from this slice. Compared to other streams, there is one case where we may unexpectedly raise an exception on read: if the underlying stream is exhausted (i.e. returns no bytes on read), and the size of this slice indicates we should still be able to read more by...
def pred_from_structures(self, target_species, structures_list, remove_duplicates=True, remove_existing=False): """ performs a structure prediction targeting compounds containing all of the target_species, based on a list of structure (those structures can fo...
performs a structure prediction targeting compounds containing all of the target_species, based on a list of structure (those structures can for instance come from a database like the ICSD). It will return all the structures formed by ionic substitutions with a probability higher than th...
def stepBy(self, steps): """ Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10). """ ...
Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10).
def combine_slices(slice_datasets, rescale=None): ''' Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM patient'...
Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM patient's coordinate system. Returns a two-tuple containing the 3...
def update_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score): """ Updates a single topic score, for a single user. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer ...
Updates a single topic score, for a single user. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. - user_twitter_id: A Twitter user iden...
def seek(self, offset, whence): """Changes the current file position of this file. The file current position always applies to the :py:func:`IFile.read` method. Same for the :py:func:`IFile.write` method it except when the :py:func:`IFile.access_mode` is :py:attr:`FileAccess...
Changes the current file position of this file. The file current position always applies to the :py:func:`IFile.read` method. Same for the :py:func:`IFile.write` method it except when the :py:func:`IFile.access_mode` is :py:attr:`FileAccessMode.append_only` or :py:attr:`Fil...
async def read(self, count=-1): """ :py:func:`asyncio.coroutine` :py:meth:`aioftp.StreamIO.read` proxy """ await self.wait("read") start = _now() data = await super().read(count) self.append("read", data, start) return data
:py:func:`asyncio.coroutine` :py:meth:`aioftp.StreamIO.read` proxy
def create_api(self): """Create the REST API.""" created_api = self.client.create_rest_api(name=self.trigger_settings.get('api_name', self.app_name)) api_id = created_api['id'] self.log.info("Successfully created API") return api_id
Create the REST API.
def hypercube(number_of_samples, variables): """ This implements Latin Hypercube Sampling. See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is :param number_of_samples: number of segments/samples :param variables: initial parameters and conditions (lis...
This implements Latin Hypercube Sampling. See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is :param number_of_samples: number of segments/samples :param variables: initial parameters and conditions (list of ranges, i.e. (70, 110), (0.1, 0.5) ..) :return:
def _dilated_conv_layer(self, output_channels, dilation_rate, apply_relu, name): """Create a dilated convolution layer. Args: output_channels: int. Number of output channels for each pixel. dilation_rate: int. Represents how many pixels each stride offset will move...
Create a dilated convolution layer. Args: output_channels: int. Number of output channels for each pixel. dilation_rate: int. Represents how many pixels each stride offset will move. A value of 1 indicates a standard convolution. apply_relu: bool. If True, a ReLU non-linearlity is added. ...
def create(cls, changes, ref, excluded_categories=set()): """Create a new change in all queues. :param changes: the change types, an iterable containing :class:`ChangeType` :param ref: the object reference (returned by `obj_ref`) of the changed ob...
Create a new change in all queues. :param changes: the change types, an iterable containing :class:`ChangeType` :param ref: the object reference (returned by `obj_ref`) of the changed object :param excluded_categories: set of categories (IDs) whos...
def get_untranscribed_prefixes_from_file(target_directory: Path) -> List[str]: """ The file "untranscribed_prefixes.txt" will specify prefixes which do not have an associated transcription file if placed in the target directory. This will fetch those prefixes from that file and will return an empty ...
The file "untranscribed_prefixes.txt" will specify prefixes which do not have an associated transcription file if placed in the target directory. This will fetch those prefixes from that file and will return an empty list if that file does not exist. See find_untranscribed_wavs function for finding un...
def fail_acs_response(request, *args, **kwargs): """ Serves as a common mechanism for ending ACS in case of any SAML related failure. Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as suitable for the project. The default behavior uses SAML specific template that is render...
Serves as a common mechanism for ending ACS in case of any SAML related failure. Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as suitable for the project. The default behavior uses SAML specific template that is rendered on any ACS error, but this can be simply changed s...
def Down(self, n = 1, dl = 0): """下方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.down_key, n)
下方向键n次
def get_saml_slos(cls, logout_request): """returns saml logout ticket info""" try: root = etree.fromstring(logout_request) return root.xpath( "//samlp:SessionIndex", namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"}) except etree...
returns saml logout ticket info
def copy(self): """Returns a copy of a Layout instance.""" layout_copy = type(self)() layout_copy._p2v = self._p2v.copy() layout_copy._v2p = self._v2p.copy() return layout_copy
Returns a copy of a Layout instance.
def init_app(self, app, session=None, parameters=None): """Initializes snow extension Set config default and find out which client type to use :param app: App passed from constructor or directly to init_app (factory) :param session: requests-compatible session to pass along to init_app...
Initializes snow extension Set config default and find out which client type to use :param app: App passed from constructor or directly to init_app (factory) :param session: requests-compatible session to pass along to init_app :param parameters: `ParamsBuilder` object passed to `Clien...
def enable_peer_bfd(self, **kwargs): """BFD enable for each specified peer. Args: rbridge_id (str): Rbridge to configure. (1, 225, etc) peer_ip (str): Peer IPv4 address for BFD setting. delete (bool): True if BFD configuration should be deleted. Defa...
BFD enable for each specified peer. Args: rbridge_id (str): Rbridge to configure. (1, 225, etc) peer_ip (str): Peer IPv4 address for BFD setting. delete (bool): True if BFD configuration should be deleted. Default value will be False if not specified. ...
def getProcessName(self, pid): """ Searches all processes for the given PID, then returns the originating command """ ps = subprocess.check_output(["ps", "aux"]).decode("ascii") processes = ps.split("\n") cols = len(processes[0].split()) - 1 for row in processes[1:]: ...
Searches all processes for the given PID, then returns the originating command
def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095). """ for i in range(len(self._pins)): self._device.set_pwm(self._pins[i], 0, raw_values[i])
Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095).
def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1...
Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple
def _add_resource_descriptions_to_pools(self, meta_list): """ Takes a list of resource descriptions adding them to the resource pool they belong to scheduling them for loading. """ if not meta_list: return for meta in meta_list: getattr(r...
Takes a list of resource descriptions adding them to the resource pool they belong to scheduling them for loading.
def _set_fcoe_map_cee_map(self, v, load=False): """ Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_map_cee_map is considered as a private method. Backends ...
Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_map_cee_map is considered as a private method. Backends looking to populate this variable should do so via calli...
def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs): """ Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by...
Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by a matching alias, and the groupby_alias is set True then the GROUP BY clause wil...
def append_dictionary_to_file(localization_key_to_comment, file_path, section_name): """ Appends dictionary of localization keys and comments to a file Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_path (str): The path of the file to append to....
Appends dictionary of localization keys and comments to a file Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_path (str): The path of the file to append to. section_name (str): The name of the section.
def collect_translations(self): """Collect all `domain` translations and return `Tuple[languages, locale_data]`""" languages = {} locale_data = {} for language_code, label in settings.LANGUAGES: languages[language_code] = '%s' % label # Create django translation...
Collect all `domain` translations and return `Tuple[languages, locale_data]`
def template_tag(library, name): """ Decorator to register class tags :param library: The template tag library, typically instantiated as ``register = Library()``. :type library: :class:`~django.template.Library` :param name: The name of the template tag :type name: str Example: .. co...
Decorator to register class tags :param library: The template tag library, typically instantiated as ``register = Library()``. :type library: :class:`~django.template.Library` :param name: The name of the template tag :type name: str Example: .. code-block:: python @template_tag(regi...
def transform(self, trans): '''Return a copy of this neurite with a 3D transformation applied''' clone = deepcopy(self) for n in clone.iter_sections(): n.points[:, 0:3] = trans(n.points[:, 0:3]) return clone
Return a copy of this neurite with a 3D transformation applied
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs): """ store this object, close it if we opened it """ if append: f = lambda store: store.append(key, value, **kwargs) else: f = lambda store: store.put(key, value, **kwargs) pa...
store this object, close it if we opened it
def prt_txt(self, prt=sys.stdout, pre=''): """Print letters, descendant count, and GO information.""" data_nts = self.get_d1nts() for ntdata in data_nts: prt.write("{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\n".format( PRE=pre, L=ntdata.D1, ...
Print letters, descendant count, and GO information.
def define_cyclic_can_msg(self, channel, can_msg=None): """ Defines a list of CAN messages for automatic transmission. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN messages ...
Defines a list of CAN messages for automatic transmission. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN messages (up to 16, see structure :class:`CanMsg`), or None to delete an older list.
def AddHeader(self, header, value): '''Add a header to send. ''' self.user_headers.append((header, value)) return self
Add a header to send.
def people_per_project(self, project_id, company_id): """ This will return all of the people in the given company that can access the given project. """ path = '/projects/%u/contacts/people/%u' % (project_id, company_id) return self._request(path)
This will return all of the people in the given company that can access the given project.
def _parse_response(self, resp): """Gets the authentication information from the returned JSON.""" access = resp["access"] token = access.get("token") self.token = token["id"] self.tenant_id = token["tenant"]["id"] self.tenant_name = token["tenant"]["name"] self.e...
Gets the authentication information from the returned JSON.
def open_stream(self, destination, timeout_ms=None): """Opens a new stream to a destination service on the device. Not the same as the posix 'open' or any other Open methods, this corresponds to the OPEN message described in the ADB protocol documentation mentioned above. It creates a stream (uniquely...
Opens a new stream to a destination service on the device. Not the same as the posix 'open' or any other Open methods, this corresponds to the OPEN message described in the ADB protocol documentation mentioned above. It creates a stream (uniquely identified by remote/local ids) that connects to a part...
def _convert_source_mapping(offset, slither): ''' Convert a text offset to a real offset see https://solidity.readthedocs.io/en/develop/miscellaneous.html#source-mappings Returns: (dict): {'start':0, 'length':0, 'filename': 'file.sol'} ''' sourceUnits = slithe...
Convert a text offset to a real offset see https://solidity.readthedocs.io/en/develop/miscellaneous.html#source-mappings Returns: (dict): {'start':0, 'length':0, 'filename': 'file.sol'}
def apply_files_filter(self, frame, filename, force_check_project_scope): ''' Should only be called if `self.is_files_filter_enabled == True`. Note that it covers both the filter by specific paths includes/excludes as well as the check which filters out libraries if not in the project s...
Should only be called if `self.is_files_filter_enabled == True`. Note that it covers both the filter by specific paths includes/excludes as well as the check which filters out libraries if not in the project scope. :param force_check_project_scope: Check that the file is in the pro...
def usernameFromRequest(request): """ Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str} """ username = request.args.get('username', [''])[0] if '@' not in username: username...
Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str}
def add_to_win32_PATH(script_fpath, *add_path_list): r""" Writes a registery script to update the PATH variable into the sync registry CommandLine: python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin" Example: >>> # DISABLE_DOCTEST ...
r""" Writes a registery script to update the PATH variable into the sync registry CommandLine: python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin" Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_win32 impor...
def _next_mutation(self): ''' :return: True if mutated, False otherwise ''' if self._keep_running(): current_idx = self.model.current_index() self.session_info.current_index = current_idx next_idx = self._test_list.current() if next_idx is ...
:return: True if mutated, False otherwise
def gen_source_models(self, gsim_lt): """ Yield empty LtSourceModel instances (one per effective realization) """ samples_by_lt_path = self.samples_by_lt_path() for i, rlz in enumerate(get_effective_rlzs(self)): smpath = rlz.lt_path num_samples = samples_b...
Yield empty LtSourceModel instances (one per effective realization)
def summary_gradient_updates(grads, opt, lr): """get summary ops for the magnitude of gradient updates""" # strategy: # make a dict of variable name -> [variable, grad, adagrad slot] vars_grads = {} for v in tf.trainable_variables(): vars_grads[v.name] = [v, None, None] for g, v in grad...
get summary ops for the magnitude of gradient updates
def _configure_common( self, prefix, fallback_level, fallback_format, handler_name, handler, custom_args='' ): """commom configuration code Args: prefix (str): A prefix for the `log_level` and `log_forma...
commom configuration code Args: prefix (str): A prefix for the `log_level` and `log_format` keys to use with the config. #FIXME: Hacky, add separate sections for each logger config? fallback_level (str): Fallback/minimum log level, for if config does not have one. fallback_f...
def best_unique_genomes(self, n): """Returns the most n fit genomes, with no duplication.""" best_unique = {} for g in self.most_fit_genomes: best_unique[g.key] = g best_unique_list = list(best_unique.values()) def key(genome): return genome.fitness ...
Returns the most n fit genomes, with no duplication.
def getbalance(self, **params): """Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance """ if not all([self.api_key, self.api_secret]): raise Auth...
Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
def write_can_msg(self, channel, can_msg): """ Transmits one ore more CAN messages through the specified CAN channel of the device. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg:...
Transmits one ore more CAN messages through the specified CAN channel of the device. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN message structure (see structure :class:`CanMsg`)....
def send_scp_burst(self, buffer_size, window_size, parameters_and_callbacks): """Send a burst of SCP packets and call a callback for each returned packet. Parameters ---------- buffer_size : int Number of bytes held in an SCP buffer by SARK, de...
Send a burst of SCP packets and call a callback for each returned packet. Parameters ---------- buffer_size : int Number of bytes held in an SCP buffer by SARK, determines how many bytes will be expected in a socket. window_size : int Number o...
def ensure_working_tree(self): """ Make sure the local repository has working tree support. :raises: :exc:`~vcs_repo_mgr.exceptions.MissingWorkingTreeError` when the local repository doesn't support a working tree. """ if not self.supports_working_tree: ...
Make sure the local repository has working tree support. :raises: :exc:`~vcs_repo_mgr.exceptions.MissingWorkingTreeError` when the local repository doesn't support a working tree.
def calculate_one_hot_encoder_output_shapes(operator): ''' Allowed input/output patterns are 1. [N, 1] ---> [N, C'] C' is the total number of categorical values. ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1) if operator.inputs[0].type.shape[1] ...
Allowed input/output patterns are 1. [N, 1] ---> [N, C'] C' is the total number of categorical values.
def _set_vlan_and_bd(self, v, load=False): """ Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_and_bd is considered as a private method. Backends looking to pop...
Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_and_bd is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
def wrap_handler(cls, handler, protocol, **kwargs): ''' Wrap a request handler with the matching protocol handler ''' def _wrapper(request, *args, **kwargs): instance = cls(request=request, **kwargs) if protocol == Resource.Protocol.http: return instance._wrap_htt...
Wrap a request handler with the matching protocol handler
def reduce_fit(interface, state, label, inp): """ Function separates aggregation of continuous and discrete features. For continuous features it aggregates partially calculated means and variances and returns them. For discrete features it aggregates pairs and returns them. Pairs with label occurrences ...
Function separates aggregation of continuous and discrete features. For continuous features it aggregates partially calculated means and variances and returns them. For discrete features it aggregates pairs and returns them. Pairs with label occurrences are used to calculate prior probabilities