text
stringlengths
81
112k
**Placeholder for the time being** :param response_args: :param request: :param kwargs: request arguments :return: Response information def do_response(self, response_args=None, request=None, **kwargs): """ **Placeholder for the time being** :param response_arg...
Build the session object. def get_session(): """Build the session object.""" # NOTE(msimonin): We provide only a basic support which focus # Chameleon cloud and its rc files if os.environ.get("OS_IDENTITY_API_VERSION") == "3": logging.info("Creating a v3 Keystone Session") auth = v3.Pas...
Check that the base image is available. Fails if the base image isn't added. This means the image should be added manually. def check_glance(session, image_name): """Check that the base image is available. Fails if the base image isn't added. This means the image should be added manually. """...
Build the flavors mapping returns the mappings id <-> flavor def check_flavors(session): """Build the flavors mapping returns the mappings id <-> flavor """ nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) flavors = nclie...
Check the network status for the deployment. If needed, it creates a dedicated : * private network /subnet * router between this network and the external network def check_network(session, configure_network, network, subnet, dns_nameservers=None, allocation_pool=None): """Che...
Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready. def wait_for_servers(session, servers): """Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready. """ nclient = nova.Client(NOVA_VERSION, session=sessio...
Checks the servers status for the deployment. If needed, it creates new servers and add a floating ip to one of them. This server can be used as a gateway to the others. def check_servers(session, machines, extra_prefix="", force_deploy=False, key_name=None, image_id=None, ...
Check if an existing server in the system take part to the current deployment def is_in_current_deployment(server, extra_prefix=""): """Check if an existing server in the system take part to the current deployment """ return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]), ...
Allow several interfaces to be added and accessed from the other machines. This is particularly useful when working with virtual ips. def allow_address_pairs(session, network, subnet): """Allow several interfaces to be added and accessed from the other machines. This is particularly useful when working w...
Check all ressources needed by Enos. def check_environment(provider_conf): """Check all ressources needed by Enos.""" session = get_session() image_id = check_glance(session, provider_conf.image) flavor_to_id, id_to_flavor = check_flavors(session) ext_net, network, subnet = check_network( s...
Implements matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html The lack of value is not checked here. Also the text doesn't prohibit having both 'value' and 'values'. :param value: single value :param claimspec: None or dictionary with 'essential', 'value' or...
Collect information about a user. This can happen in two cases, either when constructing an IdToken or when returning user info through the UserInfo endpoint :param session: Session information :param userinfo_claims: user info claims :return: User info def collect_user_info(endpoint_context, sess...
Collect user info claims that are to be placed in the id token. :param endpoint_context: Endpoint context :param session: Session information :param def_itc: Default ID Token claims :return: User information or None def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None): """ ...
Converted rows of tabular data. Returns: |list| or |tuple|: Table rows. def value_matrix(self): """Converted rows of tabular data. Returns: |list| or |tuple|: Table rows. """ if self.__value_matrix: return self.__value_matrix self....
:return: DataProperty for table data. :rtype: list def value_dp_matrix(self): """ :return: DataProperty for table data. :rtype: list """ if self.__value_dp_matrix is None: self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix( to_value_ma...
:raises ValueError: def validate_rows(self): """ :raises ValueError: """ invalid_row_idx_list = [] for row_idx, row in enumerate(self.rows): if isinstance(row, (list, tuple)) and len(self.headers) != len(row): invalid_row_idx_list.append(row_idx) ...
:return: Table data as a |dict| instance. :rtype: dict :Sample Code: .. code:: python from tabledata import TableData TableData( "sample", ["a", "b"], [[1, 2], [3.3, 4.4]] ).as_dict...
:return: Rows of the table. :rtype: list of |namedtuple| :Sample Code: .. code:: python from tabledata import TableData records = TableData( "sample", ["a", "b"], [[1, 2], [3.3, 4.4]] ...
:return: Table data as a ``pandas.DataFrame`` instance. :rtype: pandas.DataFrame :Sample Code: .. code-block:: python from tabledata import TableData TableData( "sample", ["a", "b"], [[1, 2], [3.3,...
Initialize TableData instance from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: :param str table_name: Table name to create. def from_dataframe(dataframe, table_name=""): """ Initialize TableData instance from a pandas.DataFrame instance. :param pandas.DataF...
Decorates a function to be called async on the loop thread def call_async(func): """Decorates a function to be called async on the loop thread""" @wraps(func) def wrapper(self, *args, **kw): """Wraps instance method to be called on loop thread""" def call(): """Calls function ...
Decorates a function to be called sync on the loop thread def call_sync(func): """Decorates a function to be called sync on the loop thread""" @wraps(func) def wrapper(self, *args, **kw): """Wraps instance method to be called on loop thread""" # Just return when already on the event threa...
Thread routine def target(self): """Thread routine""" while self.event.wait(): self.event.clear() while True: with self.lock: if not self.count: break self.count -= 1 with self.condit...
Actual thread def _loop(self, barrier): """Actual thread""" if sys.platform != "win32": self.loop = asyncio.new_event_loop() else: self.loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(self.loop) barrier.wait() try: self.loop...
Creates a new connection def create_connection(self, room, ws_url, agent, cookies): """Creates a new connection""" urlparts = urlsplit(ws_url) req = Request("GET", ws_url) cookies = get_cookie_header(cookies, req) if cookies: headers = dict(Cookie=cookies) e...
Sends a message def __send_message(self, proto, payload): # pylint: disable=no-self-use """Sends a message""" try: if not isinstance(payload, bytes): payload = payload.encode("utf-8") if not proto.connected: raise IOError("not connected")...
Closes a connection def close(self, proto): # pylint: disable=no-self-use """Closes a connection""" try: proto.sendClose() except Exception as ex: logger.exception("Failed to send close") proto.reraise(ex)
Process queue for these listeners. Only the items with type that matches def process(self): """Process queue for these listeners. Only the items with type that matches """ with self.lock, self.enlock: queue = copy(self.queue) self.queue.clear() callb...
Add a new listener def add(self, callback_type, callback): """Add a new listener""" with self.lock: self.callbacks[callback_type].append(callback)
Queue a new data item, make item iterable def enqueue(self, item_type, item): """Queue a new data item, make item iterable""" with self.enlock: self.queue[item_type].append(item)
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy array Image corresponding to the slitlet reg...
Determine the location of known arc lines in slitlet. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. times_sigma_threshold : float Times (robust) sigma above the median of the image to look for arc lines. ...
Compute intersection points of spectrum trails with arc lines. The member list_arc_lines is updated with new keyword:keyval values for each arc line. Parameters ---------- slitlet2d : numpy array Slitlet image to be displayed with the computed boundaries ...
Estimate the polynomial transformation to rectify the image. Parameters ---------- order : int Order of the polynomial transformation. slitlet2d : numpy array Slitlet image to be displayed with the computed boundaries and intersecting points overplott...
Rectify slitlet using computed transformation. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. resampling : int 1: nearest neighbour, 2: flux preserving interpolation. transformation : int 1: initial, 2: mo...
Median spectrum and line peaks from rectified image. In order to avoid the line ghosts, the line peaks are identified independently in the upper and lower halves of the rectified image. The final peaks correspond to lines that appear in both spectra. Parameters --------...
Intersection between two segments. def intersection(a, b, scale=1): '''Intersection between two segments.''' try: a1, a2 = a except TypeError: a1 = a.start a2 = a.stop try: b1, b2 = b except TypeError: b1 = b.start b2 = b.stop if a2 <= b1: ...
Intersect slices with a region. def clip_slices(r, region, scale=1): '''Intersect slices with a region.''' t = [] for ch in r: a1 = intersection(ch[0], region[0], scale=scale) if a1 is None: continue a2 = intersection(ch[1], region[1], scale=scale) if a2 is None:...
Set metadata in FITS headers. def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr) hdr['IMGOBBL'] = 0 hdr['OBSMODE'] = 'DITHERED_IMAGE' return hdr
Load common defaults data structures. For factorization purpose. def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None, basedir=False): """Load common defaults data structures. For factorization purpose.""" extra_vars = extra_vars or {} tags = tags or ...
Run a play. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/ansible/latest/intro_patterns.html play_source (dict): ansible task inventory_path (str): inventory to use extra_vars (dict): extra_vars to use on_err...
Run a shell command on some remote hosts. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/ansible/latest/intro_patterns.html command (str): the command to run inventory_path (str): inventory to use extra_vars (dict): e...
Run Ansible. Args: playbooks (list): list of paths to the playbooks to run inventory_path (str): path to the hosts file (inventory) extra_var (dict): extra vars to pass tags (list): list of tags to run on_error_continue(bool): Don't throw any exception in case a host is ...
Checks the network interfaces on the nodes. This enables to auto-discover the mapping interface name <-> network role. Beware, this has a side effect on each Host in roles. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` ne...
Generate an inventory file in the ini format. The inventory is generated using the ``roles`` in the ``ini`` format. If ``check_network == True``, the function will try to discover which networks interfaces are available and map them to one network of the ``networks`` parameters. Note that this auto-d...
Emulate network links. Read ``network_constraints`` and apply ``tc`` rules on all the nodes. Constraints are applied between groups of machines. Theses groups are described in the ``network_constraints`` variable and must be found in the inventory file. The newtwork constraints support ``delay``, ``rat...
Validate the network parameters (latency, bandwidth ...) Performs flent, ping tests to validate the constraints set by :py:func:`emulate_network`. Reports are available in the tmp directory used by enos. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra...
Reset the network constraints (latency, bandwidth ...) Remove any filter that have been applied to shape the traffic. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` inventory (str): path to the inventory def reset_network(rol...
Wait for all the machines to be ssh-reachable Let ansible initiates a communication and retries if needed. Args: inventory (string): path to the inventoy file to test retries (int): Number of time we'll be retrying an SSH connection interval (int): Interval to wait in seconds between t...
Expand group names. Args: grp (string): group names to expand Returns: list of groups Examples: * grp[1-3] will be expanded to [grp1, grp2, grp3] * grp1 will be expanded to [grp1] def expand_groups(grp): """Expand group names. Args: grp (string): group n...
Expand the description given the group names/patterns e.g: {src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions def _expand_description(desc): """Expand the description given the group names/patterns e.g: {src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions """ srcs = ...
Generate default symetric grp constraints. def _generate_default_grp_constraints(roles, network_constraints): """Generate default symetric grp constraints. """ default_delay = network_constraints.get('default_delay') default_rate = network_constraints.get('default_rate') default_loss = network_cons...
Generate the user specified constraints def _generate_actual_grp_constraints(network_constraints): """Generate the user specified constraints """ if 'constraints' not in network_constraints: return [] constraints = network_constraints['constraints'] actual = [] for desc in constraints:...
Merge the constraints avoiding duplicates Change constraints in place. def _merge_constraints(constraints, overrides): """Merge the constraints avoiding duplicates Change constraints in place. """ for o in overrides: i = 0 while i < len(constraints): c = constraints[i] ...
Generate constraints at the group level, It expands the group names and deal with symetric constraints. def _build_grp_constraints(roles, network_constraints): """Generate constraints at the group level, It expands the group names and deal with symetric constraints. """ # generate defaults constrai...
Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules. def _build_ip_constraints(roles, ips, constraints): """Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules. """ ...
Decorate each networks with the corresponding nic name. def _map_device_on_host_networks(provider_nets, devices): """Decorate each networks with the corresponding nic name.""" networks = copy.deepcopy(provider_nets) for network in networks: for device in devices: network.setdefault('dev...
Use ``dateutil.rrule`` to create a range of dates. The frequency must be a string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or SECONDLY. See `dateutil rrule`_ documentation for more detail. .. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html :pa...
Calculate the total energy accumulated from AC power at the end of each timestep between the given times. :param ac_power: AC Power [W] :param times: times :type times: np.datetime64[s] :return: energy [W*h] and energy times def f_energy(ac_power, times): """ Calculate the total energy acc...
Group timeseries by frequency. The frequency must be a string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or SECONDLY. The optional weekstart must be a string in the following list: MO, TU, WE, TH, FR, SA and SU. :param items: items in timeseries :param times: times corr...
Use :func:`groupby_freq` to rollup items :param items: items in timeseries :param times: times corresponding to items :param freq: One of the ``dateutil.rrule`` frequency constants :type freq: str def f_rollup(items, times, freq): """ Use :func:`groupby_freq` to rollup items :param items:...
Method to update extra metadata fields with dict obtained through `fileinfo` def fileupdate(self, data): """Method to update extra metadata fields with dict obtained through `fileinfo`""" self.name = data["name"] add = self.__additional add["filetype"] = "other" ...
Returns the thumbnail's url for this image, audio, or video file. Returns empty string if the file has no thumbnail def thumbnail(self): """Returns the thumbnail's url for this image, audio, or video file. Returns empty string if the file has no thumbnail""" if self.filetype not in ("v...
Returns the duration in seconds of this audio or video file def duration(self): """Returns the duration in seconds of this audio or video file""" if self.filetype not in ("video", "audio"): raise RuntimeError("Only videos and audio have durations") return self.info.get("length") or...
Remove this file def delete(self): """ Remove this file """ self.room.check_owner() self.conn.make_call("deleteFiles", [self.fid])
Timeout the uploader of this file def timeout(self, duration=3600): """ Timeout the uploader of this file """ self.room.check_owner() self.conn.make_call("timeoutFile", self.fid, duration)
Change the group of the running process def set_gid(self): """Change the group of the running process""" if self.group: gid = getgrnam(self.group).gr_gid try: os.setgid(gid) except Exception: message = ("Unable to switch ownership to {...
Change the user of the running process def set_uid(self): """Change the user of the running process""" if self.user: uid = getpwnam(self.user).pw_uid try: os.setuid(uid) except Exception: message = ('Unable to switch ownership to {0}:{...
Set up self.logger This function is called after load_configuration() and after changing to new user/group IDs (if configured). Logging to syslog using the root logger is configured by default, you can override this method if you want something else. def setup_logging(self): ""...
Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 def daemonize(self): """ Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX ...
Start the daemon def start(self): """Start the daemon""" if self._already_running(): message = 'pid file %s already exists. Daemon already running?\n' sys.stderr.write(message % self.pid_file) return 0 self.set_gid() self.set_uid() # Create lo...
Stop the daemon def stop(self): """Stop the daemon""" if self._already_running(): return self.reliable_kill() else: # FIXME: misleading error message message = 'Daemon not running, nothing to do.\n' sys.stderr.write(message) return 0
Determine the status of the daemon def status(self): """Determine the status of the daemon""" my_name = os.path.basename(sys.argv[0]) if self._already_running(): message = "{0} (pid {1}) is running...\n".format(my_name, self.pid) sys.stdout.write(message) re...
Retrieves embeddable resource from given ``uri``. For now only local resources (images, fonts) are supported. :param str uri: path or url to image or font resource :returns: path to local resource file. :rtype: str :raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException` def fetch_resou...
Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` def html_to_pdf(content, encoding="utf-8", link_callback=fetch_resources, **kwargs): """ Convert...
Wraps content into HTTP response. If ``filename`` is specified then ``Content-Disposition: attachment`` header is added to the response. Default ``Content-Type`` is ``application/pdf``. :param bytes content: response content :param str filename: optional filename for file download :param str ...
Create PDF document from Django html template. :param str template: Path to Django template :param dict context: Template context :param using: Optional Django template engine :param request: Django HTTP request :type request: :class:`django.http.HttpRequest` :returns: rendered PDF :rtype:...
Renders a PDF response using given ``request``, ``template`` and ``context``. If ``filename`` param is specified then the response ``Content-Disposition`` header will be set to ``attachment`` making the browser display a "Save as.." dialog. :param request: Django HTTP request :type request: :class...
Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`django.http.HttpResponse` def get_pdf_response(self, context, **response_kwargs): """ Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`d...
Replace all strings in dictionary with compiled version of themselves and return dictionary. def compile_patterns_in_dictionary(dictionary): """ Replace all strings in dictionary with compiled version of themselves and return dictionary. """ for key, value in dictionary.items(): if isin...
Validate options. def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'delimiters': for d in v: if not isinstance(d, (dict, OrderedDict)): raise ValueError("{}: 'delimters' entries must be of dict type...
Setup. def setup(self): """Setup.""" self.context_visible_first = self.config['context_visible_first'] self.delimiters = [] self.escapes = None self.line_endings = self.config['normalize_line_endings'] escapes = [] for delimiter in self.config['delimiters']: ...
Parse file. def filter(self, source_file, encoding): # noqa A001 """Parse file.""" with codecs.open(source_file, 'r', encoding=encoding) as f: text = f.read() return [filters.SourceText(self._filter(text), source_file, encoding, 'context')]
Filter. def sfilter(self, source): """Filter.""" return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')]
Context delimiter filter. def _filter(self, text): """Context delimiter filter.""" if self.line_endings: text = self.norm_nl(text) new_text = [] index = 0 last = 0 end = len(text) while index < end: m = self.escapes.match(text, pos=index...
Create a connection which can later be upgraded to use TLS. .. versionchanged:: 0.4 The `local_addr` argument was added. :param loop: The event loop to use. :type loop: :class:`asyncio.BaseEventLoop` :param protocol_factory: Factory for the protocol for the connection :param host: The hos...
Clean up all resources and call the protocols connection lost method. def _call_connection_lost_and_clean_up(self, exc): """ Clean up all resources and call the protocols connection lost method. """ self._state = _State.CLOSED try: self._protocol.connection_lost(exc...
Immediately close the stream, without sending remaining buffers or performing a proper shutdown. def abort(self): """ Immediately close the stream, without sending remaining buffers or performing a proper shutdown. """ if self._state == _State.CLOSED: self._i...
Close the stream. This performs a proper stream shutdown, except if the stream is currently performing a TLS handshake. In that case, calling :meth:`close` is equivalent to calling :meth:`abort`. Otherwise, the transport waits until all buffers are transmitted. def close(self): """ ...
Start a TLS stream on top of the socket. This is an invalid operation if the stream is not in RAW_OPEN state. If `ssl_context` is set, it overrides the `ssl_context` passed to the constructor. If `post_handshake_callback` is set, it overrides the `post_handshake_callback` passed to the ...
Write data to the transport. This is an invalid operation if the stream is not writable, that is, if it is closed. During TLS negotiation, the data is buffered. def write(self, data): """ Write data to the transport. This is an invalid operation if the stream is not writable, th...
given an array of objects de-normalized into fields def explode(prefix: str): """ given an array of objects de-normalized into fields """ def _app(i, e=None): if i is not None: return {k: v for (k, v) in iter_fields(i)}, None return i, e def iter_fields(event_field: Uni...
Check XML encoding. def _has_xml_encode(self, content): """Check XML encoding.""" encode = None m = RE_XML_START.match(content) if m: if m.group(1): m2 = RE_XML_ENCODE.match(m.group(1)) if m2: enc = m2.group(2).decode('a...
Check if tag is an element we should break on. def is_break_tag(self, el): """Check if tag is an element we should break on.""" name = el.name return name in self.break_tags or name in self.user_break_tags
Store the text as desired. def store_blocks(self, el, blocks, text, force_root): """Store the text as desired.""" if force_root or el.parent is None or self.is_break_tag(el): content = ''.join(text) if content: blocks.append((content, self.construct_selector(el)...
Construct an selector for context. def construct_selector(self, el, attr=''): """Construct an selector for context.""" selector = deque() ancestor = el while ancestor and ancestor.parent: if ancestor is not el: selector.appendleft(ancestor.name) ...
Extract text from tags. Skip any selectors specified and include attributes if specified. Ignored tags will not have their attributes scanned either. def to_text(self, tree, force_root=False): """ Extract text from tags. Skip any selectors specified and include attributes if s...
Filter the source text. def _filter(self, text, context, encoding): """Filter the source text.""" content = [] blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser)) if self.comments: for c, desc in comments: content.append(filters...
Filter. def sfilter(self, source): """Filter.""" return self._filter(source.text, source.context, source.encoding)
Decorator for declaring a lazy import. This decorator turns a function into an object that will act as a lazy importer. Whenever the object's attributes are accessed, the function is called and its return value used in place of the object. So you can declare lazy imports like this: @lazy_imp...