code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def openSourceWindow(self, current_class, method=None): """Main function to open a decompile source window It checks if it already opened and open that tab, otherwise, initialize a new window. """ log.debug("openSourceWindow for %s" % current_class) sourcewin = sel...
Main function to open a decompile source window It checks if it already opened and open that tab, otherwise, initialize a new window.
def _CalculateYLines(self, dists): """Builds a list with y-coordinates for the horizontal lines in the graph. Args: # One integer for each pair of stations # indicating the approximate distance dists: [0,33,140, ... ,X] Returns: # One integer y-coordinate for each station normalize...
Builds a list with y-coordinates for the horizontal lines in the graph. Args: # One integer for each pair of stations # indicating the approximate distance dists: [0,33,140, ... ,X] Returns: # One integer y-coordinate for each station normalized between # 0 and X, where X is the ...
def node_path_transforms(self, node): """Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters -------...
Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters ---------- node : instance of Node T...
def create(self, build_sid): """ Create a new DeploymentInstance :param unicode build_sid: The build_sid :returns: Newly created DeploymentInstance :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance """ data = values.of({'BuildSi...
Create a new DeploymentInstance :param unicode build_sid: The build_sid :returns: Newly created DeploymentInstance :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance
def Adapter(self, **kw): ''' .. TODO:: move this documentation into model/adapter.py?... The Adapter constructor supports the following parameters: :param devID: sets the local adapter\'s device identifier. For servers, this should be the externally accessible URL that launches the SyncML...
.. TODO:: move this documentation into model/adapter.py?... The Adapter constructor supports the following parameters: :param devID: sets the local adapter\'s device identifier. For servers, this should be the externally accessible URL that launches the SyncML transaction, and for clients t...
def num_lines(self): """ Lazy evaluation of the number of lines. Returns None for stdin input currently. """ if self.from_stdin: return None if not self._num_lines: self._iterate_lines() return self._num_lines
Lazy evaluation of the number of lines. Returns None for stdin input currently.
def info(self, headers=None): """Retrieves information of the node being connected to via the root endpoint ``'/'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the node that this instance is connected to....
Retrieves information of the node being connected to via the root endpoint ``'/'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the node that this instance is connected to. Some information that may be interesting...
def _writeFile(cls, filePath, content, encoding = None): """Safe file writing. Most common mistakes are checked against and reported before write operation. After that, if anything unexpected happens, user won't be left without data or with corrupted one as this method writes to a temporary file...
Safe file writing. Most common mistakes are checked against and reported before write operation. After that, if anything unexpected happens, user won't be left without data or with corrupted one as this method writes to a temporary file and then simply renames it (which should be atomic operatio...
def _find_package(c): """ Try to find 'the' One True Package for this project. Mostly for obtaining the ``_version`` file within it. Uses the ``packaging.package`` config setting if defined. If not defined, fallback is to look for a single top-level Python package (directory containing ``__ini...
Try to find 'the' One True Package for this project. Mostly for obtaining the ``_version`` file within it. Uses the ``packaging.package`` config setting if defined. If not defined, fallback is to look for a single top-level Python package (directory containing ``__init__.py``). (This search ignores a ...
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
Normalize the state
def inject_print_functions(module_name=None, module_prefix='[???]', DEBUG=False, module=None): """ makes print functions to be injected into the module """ module = _get_module(module_name, module) if SILENT: def print(*args): """ silent builtins.print ...
makes print functions to be injected into the module
def _recenter_epsf(self, epsf_data, epsf, centroid_func=centroid_com, box_size=5, maxiters=20, center_accuracy=1.0e-4): """ Calculate the center of the ePSF data and shift the data so the ePSF center is at the center of the ePSF data array. Parameters ----...
Calculate the center of the ePSF data and shift the data so the ePSF center is at the center of the ePSF data array. Parameters ---------- epsf_data : 2D `~numpy.ndarray` A 2D array containing the ePSF image. epsf : `EPSFModel` object The ePSF model. ...
def argmin_list(seq, fn): """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or'] """ best_score, best = fn(seq[0]), [] for x in seq: x_score = fn(x) if x_score < best_score: best, best_...
Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or']
def hotplugRegisterCallback( self, callback, # pylint: disable=undefined-variable events=HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT, flags=HOTPLUG_ENUMERATE, vendor_id=HOTPLUG_MATCH_ANY, product_id=HOTPLUG_MATCH_ANY, dev_c...
Registers an hotplug callback. On success, returns an opaque value which can be passed to hotplugDeregisterCallback. Callback must accept the following positional arguments: - this USBContext instance - an USBDevice instance If device has left, configuration descriptors...
def resize(self, size, interp='nearest'): """Resize the image. Parameters ---------- size : int, float, or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : :obj:`str`...
Resize the image. Parameters ---------- size : int, float, or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : :obj:`str`, optional Interpolation to use for re-si...
def getPredictionResults(network, clRegionName): """Get prediction results for all prediction steps.""" classifierRegion = network.regions[clRegionName] actualValues = classifierRegion.getOutputData("actualValues") probabilities = classifierRegion.getOutputData("probabilities") steps = classifierRegion.getSel...
Get prediction results for all prediction steps.
def transform_from_rot_trans(R, t): """Transforation matrix from rotation matrix and translation vector.""" R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
Transforation matrix from rotation matrix and translation vector.
def discard_incoming_messages(self): """ Discard all incoming messages for the time of the context manager. """ # Flush any received message so far. self.inbox.clear() # This allows nesting of discard_incoming_messages() calls. previous = self._discard_incoming_m...
Discard all incoming messages for the time of the context manager.
def minimize(self, loss_fn, x, optim_state): """ Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: ...
Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: new_x: list of Tensor, updated version of `x` ...
def create_context_menu(self, extended): """Create the context menu.""" menu = Gtk.Menu() self._menu(menu, extended) return menu
Create the context menu.
def choice_info(self): """View .info file """ info = ReadSBo(self.sbo_url).info(self.name, ".info") fill = self.fill_pager(info) self.pager(info + fill)
View .info file
async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sen...
Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while...
def univariate_envelope_plot(x, mean, std, ax=None, base_alpha=0.375, envelopes=[1, 3], lb=None, ub=None, expansion=10, **kwargs): """Make a plot of a mean curve with uncertainty envelopes. """ if ax is None: f = plt.figure() ax = f.add_subplot(1, 1, 1) elif ax == 'gca': ax = plt...
Make a plot of a mean curve with uncertainty envelopes.
def GetUser(self, sid=None, uid=None, username=None): """Retrieve a User based on sid, uid or username. On windows we first get a SID and use it to find the username. We want to avoid combining users with name collisions, which occur when local users have the same username as domain users (something l...
Retrieve a User based on sid, uid or username. On windows we first get a SID and use it to find the username. We want to avoid combining users with name collisions, which occur when local users have the same username as domain users (something like Admin is particularly common). So if a SID is provid...
def _withholdOffbids(self): """ Withholds offers/bids with invalid (<= 0.0) quantities or prices outwith the set limits. """ limits = self.limits # Eliminate offers (but not bids) above 'price_cap'. if not limits.has_key('max_offer'): limits['max_offer'] ...
Withholds offers/bids with invalid (<= 0.0) quantities or prices outwith the set limits.
def p_union(self, p): '''union : UNION IDENTIFIER '{' field_seq '}' annotations''' p[0] = ast.Union( name=p[2], fields=p[4], annotations=p[6], lineno=p.lineno(2) )
union : UNION IDENTIFIER '{' field_seq '}' annotations
def get(self, term): # type: (Any) -> Type[ChomskyTermNonterminal] """ Get nonterminal rewritable to term. If the rules is not in the grammar, nonterminal and rule rewritable to terminal are add into grammar. :param term: Term for which get the nonterminal. :return: Choms...
Get nonterminal rewritable to term. If the rules is not in the grammar, nonterminal and rule rewritable to terminal are add into grammar. :param term: Term for which get the nonterminal. :return: ChomskyTermNonterminal class for terminal.
def _compute_ambig_ll(self): """ m._compute_ambig_ll() -- Extend log-likelihood matrix to include ambiguity codes e.g. What the score of a 'S'? Here we use the max of C and G. """ for Dll in self.ll: for L in one2two.keys(): ...
m._compute_ambig_ll() -- Extend log-likelihood matrix to include ambiguity codes e.g. What the score of a 'S'? Here we use the max of C and G.
def _from_center_cartesian( self, x: float, y: float, z: float) -> Point: """ Specifies an arbitrary point relative to the center of the well based on percentages of the radius in each axis. For example, to specify the back-right corner of a well at 1/4 of the well depth from...
Specifies an arbitrary point relative to the center of the well based on percentages of the radius in each axis. For example, to specify the back-right corner of a well at 1/4 of the well depth from the bottom, the call would be `_from_center_cartesian(1, 1, -0.5)`. No checks are perfor...
def get_mol(chebi_id): '''Returns mol''' chebi_id_regexp = '^\\d+\\,' + str(chebi_id) + '\\,.*' mol_file_end_regexp = '\",mol,\\dD' this_structure = [] filename = get_file('structures.csv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: in_chebi_id = False next...
Returns mol
def _find_file(self, load): ''' Convenience function for calls made using the RemoteClient ''' path = load.get('path') if not path: return {'path': '', 'rel': ''} tgt_env = load.get('saltenv', 'base') return self.find_file(path, tgt...
Convenience function for calls made using the RemoteClient
def read_file(file_path, mode = 'rt'): """ Read the contents of a file :param file_path: Path of the file to be read :return: Contents of the file """ contents = '' with open(file_path, mode) as f: contents = f.read() return contents
Read the contents of a file :param file_path: Path of the file to be read :return: Contents of the file
def resample_image_to_target(image, target, interp_type='linear', imagetype=0, verbose=False, **kwargs): """ Resample image by using another image as target reference. This function uses ants.apply_transform with an identity matrix to achieve proper resampling. ANTsR function: `resampleImageT...
Resample image by using another image as target reference. This function uses ants.apply_transform with an identity matrix to achieve proper resampling. ANTsR function: `resampleImageToTarget` Arguments --------- image : ANTsImage image to resample target : ANTsImage ...
def parse(self, s, tokenize=True, tags=True, chunks=True, relations=False, lemmata=False, encoding="utf-8", **kwargs): """ Takes a string (sentences) and returns a tagged Unicode string (TaggedString). Sentences in the output are separated by newlines. With tokenize=True, punctuation is ...
Takes a string (sentences) and returns a tagged Unicode string (TaggedString). Sentences in the output are separated by newlines. With tokenize=True, punctuation is split from words and sentences are separated by \n. With tags=True, part-of-speech tags are parsed (NN, VB, IN, ...). ...
def create_connection(self, session=None): """ Create connection in the Connection table, according to whether it uses proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated. :param session: Session of the SQL Alchemy ORM (automatically generated with ...
Create connection in the Connection table, according to whether it uses proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator).
def solarcalcs(self): """ Solar Calculation Mutates RSM, BEM, and UCM objects based on following parameters: UCM # Urban Canopy - Building Energy Model object BEM # Building Energy Model object simTime # Simulation time bbject RSM ...
Solar Calculation Mutates RSM, BEM, and UCM objects based on following parameters: UCM # Urban Canopy - Building Energy Model object BEM # Building Energy Model object simTime # Simulation time bbject RSM # Rural Site & Vertical Diffusi...
def status_messages(self): """ Returns status messages if any """ messages = IStatusMessage(self.request) m = messages.show() for item in m: item.id = idnormalizer.normalize(item.message) return m
Returns status messages if any
def store(self, name=None): """ Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository """ if name is None: name = self.get_default_driver() self._stores[name] = self._get(name) retu...
Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository
def __params_descriptor(self, message_type, request_kind, path, method_id): """Describe the parameters of a method. If the message_type is not a ResourceContainer, will fall back to __params_descriptor_without_container (which will eventually be deprecated). If the message type is a ResourceContainer,...
Describe the parameters of a method. If the message_type is not a ResourceContainer, will fall back to __params_descriptor_without_container (which will eventually be deprecated). If the message type is a ResourceContainer, then all path/query parameters will come from the ResourceContainer This metho...
def get_ldap_user_membership(self, user_dn): """Retrieve user membership from LDAP server.""" #Escape parenthesis in DN membership_filter = self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_FILTER.replace('{distinguishedName}', user_dn.replace('(', "\(").replace(')', "\)")) try: uri, grou...
Retrieve user membership from LDAP server.
def tempo_account_add_account(self, data=None): """ Creates Account, adding new Account requires the Manage Accounts Permission. :param data: String then it will convert to json :return: """ url = 'rest/tempo-accounts/1/account/' if data is None: retur...
Creates Account, adding new Account requires the Manage Accounts Permission. :param data: String then it will convert to json :return:
def save(self): """ Update the SouceReading information for the currently recorded observations and then flush those to a file. @return: mpc_filename of the resulting save. """ self.get_writer().flush() mpc_filename = self.get_writer().get_filename() self.get_writ...
Update the SouceReading information for the currently recorded observations and then flush those to a file. @return: mpc_filename of the resulting save.
def log_print_request(method, url, query_params=None, headers=None, body=None): """ Log an HTTP request data in a user-friendly representation. :param method: HTTP method :param url: URL :param query_params: Query parameters in the URL :param headers: Headers (dict) :param body: Body (raw b...
Log an HTTP request data in a user-friendly representation. :param method: HTTP method :param url: URL :param query_params: Query parameters in the URL :param headers: Headers (dict) :param body: Body (raw body, string) :return: None
def file_verify( sender_blockchain_id, sender_key_id, input_path, sig, config_path=CONFIG_PATH, wallet_keys=None ): """ Verify that a file was signed with the given blockchain ID @config_path should be for the *client*, not blockstack-file Return {'status': True} on succes Return {'error': ...} on e...
Verify that a file was signed with the given blockchain ID @config_path should be for the *client*, not blockstack-file Return {'status': True} on succes Return {'error': ...} on error
def create_bar_chart(self, x_labels, y_values, y_label): """Creates bar char :param x_labels: Names for each variable :param y_values: Values of x labels :param y_label: Label of y axis :return: Bar chart """ self.setup(0.25) ax1 = self.get_ax() a...
Creates bar char :param x_labels: Names for each variable :param y_values: Values of x labels :param y_label: Label of y axis :return: Bar chart
def get(tgt, fun, tgt_type='glob'): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces ''' ret = salt.utils.minions.mine_get(tgt, fun, tgt_typ...
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces
def get_health_monitor(self, loadbalancer): """ Returns a dict representing the health monitor for the load balancer. If no monitor has been configured, returns an empty dict. """ uri = "/loadbalancers/%s/healthmonitor" % utils.get_id(loadbalancer) resp, body = se...
Returns a dict representing the health monitor for the load balancer. If no monitor has been configured, returns an empty dict.
def _to_pywintypes(row): """convert values in a row to types accepted by excel""" def _pywintype(x): if isinstance(x, dt.date): return dt.datetime(x.year, x.month, x.day, tzinfo=dt.timezone.utc) elif isinstance(x, (dt.datetime, pa.Timestamp)): if x.tzinfo is None: ...
convert values in a row to types accepted by excel
def save_colormap(self, name=None): """ Saves the colormap with the specified name. None means use internal name. (See get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: invalid name." # get the colormaps ...
Saves the colormap with the specified name. None means use internal name. (See get_name())
def cmd_asterix(self, args): '''asterix command parser''' usage = "usage: asterix <set|start|stop|restart|status>" if len(args) == 0: print(usage) return if args[0] == "set": self.asterix_settings.command(args[1:]) elif args[0] == "start": ...
asterix command parser
def matchesTripleExprRef(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExprLabel, _: DebugContext) -> bool: """ expr is an tripleExprRef and satisfies(value, tripleExprWithId(tripleExprRef), G, m). The tripleExprWithId function is defined in Triple Expression Reference Requirement below. """ expr =...
expr is an tripleExprRef and satisfies(value, tripleExprWithId(tripleExprRef), G, m). The tripleExprWithId function is defined in Triple Expression Reference Requirement below.
def update_flags(self, idlist, flags): """ A thin back compat wrapper around build_update(flags=X) """ return self.update_bugs(idlist, self.build_update(flags=flags))
A thin back compat wrapper around build_update(flags=X)
def train(self, X_feat, X_seq, y, X_feat_valid=None, X_seq_valid=None, y_valid=None, n_cores=3): """Train the CONCISE model :py:attr:`X_feat`, :py:attr:`X_seq`, py:attr:`y` are preferrably returned by the :py:func:`concise.prepare_data` function. Args: X...
Train the CONCISE model :py:attr:`X_feat`, :py:attr:`X_seq`, py:attr:`y` are preferrably returned by the :py:func:`concise.prepare_data` function. Args: X_feat: Numpy (float) array of shape :code:`(N, D)`. Feature design matrix storing :code:`N` training samples and :code:`D` features ...
def ignore_event(self, event_id): """Verify event id against list of events to ignore. >>> e = EventHandling(ignore=[ ... 'test1_00', ... 'test2_*', ... ]) >>> e.ignore_event('test1_00') True >>> e.ignore_event('test2_00') True >>> e.i...
Verify event id against list of events to ignore. >>> e = EventHandling(ignore=[ ... 'test1_00', ... 'test2_*', ... ]) >>> e.ignore_event('test1_00') True >>> e.ignore_event('test2_00') True >>> e.ignore_event('test3_00') False
async def async_request(session, url, **kwargs): """Do a web request and manage response.""" _LOGGER.debug("Sending %s to %s", kwargs, url) try: res = await session(url, **kwargs) if res.content_type != 'application/json': raise ResponseError( "Invalid content t...
Do a web request and manage response.
def _get_billing_cycle_number(self, billing_cycle): """Gets the 1-indexed number of the billing cycle relative to the provided billing cycle""" begins_before_initial_date = billing_cycle.date_range.lower < self.initial_billing_cycle.date_range.lower if begins_before_initial_date: rai...
Gets the 1-indexed number of the billing cycle relative to the provided billing cycle
def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --loc...
Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/sa...
def drop_index(self, raw): """ Executes a drop index command. { "op" : "c", "ns" : "testdb.$cmd", "o" : { "dropIndexes" : "testcoll", "index" : "nuie_1" } } """ dbname = raw['ns'].split('.', 1)[0] collname = raw['o']['dropIndexes']...
Executes a drop index command. { "op" : "c", "ns" : "testdb.$cmd", "o" : { "dropIndexes" : "testcoll", "index" : "nuie_1" } }
def create_role(self, name, policies=None, ttl=None, max_ttl=None, period=None, bound_service_principal_ids=None, bound_group_ids=None, bound_location=None, bound_subscription_ids=None, bound_resource_group_names=None, bound_scale_sets=None, mount_point=DEFAULT_MOUNT_POINT): ...
Create a role in the method. Role types have specific entities that can perform login operations against this endpoint. Constraints specific to the role type must be set on the role. These are applied to the authenticated entities attempting to login. Supported methods: POST: /auth...
def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
Return the id of a label's for attribute
def refine_peaks_spectrum(sx, ixpeaks, nwinwidth, method=None, geometry=None, debugplot=0): """Refine line peaks in spectrum. Parameters ---------- sx : 1d numpy array, floats Input array. ixpeaks : 1d numpy array, int Initial peak locations, in array coord...
Refine line peaks in spectrum. Parameters ---------- sx : 1d numpy array, floats Input array. ixpeaks : 1d numpy array, int Initial peak locations, in array coordinates (integers). These values can be the output from the function find_peaks_spectrum(). nwinwidth : in...
def _import_module(self, module_path): """Dynamically import a module returning a handle to it. :param str module_path: The module path :rtype: module """ LOGGER.debug('Importing %s', module_path) try: return __import__(module_path) except ImportErro...
Dynamically import a module returning a handle to it. :param str module_path: The module path :rtype: module
def run_supernova_keyring(ctx, action, environment, parameter): """ Sets or retrieves credentials stored in your system's keyring using the python-keyring module. Global credentials can be shared between multiple configuration sections: \b [prod] OS_PASSWORD=USE_KEYRING['sso_passwo...
Sets or retrieves credentials stored in your system's keyring using the python-keyring module. Global credentials can be shared between multiple configuration sections: \b [prod] OS_PASSWORD=USE_KEYRING['sso_password'] ... \b [staging] OS_PASSWORD=USE_KEYRING['...
async def _flush(self, request: 'Request', stacks: List[Stack]): """ Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call. """ for stack in stacks: await self.platform.send(request, stack)
Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call.
async def set_focus(self, set_focus_request): """Set focus to a conversation.""" response = hangouts_pb2.SetFocusResponse() await self._pb_request('conversations/setfocus', set_focus_request, response) return response
Set focus to a conversation.
def inputcooker(self): """Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ try: while True: c = self._inputcooker_getc() if not sel...
Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence.
def _IOC(cls, dir, op, structure=None): """ Encode an ioctl id. """ control = cls(dir, op, structure) def do(dev, **args): return control(dev, **args) return do
Encode an ioctl id.
def user_structure(user, site): """ An user structure. """ full_name = user.get_full_name().split() first_name = full_name[0] try: last_name = full_name[1] except IndexError: last_name = '' return {'userid': user.pk, 'email': user.email, 'nickname'...
An user structure.
def set_wv_parameters(filter_name, grism_name): """Set wavelength calibration parameters for rectified images. Parameters ---------- filter_name : str Filter name. grism_name : str Grism name. Returns ------- wv_parameters : dictionary Python dictionary containi...
Set wavelength calibration parameters for rectified images. Parameters ---------- filter_name : str Filter name. grism_name : str Grism name. Returns ------- wv_parameters : dictionary Python dictionary containing relevant wavelength calibration parameters: ...
def is_android_raw(raw): """ Returns a string that describes the type of file, for common Android specific formats """ val = None # We do not check for META-INF/MANIFEST.MF, # as you also want to analyze unsigned APKs... # AndroidManifest.xml should be in every APK. # classes.dex an...
Returns a string that describes the type of file, for common Android specific formats
def strip(value): """ REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS) """ if not value or (ord(value[0]) > 32 and ord(value[-1]) > 32): return value s = 0 e = len(value) while s < e: if ord(value[s]) > 32: break s += 1 else: return "" fo...
REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS)
def octagonal_tiling_graph(M: int, N: int) -> nx.Graph: """Return the octagonal tiling graph (4.8.8, truncated square tiling, truncated quadrille) of MxNx8 nodes The 'positions' node attribute gives node coordinates for the octagonal tiling. (Nodes are located on a square lattice, and edge lengths are ...
Return the octagonal tiling graph (4.8.8, truncated square tiling, truncated quadrille) of MxNx8 nodes The 'positions' node attribute gives node coordinates for the octagonal tiling. (Nodes are located on a square lattice, and edge lengths are uneven)
def getAsGdalRaster(self, rasterFieldName, tableName, rasterIdFieldName, rasterId, gdalFormat, newSRID=None, **kwargs): """ Returns a string/buffer representation of the raster in the specified format. Wrapper for ST_AsGDALRaster function in the database. """ # Check gdalFormat ...
Returns a string/buffer representation of the raster in the specified format. Wrapper for ST_AsGDALRaster function in the database.
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL.
def update_main_table(self): """Write generator settings to database. """ data = (json.dumps(self.settings),) self.cursor.execute(''' CREATE TABLE IF NOT EXISTS main ( settings TEXT NOT NULL DEFAULT "{}" ) ''') self.cursor.execute('...
Write generator settings to database.
def run(self): """The main loop of the frontend. Here incoming messages from the service are processed and forwarded to the corresponding callback methods.""" self.log.debug("Entered main loop") while not self.shutdown: # If no service is running slow down the main loop ...
The main loop of the frontend. Here incoming messages from the service are processed and forwarded to the corresponding callback methods.
def signature_parser(func): """ Creates an argparse.ArgumentParser from the function's signature. Arguments with no default are compulsary positional arguments, Arguments with defaults are optional --flags. If the default is True or False, the action of the flag will toggle...
Creates an argparse.ArgumentParser from the function's signature. Arguments with no default are compulsary positional arguments, Arguments with defaults are optional --flags. If the default is True or False, the action of the flag will toggle the argument and the flag takes no paramete...
def encode16Int(value): ''' Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray ''' value = int(value) encoded = bytearray(2) encoded[0] = value >> 8 encoded[1] = value & 0xFF return encoded
Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray
def transaction_read(self, items): """ Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items` :raises bloop.exceptions.TransactionCanceled: if the transaction was canceled. :r...
Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`. :param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items` :raises bloop.exceptions.TransactionCanceled: if the transaction was canceled. :return: Dict with "Records" list
def _resolve_serializer(self, serializer): """ Resolve the given serializer. :param serializer: The serializer to resolve :type serializer: str or Serializer :rtype: Serializer """ if isinstance(serializer, Serializer): return serializer if ...
Resolve the given serializer. :param serializer: The serializer to resolve :type serializer: str or Serializer :rtype: Serializer
def all_fields(self): """A list with all the fields contained in this object.""" return [field for container in FieldsContainer.class_container.values() for field in getattr(self, container)]
A list with all the fields contained in this object.
def python_portable_string(string, encoding='utf-8'): """Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode) """ if isinstance(string, six.string_types): ...
Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode)
def good_sequences_to_track(flow, motion_threshold=1.0): """Get list of good frames to do tracking in. Looking at the optical flow, this function chooses a span of frames that fulfill certain criteria. These include * not being too short or too long * not too low or too high mean flow m...
Get list of good frames to do tracking in. Looking at the optical flow, this function chooses a span of frames that fulfill certain criteria. These include * not being too short or too long * not too low or too high mean flow magnitude * a low max value (avoids motion blur) Curr...
def _get_struct_gradient(self, shape_number): """Get the values for the GRADIENT record.""" obj = _make_object("Gradient") bc = BitConsumer(self._src) obj.SpreadMode = bc.u_get(2) obj.InterpolationMode = bc.u_get(2) obj.NumGradients = bc.u_get(4) obj.GradientRecor...
Get the values for the GRADIENT record.
def export(self, nidm_version, export_dir, prepend_path): """ Copy file over of export_dir and create corresponding triples """ if self.path is not None: if export_dir is not None: # Copy file only if export_dir is not None new_file = os.path.j...
Copy file over of export_dir and create corresponding triples
def save(self, *args, **kwargs): """ Store summary if none was given and created formatted version of body text. """ if not self.summary: self.summary = truncatewords(self.body, 50) self.body_formatted = sanetize_text(self.body) super(Article, ...
Store summary if none was given and created formatted version of body text.
def sum(self, phi1, inplace=True): """ DiscreteFactor sum with `phi1`. Parameters ---------- phi1: `DiscreteFactor` instance. DiscreteFactor to be added. inplace: boolean If inplace=True it will modify the factor itself, else would return ...
DiscreteFactor sum with `phi1`. Parameters ---------- phi1: `DiscreteFactor` instance. DiscreteFactor to be added. inplace: boolean If inplace=True it will modify the factor itself, else would return a new factor. Returns ------- ...
def read_json(path): """Read local or remote.""" if path.startswith(("http://", "https://")): try: return json.loads(urlopen(path).read().decode()) except HTTPError: raise FileNotFoundError("%s not found", path) elif path.startswith("s3://"): bucket = get_boto...
Read local or remote.
def unencrypt_file(inputfile, filename, passphrase=None): """ Unencrypt input file using GPG and remove .gpg extension to its name. :param inputfile: File to encrypt :type inputfile: ``file`` like object :param filename: File's name :type filename: ``str`` :param passphrase: Passphrase of...
Unencrypt input file using GPG and remove .gpg extension to its name. :param inputfile: File to encrypt :type inputfile: ``file`` like object :param filename: File's name :type filename: ``str`` :param passphrase: Passphrase of GPG key, if equivalent to False, it will be as...
def decoratornames(self): """Get the qualified names of each of the decorators on this function. :returns: The names of the decorators. :rtype: set(str) """ result = set() decoratornodes = [] if self.decorators is not None: decoratornodes += self.deco...
Get the qualified names of each of the decorators on this function. :returns: The names of the decorators. :rtype: set(str)
def refreshTitles(self): """ Refreshes the titles for each view within this tab panel. """ for index in range(self.count()): widget = self.widget(index) self.setTabText(index, widget.windowTitle())
Refreshes the titles for each view within this tab panel.
def bed(args): """ %prog bed xmlfile Print summary of optical map alignment in BED format. """ from jcvi.formats.bed import sort p = OptionParser(bed.__doc__) p.add_option("--blockonly", default=False, action="store_true", help="Only print out large blocks, not fragments [...
%prog bed xmlfile Print summary of optical map alignment in BED format.
def dipole(src, rec, depth, res, freqtime, aniso=None, eperm=None, mperm=None, verb=2): r"""Return the electromagnetic field due to a dipole source. This is a modified version of ``empymod.model.dipole()``. It returns the separated contributions of TM--, TM-+, TM+-, TM++, TMdirect, TE--, TE-+, ...
r"""Return the electromagnetic field due to a dipole source. This is a modified version of ``empymod.model.dipole()``. It returns the separated contributions of TM--, TM-+, TM+-, TM++, TMdirect, TE--, TE-+, TE+-, TE++, and TEdirect. Parameters ---------- src, rec : list of floats or arrays ...
def update_scheduled_time(self, when): """ Updates a scheduled task's date to the given date. If the task is not scheduled, a TaskNotFound exception is raised. """ tiger = self.tiger ts = get_timestamp(when) assert ts pipeline = tiger.connection.pipeline...
Updates a scheduled task's date to the given date. If the task is not scheduled, a TaskNotFound exception is raised.
def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' ...
Function manipulates with entries and buttons.
def _to_cwlfile_with_indexes(val, get_retriever): """Convert reads with ready to go indexes into the right CWL object. Identifies the top level directory and creates a tarball, avoiding trying to handle complex secondary setups which are not cross platform. Skips doing this for reference files and sta...
Convert reads with ready to go indexes into the right CWL object. Identifies the top level directory and creates a tarball, avoiding trying to handle complex secondary setups which are not cross platform. Skips doing this for reference files and standard setups like bwa, which take up too much time an...
def get_or_create(session: Session, model: DeclarativeMeta, defaults: Dict[str, Any] = None, **kwargs: Any) -> Tuple[Any, bool]: """ Fetches an ORM object from the database, or creates one if none existed. Args: session: an SQLAlchemy :class:`Se...
Fetches an ORM object from the database, or creates one if none existed. Args: session: an SQLAlchemy :class:`Session` model: an SQLAlchemy ORM class defaults: default initialization arguments (in addition to relevant filter criteria) if we have to create a new instance ...
def update_lang(self, lang: Optional[Text], data: List[Tuple[Text, Text]], flags: Flags): """ Update translations for one specific lang """ sd = SortingDict() for item in (self.parse_item(x[0], x[1], flags) for x in da...
Update translations for one specific lang
def match_url_regex(rules, url, callback): """Given rules and a callback, find the rule that matches the url. Rules look like:: ( { 'schemes': ['https', 'ssh'], 'netlocs': ['hg.mozilla.org'], 'path_regexes': [ "^(?P<path>/...
Given rules and a callback, find the rule that matches the url. Rules look like:: ( { 'schemes': ['https', 'ssh'], 'netlocs': ['hg.mozilla.org'], 'path_regexes': [ "^(?P<path>/mozilla-(central|unified))(/|$)", ...
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def detach(): for listener in self.__interval_mutated_listeners: listener.close() self.__interval_mutated_listeners = list() ...
Override from PersistentObject.