code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def to_string(x): """ Utf8 conversion :param x: :return: """ if isinstance(x, bytes): return x.decode('utf-8') if isinstance(x, basestring): return x
Utf8 conversion :param x: :return:
def cache_from_source(path, debug_override=None): """Given the path to a .py file, return the path to its .pyc/.pyo file. The .py file does not need to exist; this simply returns the path to the .pyc/.pyo file calculated as if the .py file were imported. The extension will be .pyc unless sys.flags.opt...
Given the path to a .py file, return the path to its .pyc/.pyo file. The .py file does not need to exist; this simply returns the path to the .pyc/.pyo file calculated as if the .py file were imported. The extension will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo. If debug_ov...
def Parse(self,url,song_name,flag): ''' It will the resource URL if song is found, Otherwise it will return the list of songs that can be downloaded ''' file_download=FileDownload() html=file_download.get_html_response(url) if flag == False: soup=BeautifulSoup(html) a_list=soup.findAll('a','touch') ...
It will the resource URL if song is found, Otherwise it will return the list of songs that can be downloaded
def get_file_link(self, file_key): '''Gets link to file Args: file_key key for the file return (status code, ?) ''' #does not work self._raise_unimplemented_error() uri = '/'.join([self.api_uri, self.files_suffix, file_key, self.file_link_suffix, ]) return self._req('get...
Gets link to file Args: file_key key for the file return (status code, ?)
def check_exc_info(self, node): """ Reports a violation if exc_info keyword is used with logging.error or logging.exception. """ if self.current_logging_level not in ('error', 'exception'): return for kw in node.keywords: if kw.arg == 'exc_info': ...
Reports a violation if exc_info keyword is used with logging.error or logging.exception.
def rm_parameter(self, name): """ Removes a parameter to the existing Datamat. Fails if parameter doesn't exist. """ if name not in self._parameters: raise ValueError("no '%s' parameter found" % (name)) del self._parameters[name] del self.__dict__[na...
Removes a parameter to the existing Datamat. Fails if parameter doesn't exist.
def scale_subplots(subplots=None, xlim='auto', ylim='auto'): """Set the x and y axis limits for a collection of subplots. Parameters ----------- subplots : ndarray or list of matplotlib.axes.Axes xlim : None | 'auto' | (xmin, xmax) 'auto' : sets the limits according to the most ext...
Set the x and y axis limits for a collection of subplots. Parameters ----------- subplots : ndarray or list of matplotlib.axes.Axes xlim : None | 'auto' | (xmin, xmax) 'auto' : sets the limits according to the most extreme values of data encountered. ylim : None | 'auto' | (ymin, y...
def build_modules(is_training, vocab_size): """Construct the modules used in the graph.""" # Construct the custom getter which implements Bayes by Backprop. if is_training: estimator_mode = tf.constant(bbb.EstimatorModes.sample) else: estimator_mode = tf.constant(bbb.EstimatorModes.mean) lstm_bbb_cus...
Construct the modules used in the graph.
def visitArrayExpr(self, ctx: jsgParser.ArrayExprContext): """ arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; """ from pyjsg.parser_impl.jsg_ebnf_parser import JSGEbnf from pyjsg.parser_impl.jsg_valuetype_parser import JSGValueType self._types = [JSGValueType(self....
arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET;
def send_s3_xsd(self, url_xsd): # pragma: no cover """This method will not be re-run always, only locally and when xsd are regenerated, read the test_008_force_s3_creation on test folder """ if self.check_s3(self.domain, urlparse(url_xsd).path[1:]): return url_xsd ...
This method will not be re-run always, only locally and when xsd are regenerated, read the test_008_force_s3_creation on test folder
def _add_references(self, rec): """ Adds the reference to the record """ for ref in self.document.getElementsByTagName('ref'): for ref_type, doi, authors, collaboration, journal, volume, page, year,\ label, arxiv, publisher, institution, unstructured_text,\ ...
Adds the reference to the record
def log_loss(oracle, test_seq, ab=[], m_order=None, verbose=False): """ Evaluate the average log-loss of a sequence given an oracle """ if not ab: ab = oracle.get_alphabet() if verbose: print(' ') logP = 0.0 context = [] increment = np.floor((len(test_seq) - 1) / 100) bar_c...
Evaluate the average log-loss of a sequence given an oracle
def _sort_resources_per_hosting_device(resources): """This function will sort the resources on hosting device. The sorting on hosting device is done by looking up the `hosting_device` attribute of the resource, and its `id`. :param resources: a dict with key of resource name :r...
This function will sort the resources on hosting device. The sorting on hosting device is done by looking up the `hosting_device` attribute of the resource, and its `id`. :param resources: a dict with key of resource name :return dict sorted on the hosting device of input resource. For...
def stop(self): """Return the last day of the period as an Instant instance. >>> period('year', 2014).stop Instant((2014, 12, 31)) >>> period('month', 2014).stop Instant((2014, 12, 31)) >>> period('day', 2014).stop Instant((2014, 12, 31)) >>> period('yea...
Return the last day of the period as an Instant instance. >>> period('year', 2014).stop Instant((2014, 12, 31)) >>> period('month', 2014).stop Instant((2014, 12, 31)) >>> period('day', 2014).stop Instant((2014, 12, 31)) >>> period('year', '2012-2-29').stop ...
def brightness(im): ''' Return the brightness of an image Args: im(numpy): image Returns: float, average brightness of an image ''' im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(im_hsv) height, weight = v.shape[:2] total_bright = 0 for i in v:...
Return the brightness of an image Args: im(numpy): image Returns: float, average brightness of an image
def complete_extra(self, args): "Completions for the 'extra' command." # treat the last arg as a path and complete it if len(args) == 0: return self._listdir('./') return self._complete_path(args[-1])
Completions for the 'extra' command.
def setEditorData( self, editor, value ): """ Sets the value for the given editor to the inputed value. :param editor | <QWidget> value | <variant> """ # set the data for a multitagedit if ( isinstance(editor, XMultiTag...
Sets the value for the given editor to the inputed value. :param editor | <QWidget> value | <variant>
def strfdelta(tdelta: Union[datetime.timedelta, int, float, str], fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'): """ Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datet...
Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datetime.datetime`` objects. The ``fmt`` argument allows custom formatting to be specified. Fields can include ``seconds``, ``minutes``, ``hours``, ``days``, and ``w...
def components(self): """ Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame """ from pandas import DataFrame columns = ['days', 'hours', 'm...
Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame
def _structure_frozenset(self, obj, cl): """Convert an iterable into a potentially generic frozenset.""" if is_bare(cl) or cl.__args__[0] is Any: return frozenset(obj) else: elem_type = cl.__args__[0] dispatch = self._structure_func.dispatch return...
Convert an iterable into a potentially generic frozenset.
def _handle_msg(self, msg): """When a BGP message is received, send it to peer. Open messages are validated here. Peer handler is called to handle each message except for *Open* and *Notification* message. On receiving *Notification* message we close connection with peer. """ ...
When a BGP message is received, send it to peer. Open messages are validated here. Peer handler is called to handle each message except for *Open* and *Notification* message. On receiving *Notification* message we close connection with peer.
def add_fs(self, name, fs, write=False, priority=0): # type: (Text, FS, bool, int) -> None """Add a filesystem to the MultiFS. Arguments: name (str): A unique name to refer to the filesystem being added. fs (FS or str): The filesystem (instance or URL) to...
Add a filesystem to the MultiFS. Arguments: name (str): A unique name to refer to the filesystem being added. fs (FS or str): The filesystem (instance or URL) to add. write (bool): If this value is True, then the ``fs`` will be used as the wri...
def remove_ip(enode, portlbl, addr, shell=None): """ Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.b...
Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure....
def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None): """Send a message. Records the message in the log. """ if not isinstance(msg, str): raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__) if filters is...
Send a message. Records the message in the log.
def policy_present(name, rules): ''' Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar ...
Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar - rules: | path "secret/top-...
def plot_di(fignum, DIblock): global globals """ plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs """ X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) #...
plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs
def get_current_span(): """ Access current request context and extract current Span from it. :return: Return current span associated with the current request context. If no request context is present in thread local, or the context has no span, return None. """ # Check agains...
Access current request context and extract current Span from it. :return: Return current span associated with the current request context. If no request context is present in thread local, or the context has no span, return None.
def emotes(self, emotes): """Set the emotes :param emotes: the key of the emotes tag :type emotes: :class:`str` :returns: None :rtype: None :raises: None """ if emotes is None: self._emotes = [] return es = [] for e...
Set the emotes :param emotes: the key of the emotes tag :type emotes: :class:`str` :returns: None :rtype: None :raises: None
def name(self) -> str: """OpenSSL uses a different naming convention than the corresponding RFCs. """ return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name)
OpenSSL uses a different naming convention than the corresponding RFCs.
def show_user(self, user): """Get the info for a specific user. Returns a delegate that will receive the user in a callback.""" url = '/users/show/%s.xml' % (user) d = defer.Deferred() self.__downloadPage(url, txml.Users(lambda u: d.callback(u))) \ .addErrback(lamb...
Get the info for a specific user. Returns a delegate that will receive the user in a callback.
def get_i_name(self, num, is_oai=None): """ This method is used mainly internally, but it can be handy if you work with with raw MARC XML object and not using getters. Args: num (int): Which indicator you need (1/2). is_oai (bool/None): If None, :attr:`.oai_marc`...
This method is used mainly internally, but it can be handy if you work with with raw MARC XML object and not using getters. Args: num (int): Which indicator you need (1/2). is_oai (bool/None): If None, :attr:`.oai_marc` is used. Returns: s...
def scan(repos, options): """Given a repository list [(path, vcsname), ...], scan each of them.""" ignore_set = set() repos = repos[::-1] # Create a queue we can push and pop from while repos: directory, dotdir = repos.pop() ignore_this = any(pat in directory for pat in options.ignore_p...
Given a repository list [(path, vcsname), ...], scan each of them.
def train_with_graph(p_graph, qp_pairs, dev_qp_pairs): ''' Train a network from a specific graph. ''' global sess with tf.Graph().as_default(): train_model = GAG(cfg, embed, p_graph) train_model.build_net(is_training=True) tf.get_variable_scope().reuse_variables() dev...
Train a network from a specific graph.
def construct_routes(self): """ Gets modules routes.py and converts to module imports """ modules = self.evernode_app.get_modules() for module_name in modules: with self.app.app_context(): module = importlib.import_module( 'modules.%s.routes'...
Gets modules routes.py and converts to module imports
def object_clean(self): """ Remove large attributes from the metadata objects """ for sample in self.metadata: try: delattr(sample[self.analysistype], 'aaidentity') delattr(sample[self.analysistype], 'aaalign') delattr(sample[se...
Remove large attributes from the metadata objects
def get_key(dotenv_path, key_to_get, verbose=False): """ Gets the value of a given key from the given .env If the .env path given doesn't exist, fails :param dotenv_path: path :param key_to_get: key :param verbose: verbosity flag, raise warning if path does not exist :return: value of varia...
Gets the value of a given key from the given .env If the .env path given doesn't exist, fails :param dotenv_path: path :param key_to_get: key :param verbose: verbosity flag, raise warning if path does not exist :return: value of variable from environment file or None
def create_from_xml(resultFile, resultElem, columns=None, all_columns=False, columns_relevant_for_diff=set()): ''' This function extracts everything necessary for creating a RunSetResult object from the "result" XML tag of a benchmark result file. It returns a Run...
This function extracts everything necessary for creating a RunSetResult object from the "result" XML tag of a benchmark result file. It returns a RunSetResult object, which is not yet fully initialized. To finish initializing the object, call collect_data() before using it for anything e...
def plot2dhist(xdata,ydata,cmap='binary',interpolation='nearest', fig=None,logscale=True,xbins=None,ybins=None, nbins=50,pts_only=False,**kwargs): """Plots a 2d density histogram of provided data :param xdata,ydata: (array-like) Data to plot. :param cmap: (optional) ...
Plots a 2d density histogram of provided data :param xdata,ydata: (array-like) Data to plot. :param cmap: (optional) Colormap to use for density plot. :param interpolation: (optional) Interpolation scheme for display (passed to ``plt.imshow``). :param fig: (optional) ...
def update_dns_server(self, service_name, deployment_name, dns_server_name, address): ''' Updates the ip address of a DNS server. service_name: The name of the service. deployment_name: The name of the deployment. dns_server_name: Specifies th...
Updates the ip address of a DNS server. service_name: The name of the service. deployment_name: The name of the deployment. dns_server_name: Specifies the name of the DNS server. address: Specifies the IP address of the DNS server.
def _get_curvature(nodes, tangent_vec, s): r"""Compute the signed curvature of a curve at :math:`s`. Computed via .. math:: \frac{B'(s) \times B''(s)}{\left\lVert B'(s) \right\rVert_2^3} .. image:: ../images/get_curvature.png :align: center .. testsetup:: get-curvature imp...
r"""Compute the signed curvature of a curve at :math:`s`. Computed via .. math:: \frac{B'(s) \times B''(s)}{\left\lVert B'(s) \right\rVert_2^3} .. image:: ../images/get_curvature.png :align: center .. testsetup:: get-curvature import numpy as np import bezier fro...
def _getTransformation(self): """_getTransformation(self) -> PyObject *""" CheckParent(self) val = _fitz.Page__getTransformation(self) val = Matrix(val) return val
_getTransformation(self) -> PyObject *
def from_mask(cls, dh_mask, lwin, nwin=None, weights=None): """ Construct localization windows that are optimally concentrated within the region specified by a mask. Usage ----- x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights]) Returns ------- ...
Construct localization windows that are optimally concentrated within the region specified by a mask. Usage ----- x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights]) Returns ------- x : SHWindow class instance Parameters ---------- dh...
def server_sends_binary(self, message, name=None, connection=None, label=None): """Send raw binary `message`. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | Server sends binary | Hello! | | Server sends bina...
Send raw binary `message`. If server `name` is not given, uses the latest server. Optional message `label` is shown on logs. Examples: | Server sends binary | Hello! | | Server sends binary | ${some binary} | Server1 | label=DebugMessage | | Server sends binary | ${some...
async def sinter(self, keys, *args): "Return the intersection of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SINTER', *args)
Return the intersection of sets specified by ``keys``
def leaders_in(self, leaderboard_name, current_page, **options): ''' Retrieve a page of leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param current_page [int] Page to retrieve from the named leaderboard. @param options [Hash] Opti...
Retrieve a page of leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param current_page [int] Page to retrieve from the named leaderboard. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a...
def load_json(file): """Load JSON file at app start""" here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, file)) as jfile: data = json.load(jfile) return data
Load JSON file at app start
def _clean_record(self, record): """Remove all fields with `None` values""" for k, v in dict(record).items(): if isinstance(v, dict): v = self._clean_record(v) if v is None: record.pop(k) return record
Remove all fields with `None` values
def getAllAnnotationSets(self): """ Returns all variant annotation sets on the server. """ for variantSet in self.getAllVariantSets(): iterator = self._client.search_variant_annotation_sets( variant_set_id=variantSet.id) for variantAnnotationSet in...
Returns all variant annotation sets on the server.
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL): """ Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants """ averaging_con...
Set the base config for sensor :param averaging: Sets the numer of samples that are internally averaged :param datarate: Datarate in hertz :param mode: one of the MODE_* constants
def show_top_losses(self, k:int, max_len:int=70)->None: """ Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of actual class. `max_len` is the maximum number of tokens displayed. """ from IPython.display impor...
Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of actual class. `max_len` is the maximum number of tokens displayed.
def _edges_replaced(self, object, name, old, new): """ Handles a list of edges being set. """ self._delete_edges(old) self._add_edges(new)
Handles a list of edges being set.
def add_data(self, id, key, value): """Add new data item. :param str id: Entry id within ``SDfile``. :param str key: Data item key. :param str value: Data item value. :return: None. :rtype: :py:obj:`None`. """ self[str(id)]['data'].setdefault(key, []) ...
Add new data item. :param str id: Entry id within ``SDfile``. :param str key: Data item key. :param str value: Data item value. :return: None. :rtype: :py:obj:`None`.
def most_even_chunk(string, group): """Divide a string into a list of strings as even as possible.""" counts = [0] + most_even(len(string), group) indices = accumulate(counts) slices = window(indices, 2) return [string[slice(*one)] for one in slices]
Divide a string into a list of strings as even as possible.
def in_domain(self, points): """ Returns ``True`` if all of the given points are in the domain, ``False`` otherwise. :param np.ndarray points: An `np.ndarray` of type `self.dtype`. :rtype: `bool` """ return all([ domain.in_domain(array) f...
Returns ``True`` if all of the given points are in the domain, ``False`` otherwise. :param np.ndarray points: An `np.ndarray` of type `self.dtype`. :rtype: `bool`
def vertical_gradient(self, x0, y0, x1, y1, start, end): """Draw a vertical gradient""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) grad = gradient_list(start, end, y1 - y0) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): self.point(x, y, grad[y ...
Draw a vertical gradient
def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answer
Shuffle the step
def paste_buffer(pymux, variables): """ Paste clipboard content into buffer. """ pane = pymux.arrangement.get_active_pane() pane.process.write_input(get_app().clipboard.get_data().text, paste=True)
Paste clipboard content into buffer.
def _default_return_columns(self): """ Return a list of the model elements that does not include lookup functions or other functions that take parameters. """ return_columns = [] parsed_expr = [] for key, value in self.components._namespace.items(): i...
Return a list of the model elements that does not include lookup functions or other functions that take parameters.
def update_record(self, name, new_data, condition, update_only=False, debug=False): """ Find the first row in self.df with index == name and condition == True. Update that record with new_data, then delete any additional records where index == name and condi...
Find the first row in self.df with index == name and condition == True. Update that record with new_data, then delete any additional records where index == name and condition == True. Change is inplace
def pipe(): """create an inter-process communication pipe :returns: a pair of :class:`File` objects ``(read, write)`` for the two ends of the pipe """ r, w = os.pipe() return File.fromfd(r, 'rb'), File.fromfd(w, 'wb')
create an inter-process communication pipe :returns: a pair of :class:`File` objects ``(read, write)`` for the two ends of the pipe
def start_session(self): """ Starts a Salesforce session and determines which SF instance to use for future requests. """ if self.has_active_session(): raise Exception("Session already in progress.") response = requests.post(self._get_login_url(), ...
Starts a Salesforce session and determines which SF instance to use for future requests.
def get_sql_type(self, instance, counter_name): ''' Return the type of the performance counter so that we can report it to Datadog correctly If the sql_type is one that needs a base (PERF_RAW_LARGE_FRACTION and PERF_AVERAGE_BULK), the name of the base counter will also be returne...
Return the type of the performance counter so that we can report it to Datadog correctly If the sql_type is one that needs a base (PERF_RAW_LARGE_FRACTION and PERF_AVERAGE_BULK), the name of the base counter will also be returned
def route(**kwargs): """ Route a request to different views based on http verb. Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE', where the first four map to a view to route to for that type of request method/verb, and 'ELSE' maps to a view to pass the request to if the given request m...
Route a request to different views based on http verb. Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE', where the first four map to a view to route to for that type of request method/verb, and 'ELSE' maps to a view to pass the request to if the given request method/verb was not specified.
def sample_initial(self, nlive=500, update_interval=None, first_update=None, maxiter=None, maxcall=None, logl_max=np.inf, dlogz=0.01, live_points=None): """ Generate a series of initial samples from a nested sampling run using a fixed number of live ...
Generate a series of initial samples from a nested sampling run using a fixed number of live points using an internal sampler from :mod:`~dynesty.nestedsamplers`. Instantiates a generator that will be called by the user. Parameters ---------- nlive : int, optional ...
def fromid(self, item_id): """ Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int. """ if not item_id: raise Exception('Need an i...
Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int.
def main(arguments=None): """ *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="DEBUG", option...
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
def intervalAdd(self, a, b, val): """Variant, adds val to t[a], to t[a + 1] ... and to t[b] :param int a b: with 1 <= a <= b """ self.add(a, +val) self.add(b + 1, -val)
Variant, adds val to t[a], to t[a + 1] ... and to t[b] :param int a b: with 1 <= a <= b
def check_can_approve(self, request, application, roles): """ Check the person's authorization. """ try: authorised_persons = self.get_authorised_persons(application) authorised_persons.get(pk=request.user.pk) return True except Person.DoesNotExist: ...
Check the person's authorization.
def get_bundle(self, bundle_id=None): # type: (Union[Bundle, int]) -> Bundle """ Retrieves the :class:`~pelix.framework.Bundle` object for the bundle matching the given ID (int). If no ID is given (None), the bundle associated to this context is returned. :param bundle_i...
Retrieves the :class:`~pelix.framework.Bundle` object for the bundle matching the given ID (int). If no ID is given (None), the bundle associated to this context is returned. :param bundle_id: A bundle ID (optional) :return: The requested :class:`~pelix.framework.Bundle` object ...
def disable(self, name=None): """Disable one or all actions.""" if name is None: for name in self._actions_dict: self.disable(name) return self._actions_dict[name].qaction.setEnabled(False)
Disable one or all actions.
def _get_results(self, page): """Find every div tag containing torrent details on given page, then parse the results into a list of Torrents and return them""" soup = _get_soup(page) details = soup.find_all("tr", class_="odd") even = soup.find_all("tr", class_="even") # Join the results for i in range(l...
Find every div tag containing torrent details on given page, then parse the results into a list of Torrents and return them
def rowsBeforeRow(self, rowObject, count): """ Wrapper around L{rowsBeforeItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to...
Wrapper around L{rowsBeforeItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to uniquely identify a row. @param count: an int...
def request(schema): """ Decorate a function with a request schema. """ def wrapper(func): setattr(func, REQUEST, schema) return func return wrapper
Decorate a function with a request schema.
def _discarded_reads2_out_file_name(self): """Checks if file name is set for discarded reads2 output. Returns absolute path.""" if self.Parameters['-4'].isOn(): discarded_reads2 = self._absolute(str(self.Parameters['-4'].Value)) else: raise ValueError( ...
Checks if file name is set for discarded reads2 output. Returns absolute path.
def paste(location): """paste a file or directory that has been previously copied""" copyData = settings.getDataFile() if not location: location = "." try: data = pickle.load(open(copyData, "rb")) speech.speak("Pasting " + data["copyLocation"] + " to current directory.") except: speech.fail("It doesn't loo...
paste a file or directory that has been previously copied
def match(self, other_version): """Returns True if other_version matches. Args: other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a number or a wildcard. """ major, minor, patch = _str_to_version(other_version, allow_wildcard=True) return (major in [self.major, "*"] ...
Returns True if other_version matches. Args: other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a number or a wildcard.
def _compute_video_hash(videofile): """ compute videofile's hash reference: https://docs.google.com/document/d/1w5MCBO61rKQ6hI5m9laJLWse__yTYdRugpVyz4RzrmM/preview """ seek_positions = [None] * 4 hash_result = [] with open(videofile, 'rb') as fp: total_size = ...
compute videofile's hash reference: https://docs.google.com/document/d/1w5MCBO61rKQ6hI5m9laJLWse__yTYdRugpVyz4RzrmM/preview
def list_theme(): """List all available Engineer themes.""" from engineer.themes import ThemeManager themes = ThemeManager.themes() col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.root_path) + 2) for t in themes.itervalues()])) themes = ThemeManager.themes_by_finder() for finder in sorted(th...
List all available Engineer themes.
def random_density(qubits: Union[int, Qubits]) -> Density: """ Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) ...
Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) https://arxiv.org/abs/quant-ph/0012101
def handle_device_json(self, data): """Manage the device json list.""" self._device_json.insert(0, data) self._device_json.pop()
Manage the device json list.
def extract_token_and_qualifier(text, line=0, column=0): ''' Extracts the token a qualifier from the text given the line/colum (see test_extract_token_and_qualifier for examples). :param unicode text: :param int line: 0-based :param int column: 0-based ''' # Note: not using the tokenize...
Extracts the token a qualifier from the text given the line/colum (see test_extract_token_and_qualifier for examples). :param unicode text: :param int line: 0-based :param int column: 0-based
def plot(self): """ Plot posterior from simple nonstochetric regression. """ figure() plot_envelope(self.M, self.C, self.xplot) for i in range(3): f = Realization(self.M, self.C) plot(self.xplot,f(self.xplot)) plot(self.abundance, self.fry...
Plot posterior from simple nonstochetric regression.
def prepend_to_file(path, data, bufsize=1<<15): """TODO: * Add a random string to the backup file. * Restore permissions after copy. """ # Backup the file # backupname = path + os.extsep + 'bak' # Remove previous backup if it exists # try: os.unlink(backupname) except OSError: pass ...
TODO: * Add a random string to the backup file. * Restore permissions after copy.
def ai(board, who='x'): """ Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| > """ return sorted(board.possible(), key=lambda b: value(b, who))[-1]
Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| >
def read_namespaced_network_policy(self, name, namespace, **kwargs): """ read the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_network_policy(name...
read the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_network_policy(name, namespace, async_req=True) >>> result = thread.get() :param async_req ...
def get_preview_url(self, data_type='L1C'): """Returns url location of full resolution L1C preview :return: """ if self.data_source is DataSource.SENTINEL2_L1C or self.safe_type is EsaSafeType.OLD_TYPE: return self.get_url(AwsConstants.PREVIEW_JP2) return self.get_qi_...
Returns url location of full resolution L1C preview :return:
def load_vcf( path, genome=None, reference_vcf_key="reference", only_passing=True, allow_extended_nucleotides=False, include_info=True, chunk_size=10 ** 5, max_variants=None, sort_key=variant_ascending_position_sort_key, distinct=True): ...
Load reference name and Variant objects from the given VCF filename. Currently only local files are supported by this function (no http). If you call this on an HTTP URL, it will fall back to `load_vcf`. Parameters ---------- path : str Path to VCF (*.vcf) or compressed VCF (*.vcf.gz). ...
def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock: """ Mine the current block. Proxies to self.pack_block method. """ packed_block = self.pack_block(self.block, *args, **kwargs) final_block = self.finalize_block(packed_block) # Perform validation self...
Mine the current block. Proxies to self.pack_block method.
def fetch(self, resource_class): """Construct a :class:`.Request` for the given resource type. Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly. Examples:: client.fetch(Asset) client.fetch(Entry) client.fet...
Construct a :class:`.Request` for the given resource type. Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly. Examples:: client.fetch(Asset) client.fetch(Entry) client.fetch(ContentType) client.fetch(Cus...
def real_time_scheduling(self, availability, oauth, event, target_calendars=()): """Generates an real time scheduling link to start the OAuth process with an event to be automatically upserted :param dict availability: - A dict describing the availability details for the event: :pa...
Generates an real time scheduling link to start the OAuth process with an event to be automatically upserted :param dict availability: - A dict describing the availability details for the event: :participants - A dict stating who is required for the availability ...
def end_span(self, *args, **kwargs): """End a span. Update the span_id in SpanContext to the current span's parent span id; Update the current span. """ cur_span = self.current_span() if cur_span is None and self._spans_list: cur_span = self._spans_list[-1] i...
End a span. Update the span_id in SpanContext to the current span's parent span id; Update the current span.
def handle(self, *args, **kwargs): """ Command handler for the "metrics" command. """ frequency = kwargs['frequency'] frequencies = settings.STATISTIC_FREQUENCY_ALL if frequency == 'a' else (frequency.split(',') if ',' in frequency else [frequency]) if kwargs['list']: ...
Command handler for the "metrics" command.
def isclose(a, b, rtol=1e-5, atol=1e-8): """This is essentially np.isclose, but slightly faster.""" return abs(a - b) < (atol + rtol * abs(b))
This is essentially np.isclose, but slightly faster.
def GetArchiveInfo(self): '''Obtains information on CHM archive. This function checks the /#SYSTEM file inside the CHM archive to obtain the index, home page, topics, encoding and title. It is called from LoadCHM. ''' self.searchable = extra.is_searchable(self.file) ...
Obtains information on CHM archive. This function checks the /#SYSTEM file inside the CHM archive to obtain the index, home page, topics, encoding and title. It is called from LoadCHM.
def get_all_fields(obj): """Returns a list of all field names on the instance.""" fields = [] for f in obj._meta.fields: fname = f.name get_choice = "get_" + fname + "_display" if hasattr(obj, get_choice): value = getattr(obj, get_choice)() else: try:...
Returns a list of all field names on the instance.
def copy(self): """ Copy the currently selected text to the clipboard, removing prompts. """ if self._page_control is not None and self._page_control.hasFocus(): self._page_control.copy() elif self._control.hasFocus(): text = self._control.textCursor().selection()...
Copy the currently selected text to the clipboard, removing prompts.
def _to_DOM(self): """ Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object """ root_node = ET.Element("no2index") reference_time_node = ET.SubElement(root_node, "reference_time") reference_t...
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
def WaitProcessing(obj, eng, callbacks, exc_info): """Take actions when WaitProcessing is raised. ..note:: We're essentially doing HaltProcessing, plus `obj.set_action` and object status `WAITING` instead of `HALTED`. This is not present in TransitionActions so that...
Take actions when WaitProcessing is raised. ..note:: We're essentially doing HaltProcessing, plus `obj.set_action` and object status `WAITING` instead of `HALTED`. This is not present in TransitionActions so that's why it is not calling super in this case.
def check_spot_requests(self, requests, tags=None): """Check status of one or more EC2 spot instance requests. :param requests: List of EC2 spot instance request IDs. :type requests: list :param tags: :type tags: dict :return: List of boto.ec2.instance.Instance's created...
Check status of one or more EC2 spot instance requests. :param requests: List of EC2 spot instance request IDs. :type requests: list :param tags: :type tags: dict :return: List of boto.ec2.instance.Instance's created, order corresponding to requests param (None if request ...
def mkdir(name, path): '''Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist. ''' with Session() as session: try: session.VFolder...
Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist.