code
stringlengths
1
18.2k
def _set_remote(self, stream=False): """ Call :py:meth:`~._args_for_remote`; if the return value is not None, execute 'terraform remote config' with those arguments and ensure it exits 0. :param stream: whether or not to stream TF output in realtime :type stream: bool """ args = self._args_for_remote() if args is None:...
def _run_tf(self, cmd, cmd_args=[], stream=False): """ Run a single terraform command via :py:func:`~.utils.run_cmd`; raise exception on non-zero exit status. :param cmd: terraform command to run :type cmd: str :param cmd_args: arguments to command :type cmd_args: :std:term:`list` :return: command output :rtype: str :r...
def _taint_deployment(self, stream=False): """ Run 'terraform taint aws_api_gateway_deployment.depl' to taint the deployment resource. This is a workaround for https://github.com/hashicorp/terraform/issues/6613 :param stream: whether or not to stream TF output in realtime :type stream: bool """ args = ['aws_api_gateway...
def apply(self, stream=False): """ Run a 'terraform apply' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) try: self._taint_deployment(stream=stream) except Exception: pass args = ['-input=false', '-refresh=true', '.'] logger.warning('Running terraform ...
def _show_outputs(self): """ Print the terraform outputs. """ outs = self._get_outputs() print("\n\n" + '=> Terraform Outputs:') for k in sorted(outs): print('%s = %s' % (k, outs[k]))
def _get_outputs(self): """ Return a dict of the terraform outputs. :return: dict of terraform outputs :rtype: dict """ if self.tf_version >= (0, 7, 0): logger.debug('Running: terraform output') res = self._run_tf('output', cmd_args=['-json']) outs = json.loads(res.strip()) res = {} for k in outs.keys(): if isinstance(...
def destroy(self, stream=False): """ Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) args = ['-refresh=true', '-force', '.'] logger.warning('Running terraform destroy: %s', ' '.join(args)) out = self._run_tf('destroy', cmd_args...
def _setup_tf(self, stream=False): """ Setup terraform; either 'remote config' or 'init' depending on version. """ if self.tf_version < (0, 9, 0): self._set_remote(stream=stream) return self._run_tf('init', stream=stream) logger.info('Terraform initialized')
def new_conn(self): """ Create a new ConnectionWrapper instance :return: """ """ :return: """ logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args) return ConnectionWrapper(self._pool, **self._conn_args)
def acquire(self, timeout=None): """Acquire a connection :param timeout: If provided, seconds to wait for a connection before raising Queue.Empty. If not provided, blocks indefinitely. :returns: Returns a RethinkDB connection :raises Empty: No resources are available before timeout. """ self._pool_lock.acquire() if tim...
def release(self, conn): """Release a previously acquired connection. The connection is put back into the pool.""" self._pool_lock.acquire() self._pool.put(ConnectionWrapper(self._pool, conn)) self._current_acquired -= 1 self._pool_lock.release()
def release_pool(self): """Release pool and all its connection""" if self._current_acquired > 0: raise PoolException("Can't release pool: %d connection(s) still acquired" % self._current_acquired) while not self._pool.empty(): conn = self.acquire() conn.close() if self._cleanup_thread is not None: self._thread_event.se...
def index(self): """ Reset inspector buffers and index project sources dependencies. This have to be executed each time an event occurs. Note: If a Boussole exception occurs during operation, it will be catched and an error flag will be set to ``True`` so event operation will be blocked without blocking or breaking wat...
def compile_source(self, sourcepath): """ Compile source to its destination Check if the source is eligible to compile (not partial and allowed from exclude patterns) Args: sourcepath (string): Sass source path to compile to its destination using project settings. Returns: tuple or None: A pair of (sourcepath, destinat...
def compile_dependencies(self, sourcepath, include_self=False): """ Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``True`` the given sourcepath is add to items to compile, else only its depen...
def on_moved(self, event): """ Called when a file or a directory is moved or renamed. Many editors don't directly change a file, instead they make a transitional file like ``*.part`` then move it to the final filename. Args: event: Watchdog event, either ``watchdog.events.DirMovedEvent`` or ``watchdog.events.FileModifi...
def on_created(self, event): """ Called when a new file or directory is created. Todo: This should be also used (extended from another class?) to watch for some special name file (like ".boussole-watcher-stop" create to raise a KeyboardInterrupt, so we may be able to unittest the watcher (click.CliRunner is not able to...
def on_modified(self, event): """ Called when a file or directory is modified. Args: event: Watchdog event, ``watchdog.events.DirModifiedEvent`` or ``watchdog.events.FileModifiedEvent``. """ if not self._event_error: self.logger.info(u"Change detected from an edit on: %s", event.src_path) self.compile_dependencies(even...
def on_deleted(self, event): """ Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or ``watchdog.events.FileDeletedEvent``. """ if not self._event_error: self.logger.info(u"...
def compile_dependencies(self, sourcepath, include_self=True): """ Same as inherit method but the default value for keyword argument ``ìnclude_self`` is ``True``. """ return super(SassProjectEventHandler, self).compile_dependencies( sourcepath, include_self=include_self )
def requests_get(url): """ Run :func:`requests.get` in a ``cached()`` wrapper. The cache wrapper uses the default timeout (environment variable ``PYTHON_FTR_CACHE_TIMEOUT``, 3 days by default). It is used in :func:`ftr_process`. """ LOGGER.info(u'Fetching %s…', url) return requests.get(url)
def sanitize_next_page_link(next_page_link, base_url): """ Convert relative links or query_string only links to absolute URLs. """ if not next_page_link.startswith(u'http'): if next_page_link.startswith(u'?'): # We have some "?current_page=2" scheme. next_page_link = base_url + next_page_link if next_page_link.startswi...
def ftr_process(url=None, content=None, config=None, base_url=None): u""" process an URL, or some already fetched content from a given URL. :param url: The URL of article to extract. Can be ``None``, but only if you provide both ``content`` and ``config`` parameters. :type url: str, unicode or ``None`` :param content: ...
URLs. It will hold the base URL (the first one fetched), and will serve as base for fixing non-schemed URLs or query_string-only links to next page(s). Please do not set this parameter until you very know what you are doing. Default: ``None``. :type base_url: str or unicode or None :raises: - :class:`RuntimeError` in a...
— and concatenated into the instance :attr:`body` attribute. The :attr:`next_page_link` attribute will be a ``list`` containing all sub-pages links. Note: the first link is the one you fed the extractor with ; it will not be repeated in the list. - or ``None``, if content was not given and url fetching returned a non-O...
if url is None: raise RuntimeError('When content is unset, url must be set.') try: result = requests_get(url) if result.status_code != requests.codes.ok: LOGGER.error(u'Wrong status code in return while getting ' u'“%s”.', url) return None # Override before accessing result.text ; see `requests` doc. result.encoding = ...
is not None: extractor.next_page_link.extend(next_extractor.next_page_link) return extractor return None
def hebrew_number(num, hebrew=True, short=False): """Return "Gimatria" number.""" if not hebrew: return str(num) if not 0 <= num < 10000: raise ValueError('num must be between 0 to 9999, got:{}'.format(num)) hstring = u"" if num >= 1000: hstring += htables.DIGITS[0][num // 1000] hstring += u"' " num = num % 1000 while ...
= hstring[:-1] + u'"' + hstring[-1] return hstring
def get_omer_string(omer): # pylint: disable=too-many-branches """Return a string representing the count of the Omer.""" # TODO: The following function should be simplified (see pylint) tens = [u"", u"עשרה", u"עשרים", u"שלושים", u"ארבעים"] ones = [u"", u"אחד", u"שנים", u"שלושה", u"ארבעה", u"חמשה", u"ששה", u"שבעה", u"שמ...
omer == 1: omer_string += u'יום אחד ' else: # omer == 2 omer_string += u'שני ימים ' if omer > 6: omer_string += u'שהם ' weeks = omer // 7 days = omer % 7 if weeks > 2: omer_string += ones[weeks] + u' שבועות ' elif weeks == 1: omer_string += u'שבוע אחד ' else: # weeks == 2 omer_string += u'שני שבועות ' if days: omer_str...
def hdate(self): """Return the hebrew date.""" if self._last_updated == "hdate": return self._hdate return conv.jdn_to_hdate(self._jdn)
def hdate(self, date): """Set the dates of the HDate object based on a given Hebrew date.""" # Sanity checks if date is None and isinstance(self.gdate, datetime.date): # Calculate the value since gdate has been set date = self.hdate if not isinstance(date, HebrewDate): raise TypeError('date: {} is not of type HebrewDat...
def gdate(self): """Return the Gregorian date for the given Hebrew date object.""" if self._last_updated == "gdate": return self._gdate return conv.jdn_to_gdate(self._jdn)
def _jdn(self): """Return the Julian date number for the given date.""" if self._last_updated == "gdate": return conv.gdate_to_jdn(self.gdate) return conv.hdate_to_jdn(self.hdate)
def hebrew_date(self): """Return the hebrew date string.""" return u"{} {} {}".format( hebrew_number(self.hdate.day, hebrew=self.hebrew), # Day htables.MONTHS[self.hdate.month - 1][self.hebrew], # Month hebrew_number(self.hdate.year, hebrew=self.hebrew))
def holiday_description(self): """ Return the holiday description. In case none exists will return None. """ entry = self._holiday_entry() desc = entry.description return desc.hebrew.long if self.hebrew else desc.english
def _holiday_entry(self): """Return the abstract holiday information from holidays table.""" holidays_list = self.get_holidays_for_year() holidays_list = [ holiday for holiday, holiday_hdate in holidays_list if holiday_hdate.hdate == self.hdate ] assert len(holidays_list) <= 1 # If anything is left return it, otherwise...
def rosh_hashana_dow(self): """Return the Hebrew day of week for Rosh Hashana.""" jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Tishrei, 1)) return (jdn + 1) % 7 + 1
def pesach_dow(self): """Return the first day of week for Pesach.""" jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Nisan, 15)) return (jdn + 1) % 7 + 1
def omer_day(self): """Return the day of the Omer.""" first_omer_day = HebrewDate(self.hdate.year, Months.Nisan, 16) omer_day = self._jdn - conv.hdate_to_jdn(first_omer_day) + 1 if not 0 < omer_day < 50: return 0 return omer_day
def next_day(self): """Return the HDate for the next day.""" return HDate(self.gdate + datetime.timedelta(1), self.diaspora, self.hebrew)
def previous_day(self): """Return the HDate for the previous day.""" return HDate(self.gdate + datetime.timedelta(-1), self.diaspora, self.hebrew)
def upcoming_shabbat(self): """Return the HDate for either the upcoming or current Shabbat. If it is currently Shabbat, returns the HDate of the Saturday. """ if self.is_shabbat: return self # If it's Sunday, fast forward to the next Shabbat. saturday = self.gdate + datetime.timedelta( (12 - self.gdate.weekday()) % 7) ...
def upcoming_shabbat_or_yom_tov(self): """Return the HDate for the upcoming or current Shabbat or Yom Tov. If it is currently Shabbat, returns the HDate of the Saturday. If it is currently Yom Tov, returns the HDate of the first day (rather than "leil" Yom Tov). To access Leil Yom Tov, use upcoming_shabbat_or_yom_tov.p...
def first_day(self): """Return the first day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the first in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom Tov, nor Shabbat, this just returns itsel...
def last_day(self): """Return the last day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the last in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom Tov, nor Shabbat, this just returns itself. ...
def get_holidays_for_year(self, types=None): """Get all the actual holiday days for a given HDate's year. If specified, use the list of types to limit the holidays returned. """ # Filter any non-related holidays depending on Israel/Diaspora only holidays_list = [ holiday for holiday in htables.HOLIDAYS if (holiday.isra...
return product(*([x] if isinstance(x, int) else x for x in holiday.date)) # Compute out every actual Hebrew date on which a holiday falls for # this year by exploding out the possible days for each holiday. holidays_list = [ (holiday, HDate( heb_date=HebrewDate(self.hdate.year, date_instance[1], date_instance[0]), dias...
def upcoming_yom_tov(self): """Find the next upcoming yom tov (i.e. no-melacha holiday). If it is currently the day of yom tov (irrespective of zmanim), returns that yom tov. """ if self.is_yom_tov: return self this_year = self.get_holidays_for_year([HolidayTypes.YOM_TOV]) next_rosh_hashana = HDate( heb_date=HebrewDate...
def get_reading(self): """Return number of hebrew parasha.""" _year_type = (self.year_size() % 10) - 3 year_type = ( self.diaspora * 1000 + self.rosh_hashana_dow() * 100 + _year_type * 10 + self.pesach_dow()) _LOGGER.debug("Year type: %d", year_type) # Number of days since rosh hashana rosh_hashana = HebrewDate(self.hd...
indexes for the readings of the given year def unpack_readings(readings): return list(chain( *([x] if isinstance(x, int) else x for x in readings))) reading_for_year = htables.READINGS[year_type] readings = unpack_readings(reading_for_year) # Maybe recompute the year type based on the upcoming shabbat. # This avoids an...
def ls(ctx, available): "List installed datasets on path" path = ctx.obj['path'] global_ = ctx.obj['global_'] _ls(available=available, **ctx.obj)
def reqs(ctx, dataset, kwargs): "Get the dataset's pip requirements" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).reqs(**kwargs))
def size(ctx, dataset, kwargs): "Show dataset size" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)
def get(ctx, dataset, rm, keep_compressed, dont_process, dont_download, keep_raw, kwargs): "performs the operations download, extract, rm_compressed, processes and rm_raw, in sequence. KWARGS must be in the form: key=value, and are fowarded to all opeartions." kwargs = parse_kwargs(kwargs) process = not dont_process rm...
def rm(ctx, dataset, kwargs): "removes the dataset's folder if it exists" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm(**kwargs)
def rm_subsets(ctx, dataset, kwargs): "removes the dataset's training-set and test-set folders if they exists" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_subsets(**kwargs)
def extract(ctx, dataset, kwargs): "extracts the files from the compressed archives" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).extract(**kwargs)
def rm_compressed(ctx, dataset, kwargs): "removes the compressed files" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_compressed(**kwargs)
def process(ctx, dataset, kwargs): "processes the data to a friendly format" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).process(**kwargs)
def rm_raw(ctx, dataset, kwargs): "removes the raw unprocessed data" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_raw(**kwargs)
def hist(xs, range=None, margin=10, width=None): ''' xs: array of numbers, preferably an np.array, can contain nans, infinities range: (minimum, maximum) tuple of numbers (defaults to (min, max) of xs) margin: number of characters to use for the min-max labels (default: 10) width: number of characters that will fit in ...
np.isfinite(xs) # don't copy it unless we need to (we don't need to if there are only finite numbers) # but if there are some nans / infinities, remove them finite_xs = xs[finite] # if nonfinite.any() else xs # compute the histogram values as floats, which is easier, even though we renormalize anyway hist_values, bin_e...
%s' % ( ('(%d) -inf' % np.count_nonzero(neginf) if neginf.any() else '').rjust(margin), ('(%d) nan' % np.count_nonzero(nan) if nan.any() else '').center(len(cells)), ('(%d) +inf' % np.count_nonzero(posinf) if posinf.any() else '').ljust(margin) )
def points(ys, width=None): '''Usage: import scipy.stats def walk(steps, position=0): for step in steps: position += step yield position positions = list(walk(scipy.stats.norm.rvs(size=1000))) points(positions) ''' if width is None: width = terminal.width() ys = np.array(ys) n = len(ys) y_min, y_max = np.min(ys), np.ma...
% y_min
def write_moc_fits_hdu(moc): """Create a FITS table HDU representation of a MOC. """ # Ensure data are normalized. moc.normalize() # Determine whether a 32 or 64 bit column is required. if moc.order < 14: moc_type = np.int32 col_type = 'J' else: moc_type = np.int64 col_type = 'K' # Convert to the NUNIQ value which guar...
= fits.BinTableHDU(rec) # Mandatory Keywords. tbhdu.header['PIXTYPE'] = 'HEALPIX' tbhdu.header['ORDERING'] = 'NUNIQ' tbhdu.header['COORDSYS'] = 'C' tbhdu.header['MOCORDER'] = moc.order tbhdu.header.comments['PIXTYPE'] = 'HEALPix magic code' tbhdu.header.comments['ORDERING'] = 'NUNIQ coding method' tbhdu.header.comments...
def write_moc_fits(moc, filename, **kwargs): """Write a MOC as a FITS file. Any additional keyword arguments are passed to the astropy.io.fits.HDUList.writeto method. """ tbhdu = write_moc_fits_hdu(moc) prihdr = fits.Header() prihdu = fits.PrimaryHDU(header=prihdr) hdulist = fits.HDUList([prihdu, tbhdu]) hdulist.writet...
def read_moc_fits(moc, filename, include_meta=False, **kwargs): """Read data from a FITS file into a MOC. Any additional keyword arguments are passed to the astropy.io.fits.open method. """ hl = fits.open(filename, mode='readonly', **kwargs) read_moc_fits_hdu(moc, hl[1], include_meta)
def read_moc_fits_hdu(moc, hdu, include_meta=False): """Read data from a FITS table HDU into a MOC. """ if include_meta: header = hdu.header if 'MOCTYPE' in header: moc.type = header['MOCTYPE'] if 'MOCID' in header: moc.id = header['MOCID'] if 'ORIGIN' in header: moc.origin = header['ORIGIN'] if 'EXTNAME' in header: mo...
current_cells)
def _tracebacks(score_matrix, traceback_matrix, idx): """Implementation of traceeback. This version can produce empty tracebacks, which we generally don't want users seeing. So the higher level `tracebacks` filters those out. """ score = score_matrix[idx] if score == 0: yield () return directions = traceback_matrix[idx...
def tracebacks(score_matrix, traceback_matrix, idx): """Calculate the tracebacks for `traceback_matrix` starting at index `idx`. Returns: An iterable of tracebacks where each traceback is sequence of (index, direction) tuples. Each `index` is an index into `traceback_matrix`. `direction` indicates the direction into wh...
def build_score_matrix(a, b, score_func, gap_penalty): """Calculate the score and traceback matrices for two input sequences and scoring functions. Returns: A tuple of (score-matrix, traceback-matrix). Each entry in the score-matrix is a numeric score. Each entry in the traceback-matrix is a logical ORing of the direct...
= max_score for _, direction in scores: traceback_matrix[row, col] = traceback_matrix[row, col] | direction.value return score_matrix, traceback_matrix
def _traceback_to_alignment(tb, a, b): """Convert a traceback (i.e. as returned by `tracebacks()`) into an alignment (i.e. as returned by `align`). Arguments: tb: A traceback. a: the sequence defining the rows in the traceback matrix. b: the sequence defining the columns in the traceback matrix. Returns: An iterable of...
def align(a, b, score_func, gap_penalty): """Calculate the best alignments of sequences `a` and `b`. Arguments: a: The first of two sequences to align b: The second of two sequences to align score_func: A 2-ary callable which calculates the "match" score between two elements in the sequences. gap_penalty: A 1-ary calla...
in the corresponding sequence. """ score_matrix, tb_matrix = build_score_matrix(a, b, score_func, gap_penalty) max_score = max(score_matrix.values()) max_indices = (index for index, score in score_matrix.items() if score == max_score) alignments = ( tuple(_traceback_to_alignment(tb, a, b)) for idx in max_indices for tb...
def unsubscribe(user_id, from_all=False, campaign_ids=None, on_error=None, on_success=None): """ Unsubscribe a user from some or all campaigns. :param str | number user_id: the id you use to identify a user. this should be static for the lifetime of a user. :param bool from_all True to unsubscribe from all campaigns. T...
campaign_ids=campaign_ids, on_error=on_error, on_success=on_success, )
def subscribe(user_id, to_all=False, campaign_ids=None, on_error=None, on_success=None): """ Resubscribe a user to some or all campaigns. :param str | number user_id: the id you use to identify a user. this should be static for the lifetime of a user. :param bool to_all True to reubscribe to all campaigns. Take precede...
campaign_ids=campaign_ids, on_error=on_error, on_success=on_success, )
def disable_all_tokens(platform, user_id, on_error=None, on_success=None): """ Disable ALL device tokens for the given user on the specified platform. :param str platform The platform which to disable token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outbound.APNS). :para...
def disable_token(platform, user_id, token, on_error=None, on_success=None): """ Disable a device token for a user. :param str platform The platform which to disable token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outbound.APNS). :param str | number user_id: the id you ...
def register_token(platform, user_id, token, on_error=None, on_success=None): """ Register a device token for a user. :param str platform The platform which to register token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outbound.APNS). :param str | number user_id: the id y...
def alias(user_id, previous_id, on_error=None, on_success=None): """ Alias one user id to another. :param str | number user_id: the id you use to identify a user. this will be the user's primary user id. :param str | number previous_id: the id you previously used to identify a user (or the old user id you want to assoc...
__error_message(ERROR_USER_ID)) return if not isinstance(previous_id, six.string_types + (Number,)): on_error(ERROR_PREVIOUS_ID, __error_message(ERROR_PREVIOUS_ID)) return data = dict( user_id=user_id, previous_id=previous_id, ) try: resp = requests.post( "%s/identify" % __BASE_URL, data=json.dumps(data), headers=__HEA...
def identify(user_id, previous_id=None, group_id=None, group_attributes=None, first_name=None, last_name=None, email=None, phone_number=None, apns_tokens=None, gcm_tokens=None, attributes=None, on_error=None, on_success=None): """ Identifying a user creates a record of your user in Outbound. Identify calls should be ma...
the user's last name. :param str email: OPTIONAL the user's email address. :param str phone_number: OPTIONAL the user's phone number. :param str | list apns_tokens: OPTIONAL the device tokens for the user's iOS devices. If a single string is given it is put into a list. :param str | list gcm_tokens: OPTIONAL the device...
call if/when the API call succeeds. on_success callback takes no parameters. """ on_error = on_error or __on_error on_success = on_success or __on_success if not __is_init(): on_error(ERROR_INIT, __error_message(ERROR_INIT)) return if not isinstance(user_id, six.string_types + (Number,)): on_error(ERROR_USER_ID, __erro...
def track(user_id, event, first_name=None, last_name=None, email=None, phone_number=None, apns_tokens=None, gcm_tokens=None, user_attributes=None, properties=None, on_error=None, on_success=None, timestamp=None): """ For any event you want to track, when a user triggers that event you would call this function. You can ...
gcm_tokens: OPTIONAL the device tokens for the user's Android devices. If a single string is given it is put into a list. :param dict user_attributes: An optional dictionary with any additional freeform attributes describing the user. :param dict properties: An optional dictionary with any properties that describe the ...
on_success = on_success or __on_success if not __is_init(): on_error(ERROR_INIT, __error_message(ERROR_INIT)) return if not isinstance(user_id, six.string_types + (Number,)): on_error(ERROR_USER_ID, __error_message(ERROR_USER_ID)) return if not isinstance(event, six.string_types): on_error(ERROR_EVENT_NAME, __error_mes...
def dump(self, content, filepath, indent=4): """ Dump settings content to filepath. Args: content (str): Settings content. filepath (str): Settings file location. """ with open(filepath, 'w') as fp: json.dump(content, fp, indent=indent)
def parse(self, filepath, content): """ Parse opened settings content using JSON parser. Args: filepath (str): Settings object, depends from backend content (str): Settings content from opened file, depends from backend. Raises: boussole.exceptions.SettingsBackendError: If parser can not decode a valid JSON object. Ret...
def run_client(ip, port, authkey, max_items=None, timeout=2): """Connect to a SwarmServer and do its dirty work. :param ip: ip address of server :param port: port to connect to on server :param authkey: authorization key :param max_items: maximum number of items to process from server. Useful for say running clients on...
def worker(n): """Spend some time calculating exponentials.""" for _ in xrange(999999): a = exp(n) b = exp(2*n) return n, a
def imap_unordered(self, jobs, timeout=0.5): """A iterator over a set of jobs. :param jobs: the items to pass through our function :param timeout: timeout between polling queues Results are yielded as soon as they are available in the output queue (up to the discretisation provided by timeout). Since the queues can be ...