code stringlengths 1 18.2k |
|---|
- startTime).total_seconds() self._metadata[self.SETUP_TIME] = (doneSetupTime - startTime).total_seconds() self._metadata[self.EXPERIMENT_TIME] = (doneExperimentTime - doneSetupTime).total_seconds() self._metadata[self.TEARDOWN_TIME] = (doneTeardownTime - doneExperimentTime).total_seconds() # set the success flag self.... |
self.report(params, self._metadata, res) |
def success( self ): """Test whether the experiment has been run successfully. This will be False if the experiment hasn't been run, or if it's been run and failed (in which case the exception will be stored in the metadata). :returns: ``True`` if the experiment has been run successfully""" if self.STATUS in self.metad... |
def results( self ): """Return a complete results dict. Only really makes sense for recently-executed experimental runs. :returns: the results dict""" return self.report(self.parameters(), self.metadata(), self.experimentalResults()) |
def SetProperties(has_props_cls, input_dict, include_immutable=True): """A helper method to set an ``HasProperties`` object's properties from a dictionary""" props = has_props_cls() if not isinstance(input_dict, (dict, collections.OrderedDict)): raise RuntimeError('input_dict invalid: ', input_dict) for k, v in iter(in... |
in has_props_cls._props} return props |
def ReadTif(tifFile): """Reads a tif file to a 2D NumPy array""" img = Image.open(tifFile) img = np.array(img) return img |
def GenerateBand(self, band, meta_only=False, cast=False): """Genreate a Band object given band metadata Args: band (dict): dictionary containing metadata for a given band Return: Band : the loaded Band onject""" # Read the band data and add it to dictionary if not meta_only: fname = band.get('file_name') data = self.R... |
with nans data = data.astype(np.float32) data[data==band.fill_value] = -9999 if band.valid_range is not None: data[data<band.valid_range.min] = -9999 data[data>band.valid_range.max] = -9999 data[data==-9999] = np.nan else: data = np.ma.masked_where(data==band.fill_value, data) if band.valid_range is not None: data = np... |
def Read(self, meta_only=False, allowed=None, cast=False): """Read the ESPA XML metadata file""" if allowed is not None and not isinstance(allowed, (list, tuple)): raise RuntimeError('`allowed` must be a list of str names.') meta = xmltodict.parse( open(self.filename, 'r').read() ).get('espa_metadata') # Handle bands s... |
self.GenerateBand(bands[i], meta_only=meta_only, cast=cast) self.bdict[b.name] = b elif not cast and self.bdict[info.name].data.dtype == np.float32: b = self.GenerateBand(bands[i], meta_only=meta_only, cast=cast) self.bdict[b.name] = b ras.bands = self.bdict if not meta_only: ras.validate() return ras |
def search_records(self, rq={}, limit=100, offset=0, sort=None, fields=None, fields_exclude=FIELDS_EXCLUDE_DEFAULT): """ rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields a list of fields to return, specified using the fieldName parameter from... |
def search_media(self, mq={}, rq={}, limit=100, offset=0, sort=None, fields=None, fields_exclude=FIELDS_EXCLUDE_DEFAULT): """ mq Search Query in iDigBio Query Format, using Media Query Fields rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Media Query Fields fields a ... |
def java_version(): """Call java and return version information. :return unicode: Java version string """ result = subprocess.check_output( [c.JAVA, '-version'], stderr=subprocess.STDOUT ) first_line = result.splitlines()[0] return first_line.decode() |
def epubcheck_help(): """Return epubcheck.jar commandline help text. :return unicode: helptext from epubcheck.jar """ # tc = locale.getdefaultlocale()[1] with open(os.devnull, "w") as devnull: p = subprocess.Popen( [c.JAVA, '-Duser.language=en', '-jar', c.EPUBCHECK, '-h'], stdout=subprocess.PIPE, stderr=devnull, ) resu... |
def generate_sample_json(): """Generate sample json data for testing""" check = EpubCheck(samples.EPUB3_VALID) with open(samples.RESULT_VALID, 'wb') as jsonfile: jsonfile.write(check._stdout) check = EpubCheck(samples.EPUB3_INVALID) with open(samples.RESULT_INVALID, 'wb') as jsonfile: jsonfile.write(check._stdout) |
def iter_files(root, exts=None, recursive=False): """ Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to walk the complete directory ... |
def participate(self, identity, experiment_name, variant): """ Set the variant for a specific user and mark a participation for the experiment. Participation will *only* be marked for visitors who have been verified as humans (to avoid skewing reports with requests from bots and web crawlers). """ self.set_variant(iden... |
def to_weld_vec(weld_type, ndim): """Convert multi-dimensional data to WeldVec types. Parameters ---------- weld_type : WeldType WeldType of data. ndim : int Number of dimensions. Returns ------- WeldVec WeldVec of 1 or more dimensions. """ for i in range(ndim): weld_type = WeldVec(weld_type) return weld_type |
def to_shared_lib(name): """Return library name depending on platform. Parameters ---------- name : str Name of library. Returns ------- str Name of library with extension. """ if sys.platform.startswith('linux'): return name + '.so' elif sys.platform.startswith('darwin'): return name + '.dylib' elif sys.platform.start... |
def check_type(value: typing.Any, hint: typing.Optional[type]) -> bool: """Check given ``value``'s type. :param value: given argument :param hint: expected type of given ``value``. as like :mod:`typing` interprets, :const:`None` is interpreted as :class:`types.NoneType` :type hint: :class:`typing.Optional`[:class:`type... |
def check_return(callable_name: str, r: typing.Any, hints: typing.Mapping[str, type]) -> None: """Check return type, raise :class:`TypeError` if return type is not expected type. :param str callable_name: callable name of :func:`~.typechecked` checked :param r: returned result :param hints: assumed type of given ``r`` ... |
def check_callable(callable_: typing.Callable, hint: type) -> bool: """Check argument type & return type of :class:`typing.Callable`. since it raises check :class:`typing.Callable` using `isinstance`, so compare in diffrent way :param callable_: callable object given as a argument :param hint: assumed type of given ``c... |
def check_tuple(data: typing.Tuple, hint: typing.Union[type, typing.TypingMeta]) -> bool: """Check argument type & return type of :class:`typing.Tuple`. since it raises check :class:`typing.Tuple` using `isinstance`, so compare in diffrent way :param data: tuple given as a argument :param hint: assumed type of given ``... |
def check_union(data: typing.Union, hint: type) -> bool: """Check argument type & return type of :class:`typing.Union`. since it raises check :class:`typing.Union` using `isinstance`, so compare in diffrent way :param data: union given as a argument :param hint: assumed type of given ``data`` """ r = any(check_type(dat... |
def check_arguments(c: typing.Callable, hints: typing.Mapping[str, typing.Optional[type]], *args, **kwargs) -> None: """Check arguments type, raise :class:`TypeError` if argument type is not expected type. :param c: callable object want to check types :param hints: assumed type of given ``c`` result of :func:`typing.ge... |
def typechecked(call_: typing.Callable[..., T]) -> T: """A decorator to make a callable object checks its types .. code-block:: python from typing import Callable @typechecked def foobar(x: str) -> bool: return x == 'hello world' @typechecked def hello_world(foo: str, bar: Callable[[str], bool]) -> bool: return bar(foo... |
def get_cmd_by_path(self, existed_cmd_path): """ :return: { "name": cmd_name, "cmd": Resource instance, "children": {} } """ parent = self.tree for cmd_name in existed_cmd_path: try: parent = parent['children'][cmd_name] except KeyError: raise ValueError( "Given key [%s] in path %s does not exist in tree." % (cmd_name,... |
def _add_node(self, cmd_node, cmd_path): """ :type cmd_path: list or tuple """ parent = self.tree for cmd_key in cmd_path: if cmd_key not in parent['children']: break parent = parent['children'][cmd_key] parent["children"][cmd_node['name']] = cmd_node return cmd_node |
def add_parent_commands(self, cmd_path, help=None): """ Create parent command object in cmd tree then return the last parent command object. :rtype: dict """ existed_cmd_end_index = self.index_in_tree(cmd_path) new_path, existed_path = self._get_paths( cmd_path, existed_cmd_end_index, ) parent_node = self.get_cmd_by_pa... |
def index_in_tree(self, cmd_path): """ Return the start index of which the element is not in cmd tree. :type cmd_path: list or tuple :return: None if cmd_path already indexed in tree. """ current_tree = self.tree for key in cmd_path: if key in current_tree['children']: current_tree = current_tree['children'][key] else:... |
def create_report(outdirname, report_filename, **kwargs): """Creates a LaTeX report. :param report_filename: the name of the file. :param outdirname: the name of the output directory. :type report_filename: str :type outdirname: str """ # Checking the required variables if "steps" in kwargs: assert "descriptions" in kw... |
to a separate file (for access later) steps_filename = None if "steps_filename" in kwargs: steps_filename = kwargs["steps_filename"] else: steps_filename = os.path.join(outdirname, "steps_summary.tex") with open(steps_filename, "w") as o_file: zipped = zip(kwargs["steps"], kwargs["descriptions"], kwargs["long_descripti... |
[i.split("\t")[0] for i in i_file.read().splitlines()] # Adding the bibliography content biblio_entry = latex.bib_entry( name="pyGenClean", authors="Lemieux Perreault LP, Provost S, Legault MA, Barhdadi A, " r"Dub\'e MP", title="pyGenClean: efficient tool for genetic data clean up before " "association testing", journa... |
DNA samples in " "sequencing and array-based genotype data", journal="The American Journal of Human Genetics", year="2012", volume="91", number="5", pages="839--848", ) # Getting the template main_template = latex.jinja2_env.get_template("main_document.tex") # Getting the data today = datetime.today() # Reading the gra... |
def _format_background(background): """Formats the background section :param background: the background content or file. :type background: str or file :returns: the background content. :rtype: str """ # Getting the background if os.path.isfile(background): with open(background, "r") as i_file: background = i_file.read(... |
def _create_summary_table(fn, template, nb_samples, nb_markers): """Creates the final table. :param fn: the name of the file containing the summary. :param template: the Jinja2 template. :param nb_samples: the final number of samples. :param nb_markers: the final number of markers. :type fn: str :type template: Jinja2.... |
starts with '---', then it's a horizontal line if line.startswith("---"): data["data"].append(dict(hline=True)) # Changing to next line line = i_file.readline() continue # If the line starts with ' -', then it's a sub section if line.startswith(" -"): tmp = line[4:].rstrip("\r\n").split("\t") if data["header"].endswith... |
def weld_str_lower(array): """Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """map( {array}, |e: vec[i8]| result( for(e, appender[i8], |c: ... |
def weld_str_upper(array): """Convert values to uppercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """map( {array}, |e: vec[i8]| result( for(e, appender[i8], |c: ... |
def weld_str_capitalize(array): """Capitalize first letter. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """map( {array}, |e: vec[i8]| let lenString = len(e); if(lenSt... |
def weld_str_get(array, i): """Retrieve character at index i. Parameters ---------- array : numpy.ndarray or WeldObject Input data. i : int Index of character to retrieve. If greater than length of string, returns None. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_ob... |
def weld_str_strip(array): """Strip whitespace from start and end of elements. Note it currently only looks for whitespace (Ascii 32), not tabs or EOL. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_... |
def weld_str_slice(array, start=None, stop=None, step=None): """Slice each element. Parameters ---------- array : numpy.ndarray or WeldObject Input data. start : int, optional stop : int, optional step : int, optional Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_obje... |
def weld_str_startswith(array, pat): """Check which elements start with pattern. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To check for. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) pat_id = get_weld_obj_id(weld_obj... |
def weld_str_find(array, sub, start, end): """Return index of sub in elements if found, else -1. Parameters ---------- array : numpy.ndarray or WeldObject Input data. sub : str To check for. start : int Start index for searching. end : int or None Stop index for searching. Returns ------- WeldObject Representation of t... |
start by assuming sub is not found, until proven it is let words_iter_res = iterate({{0L, false}}, |p| let e_i = p.$0; let pat_i = 0L; # start by assuming the substring and sub are the same, until proven otherwise let word_check_res = iterate({{e_i, pat_i, true}}, |q| let found = lookup(string, q.$0) == lookup({sub}, q... |
def weld_str_replace(array, pat, rep): """Replace first occurrence of pat with rep. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To find. rep : str To replace with. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) pat_id =... |
+ 1L, found}}, q.$1 + 1L < lenPat && found == true }} ).$2; {{ {{p.$0 + 1L, word_check_res}}, p.$0 + lenPat < lenString && word_check_res == false }} ); if(words_iter_res.$1 == true, let rep_from = words_iter_res.$0 - 1L; let rep_to = rep_from + lenPat; let res = appender[i8]; let res = for(slice(e, 0L, rep_from), res,... |
def weld_str_split(array, pat, side): """Split on pat and return side. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To find. side : {0, 1} Which side to return, with 0 being left and 1 being right Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = cr... |
found, until proven it is let words_iter_res = iterate({{0L, false}}, |p| let e_i = p.$0; let pat_i = 0L; # start by assuming the substring and sub are the same, until proven otherwise let word_check_res = iterate({{e_i, pat_i, true}}, |q| let found = lookup(e, q.$0) == lookup({pat}, q.$1); {{ {{q.$0 + 1L, q.$1 + 1L, f... |
def _isPromise(obj): """ A utility function to determine if the specified object is a promise using "duck typing". """ return hasattr(obj, "fulfill") and \ _isFunction(getattr(obj, "fulfill")) and \ hasattr(obj, "reject") and \ _isFunction(getattr(obj, "reject")) and \ hasattr(obj, "then") and \ _isFunction(getattr(obj... |
def listPromise(*args): """ A special function that takes a bunch of promises and turns them into a promise for a vector of values. In other words, this turns an list of promises for values into a promise for a list of values. """ ret = Promise() def handleSuccess(v, ret): for arg in args: if not arg.isFulfilled(): ret... |
def dictPromise(m): """ A special function that takes a dictionary of promises and turns them into a promise for a dictionary of values. In other words, this turns an dictionary of promises for values into a promise for a dictionary of values. """ ret = Promise() def handleSuccess(v, ret): for p in m.values(): if not p... |
def fulfill(self, value): """ Fulfill the promise with a given value. """ assert self._state==self.PENDING self._state=self.FULFILLED; self.value = value for callback in self._callbacks: try: callback(value) except Exception: # Ignore errors in callbacks pass # We will never call these callbacks again, so allow # them ... |
def reject(self, reason): """ Reject this promise for a given reason. """ assert self._state==self.PENDING self._state=self.REJECTED; self.reason = reason for errback in self._errbacks: try: errback(reason) except Exception: # Ignore errors in callbacks pass # We will never call these errbacks again, so allow # them to... |
def get(self, timeout=None): """Get the value of the promise, waiting if necessary.""" self.wait(timeout) if self._state==self.FULFILLED: return self.value else: raise ValueError("Calculation didn't yield a value") |
def wait(self, timeout=None): """ An implementation of the wait method which doesn't involve polling but instead utilizes a "real" synchronization scheme. """ import threading if self._state!=self.PENDING: return e = threading.Event() self.addCallback(lambda v: e.set()) self.addErrback(lambda r: e.set()) e.wait(timeout... |
def then(self, success=None, failure=None): """ This method takes two optional arguments. The first argument is used if the "self promise" is fulfilled and the other is used if the "self promise" is rejected. In either case, this method returns another promise that effectively represents the result of either the first ... |
which, when fulfilled or rejected, will cascade its value or reason to the promise returned by this method. * A value - which will be assigned as either the value or the reason for the promise returned by this method when the "self promise" is either fulfilled or rejected, respectively. """ ret = Promise() def callAndF... |
newvalue.then(lambda v: ret.fulfill(v), lambda r: ret.reject(r)) else: ret.fulfill(newvalue) elif failure!=None: # From 3.2.6.5 ret.reject(r) else: pass except Exception as e: ret.reject(e) if self._state==self.PENDING: """ If this is still pending, then add callbacks to the existing promise that call either the succes... |
elif self._state==self.REJECTED: """ If this promise was already rejected, then we need to use the second argument to this method to determine the value to use in fulfilling the promise that we return from this method. """ try: if _isFunction(failure): newvalue = failure(self.reason) if _isPromise(newvalue): newvalue.t... |
def compute_samples(f, x, samples, **kwargs): r""" Apply f(x,theta) to x array and theta in samples. Parameters ---------- f: function list of functions :math:`f(x;\theta)` with dependent variable :math:`x`, parameterised by :math:`\theta`. x: 1D array-like x values to evaluate :math:`f(x;\theta)` at. samples: 2D array... |
zip(f, samples): if len(s) > 0: fsamps = parallel_apply(fi, s, precurry=(x,), parallel=parallel, tqdm_kwargs=tqdm_kwargs) fsamps = numpy.array(fsamps).transpose().copy() fsamples.append(fsamps) fsamples = numpy.concatenate(fsamples, axis=1) if cache: cache.save(x, samples, fsamples) return fsamples |
def samples_from_getdist_chains(params, file_root, latex=False): """ Extract samples and weights from getdist chains. Parameters ---------- params: list(str) Names of parameters to be supplied to second argument of f(x|theta). file_root: str, optional Root name for getdist chains files. This variable automatically defi... |
[samples.parLabel(p) for p in params] return samps, weights, latex else: return samps, weights |
def get_session_url(session_id, type='view', **params): """ Allowed types are: `view`, `assets`, `download`. """ url = 'sessions/{}/{}'.format(session_id, type) url = urljoin(API_URL, url) return add_to_url(url, **params) |
def checkArgs(args): """Checks the arguments and options. :param args: a an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to... |
def main(cert, key, pushtoken, url): """Create, connect, and block on the listener worker.""" try: worker = APNSWorker(cert=cert, key=key, pushtoken=pushtoken, url=url) worker.connect() worker.run_forever() except KeyboardInterrupt: worker.close() |
def opened(self): """Connect to the websocket, and ensure the account is connected and the INBOX is being watched, and then start watchingAll. """ def post_setup((cmds, resps)): """Post setup callback.""" logger.info("Setup complete, listening...") self.send_cmds(('connect', CONN_SPEC), ('watchMailboxes', {'account': A... |
def valuedispatch(func): """Decorates a function to dispatch handler of the value of the first argument. """ registry = {} def dispatch(value): return registry.get(value, func) def register(value, func=None): if func is None: return lambda f: register(value, f) registry[value] = func return func def wrapper(*args, **kw... |
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node # NOQA """Resolve the pending_xref *node* with the given *typ* and *target*. This method should return a new node, to replace the xref node... |
def weld_merge_join(arrays_self, weld_types_self, arrays_other, weld_types_other, how, is_on_sorted, is_on_unique, readable_text): """Applies merge-join on the arrays returning indices from each to keep in the resulting Parameters ---------- arrays_self : list of (numpy.ndarray or WeldObject) Columns from the self Data... |
------- tuple of WeldObject Two columns of indices from the input arrays, indices of the rows from self and other that should be available in the resulting joined DataFrame. """ assert is_on_unique weld_obj_vec_of_struct_self = weld_arrays_to_vec_of_struct(arrays_self, weld_types_self) weld_obj_vec_of_struct_other = we... |
def weld_merge_outer_join(arrays_self, weld_types_self, arrays_other, weld_types_other, how, is_on_sorted, is_on_unique, readable_text): """Applies merge-join on the arrays returning indices from each to keep in the resulting Parameters ---------- arrays_self : list of (numpy.ndarray or WeldObject) Columns from the sel... |
add in the Weld placeholder. Returns ------- tuple of WeldObject Three objects: first 2 are indices from the input arrays, indices of the rows from self and other that should be available in the resulting joined DataFrame. The last object will be a tuple containing the new index with actual values, not indices to other... |
def weld_align(df_index_arrays, df_index_weld_types, series_index_arrays, series_index_weld_types, series_data, series_weld_type): """Returns the data from the Series aligned to the DataFrame index. Parameters ---------- df_index_arrays : list of (numpy.ndarray or WeldObject) The index columns as a list. df_index_weld_... |
) ) )""" weld_obj.weld_code = weld_template.format(series_dict=series_dict_obj_id, df_index=df_index_obj_id, index_type=index_type, data_type=series_weld_type, missing=missing_literal) return weld_obj |
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Checks the number of samples in the ``tfam`` file (:py:func:`compute_nb_samples`). 3. Computes the heterozygosity rate (:py:func:`compute_heterozygosity`). 4.... |
def save_heterozygosity(heterozygosity, samples, out_prefix): """Saves the heterozygosity data. :param heterozygosity: the heterozygosity data. :param samples: the list of samples. :param out_prefix: the prefix of the output files. :type heterozygosity: numpy.array :type samples: list of tuples of str :type out_prefix:... |
def compute_nb_samples(in_prefix): """Check the number of samples. :param in_prefix: the prefix of the input file. :type in_prefix: str :returns: the number of sample in ``prefix.fam``. """ file_name = in_prefix + ".tfam" nb = None with open(file_name, 'rb') as input_file: nb = len(input_file.readlines()) return nb |
def compute_heterozygosity(in_prefix, nb_samples): """Computes the heterozygosity ratio of samples (from tped).""" tped_name = in_prefix + ".tped" tfam_name = in_prefix + ".tfam" # The function we want to use check_heterozygosity = np.vectorize(is_heterozygous) # The autosomes autosomes = {str(i) for i in xrange(1, 23)... |
each samples (excluding no calls) nb_markers += genotypes != "0 0" return np.true_divide(heterozygosity, nb_markers), samples |
def plot_heterozygosity(heterozygosity, options): """Plots the heterozygosity rate distribution. :param heterozygosity: the heterozygosity data. :param options: the options. :type heterozygosity: numpy.array :type options: argparse.Namespace Plots a histogram or a boxplot of the heterozygosity distribution. """ # impor... |
notch=True, vert=False) else: # Specific settings for the histogram ax.set_ylabel("Proportion") # The histogram ax.hist( heterozygosity, bins=options.bins, color="#0099CC", histtype="stepfilled", weights=np.zeros_like(heterozygosity) + 1.0 / len(heterozygosity), ) # Plotting the mean, the median and the variance the_me... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
def addEmptyTab(self, text=''): """ Add a new DEFAULT_TAB_WIDGET, open editor to set text if no text is given """ tab = self.defaultTabWidget() c = self.count() self.addTab(tab, text) self.setCurrentIndex(c) if not text: self.tabBar().editTab(c) self.sigTabAdded.emit(tab) return tab |
def _mkAddBtnVisible(self): """ Ensure that the Add button is visible also when there are no tabs """ if not self._btn_add_height: # self._btn_add_height = self.cornerWidget().height() self._btn_add_height = self._cwBtn.height() if self.count() == 0: # self.cornerWidget().setMinimumHeight(self._btn_add_height - 8) self... |
def removeTab(self, tab): """allows to remove a tab directly -not only by giving its index""" if not isinstance(tab, int): tab = self.indexOf(tab) return super(FwTabWidget, self).removeTab(tab) |
def tabText(self, tab): """ allow index or tab widget instance""" if not isinstance(tab, int): tab = self.indexOf(tab) return super(FwTabWidget, self).tabText(tab) |
def on_failure(self, entity): """ Callback function when there is a failure in a connection to whatsapp server """ logger.error("Login failed, reason: %s" % entity.getReason()) self.connected = False |
def on_message(self, message_protocol_entity): """ Callback function when receiving message from whatsapp server """ logger.info("Message id %s received" % message_protocol_entity.getId()) # answer with receipt self.toLower(message_protocol_entity.ack()) |
def send_message(self, number, content): """ Send message :param str number: phone number with cc (country code) :param str content: body text of the message """ outgoing_message = TextMessageProtocolEntity(content.encode("utf-8") if sys.version_info >= (3, 0) else content, to=self.normalize_jid(number)) self.toLower(o... |
def send_image(self, number, path, caption=None): """ Send image message :param str number: phone number with cc (country code) :param str path: image file path """ return self._send_media_path(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, caption) |
def send_audio(self, number, path): """ Send audio message :param str number: phone number with cc (country code) :param str path: audio file path """ return self._send_media_path(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO) |
def send_location(self, number, name, url, latitude, longitude): """ Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str url: location url :param str longitude: location longitude :param str latitude: location latitude """ location_messag... |
def send_vcard(self, number, name, data): """ Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str data: vcard format i.e. BEGIN:VCARD VERSION:3.0 N:;Home;;; FN:Home item1.TEL:+34 911234567 item1.X-ABLabel:Home END:VCARD """ vcard_message ... |
def open_archive(stream, filename): """ Open an archive (tarball or zip) and return the object. """ name, ext = os.path.splitext(os.path.basename(filename)) def targz_handler(stream): return TarGZAdapter(tarfile.open(fileobj=stream, mode='r:gz')) cls = [zipfile.ZipFile, targz_handler]['gz' in ext] archive = cls(stream)... |
def get_prefix_dir(archive): """ Often, all files are in a single directory. If so, they'll all have the same prefix. Determine any such prefix. archive is a ZipFile """ names = archive.namelist() shortest_name = sorted(names, key=len)[0] candidate_prefixes = [ shortest_name[:length] for length in range(len(shortest_na... |
def _clean_metadata(self): """ the long description doesn't load properly (gets unwanted indents), so fix it. """ desc = self.metadata.get_long_description() if not isinstance(desc, six.text_type): desc = desc.decode('utf-8') lines = io.StringIO(desc) def trim_eight_spaces(line): if line.startswith(' ' * 8): line = lin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.