sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def confidence_interval_arr(data, conf=0.95): r""" Computes element-wise confidence intervals from a sample of ndarrays Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals Parameters ---------- data : ndarray (K, (shape)) ndarray of ndarrays, the first...
r""" Computes element-wise confidence intervals from a sample of ndarrays Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals Parameters ---------- data : ndarray (K, (shape)) ndarray of ndarrays, the first index is a sample index, the remaining indexes ar...
entailment
def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actio...
Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actions sent to the server. * the count of action...
entailment
def query_single(self, object_type, url_params, query_params=None): # type: (str, list, dict) -> dict """ Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL componen...
Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: the found object (a dictionary), which is em...
entailment
def query_multiple(self, object_type, page=0, url_params=None, query_params=None): # type: (str, int, list, dict) -> tuple """ Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermined. :param object_type: string constant query type...
Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermined. :param object_type: string constant query type: either "user" or "group") :param page: numeric page (0-based) of results to get (up to 200 in a page) :param url_params: optional lis...
entailment
def execute_single(self, action, immediate=False): """ Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands se...
Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands sent earlier in this command's batch), specify a True value for the immed...
entailment
def execute_multiple(self, actions, immediate=True): """ Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency yo...
Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency you can set immeediate=False which will cause the connection to wait ...
entailment
def _execute_batch(self, actions): """ Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action...
Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action objects to be executed :return: count of succe...
entailment
def make_call(self, path, body=None, delete=False): """ Make a single UMAPI call with error handling and retry on temporary failure. :param path: the string endpoint path for the call :param body: (optional) list of dictionaries to be serialized into the request body :return: the...
Make a single UMAPI call with error handling and retry on temporary failure. :param path: the string endpoint path for the call :param body: (optional) list of dictionaries to be serialized into the request body :return: the requests.result object (on 200 response), raise error otherwise
entailment
def paginate(query, org_id, max_pages=maxsize, max_records=maxsize): """ Paginate through all results of a UMAPI query :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param max_pages: the max number of pages to collect before...
Paginate through all results of a UMAPI query :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param max_pages: the max number of pages to collect before returning (default all) :param max_records: the max number of records to col...
entailment
def make_call(query, org_id, page): """ Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_...
Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param pa...
entailment
def do(self, **kwargs): """ Here for compatibility with legacy clients only - DO NOT USE!!! This is sort of mix of "append" and "insert": it puts commands in the list, with some half smarts about which commands go at the front or back. If you add multiple commands to the back in ...
Here for compatibility with legacy clients only - DO NOT USE!!! This is sort of mix of "append" and "insert": it puts commands in the list, with some half smarts about which commands go at the front or back. If you add multiple commands to the back in one call, they will get added sorted by comm...
entailment
def split(self, max_commands): """ Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one """ a_prior = A...
Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one
entailment
def append(self, **kwargs): """ Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls t...
Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls to append in that order. Luckily, append returns...
entailment
def insert(self, **kwargs): """ Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user creation), but may be need to beadded after other commands have already been specified. Later calls to insert put ...
Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user creation), but may be need to beadded after other commands have already been specified. Later calls to insert put their commands before those in the earlier calls...
entailment
def report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encounter...
Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encountered
entailment
def execution_errors(self): """ Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information """ if self.s...
Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information
entailment
def maybe_split_groups(self, max_groups): """ Check if group lists in add/remove directives should be split and split them if needed :param max_groups: Max group list size :return: True if at least one command was split, False if none were split """ split_commands = [] ...
Check if group lists in add/remove directives should be split and split them if needed :param max_groups: Max group list size :return: True if at least one command was split, False if none were split
entailment
def reload(self): """ Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None """ self._results = [] self._next_item_index = 0 self._next_page_index = 0 self._last_page_se...
Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None
entailment
def _next_page(self): """ Fetch the next page of the query. """ if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self...
Fetch the next page of the query.
entailment
def all_results(self): """ Eagerly fetch all the results. This can be called after already doing some amount of iteration, and it will return all the previously-iterated results as well as any results that weren't yet iterated. :return: a list of all the results. """ ...
Eagerly fetch all the results. This can be called after already doing some amount of iteration, and it will return all the previously-iterated results as well as any results that weren't yet iterated. :return: a list of all the results.
entailment
def _fetch_result(self): """ Fetch the queried object. """ self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
Fetch the queried object.
entailment
def create(self, first_name=None, last_name=None, country=None, email=None, on_conflict=IfAlreadyExistsOptions.ignoreIfAlreadyExists): """ Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because we retr...
Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because we retry create calls if they time out, the default conflict handling for creation is to ignore the create call if the user already exists (possibly from an earlier call...
entailment
def update(self, email=None, username=None, first_name=None, last_name=None, country=None): """ Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param fir...
Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param first_name: new first name for this user :param last_name: new last name for this user :param count...
entailment
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the u...
Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the user should be added to :param all_groups: a boolean meaning add to all (don't specify...
entailment
def remove_from_groups(self, groups=None, all_groups=False, group_type=None): """ Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type ...
Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return...
entailment
def add_role(self, groups=None, role_type=RoleTypes.admin): """ Make user have a role (typically PLC admin) with respect to some PLC groups. :param groups: list of group names the user should have this role for :param role_type: the role (defaults to "admin") :return: the User, s...
Make user have a role (typically PLC admin) with respect to some PLC groups. :param groups: list of group names the user should have this role for :param role_type: the role (defaults to "admin") :return: the User, so you can do User(...).add_role(...).add_to_groups(...)
entailment
def remove_role(self, groups=None, role_type=RoleTypes.admin): """ Remove user from a role (typically admin) of some groups. :param groups: list of group names the user should NOT have this role for :param role_type: the type of role (defaults to "admin") :return: the User, so yo...
Remove user from a role (typically admin) of some groups. :param groups: list of group names the user should NOT have this role for :param role_type: the type of role (defaults to "admin") :return: the User, so you can do User(...).remove_role(...).remove_from_groups(...)
entailment
def remove_from_organization(self, delete_account=False): """ Remove a user from the organization's list of visible users. Optionally also delete the account. Deleting the account can only be done if the organization owns the account's domain. :param delete_account: Whether to delete th...
Remove a user from the organization's list of visible users. Optionally also delete the account. Deleting the account can only be done if the organization owns the account's domain. :param delete_account: Whether to delete the account after removing from the organization (default false) :return...
entailment
def delete_account(self): """ Delete a user's account. Deleting the user's account can only be done if the user's domain is controlled by the authorized organization, and removing the account will also remove the user from all organizations with access to that domain. :return: No...
Delete a user's account. Deleting the user's account can only be done if the user's domain is controlled by the authorized organization, and removing the account will also remove the user from all organizations with access to that domain. :return: None, because you cannot follow this command wit...
entailment
def _validate(cls, group_name): """ Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group """ if group_name and not cls._group_name_regex.match(group_name): r...
Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group
entailment
def add_to_products(self, products=None, all_products=False): """ Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify produc...
Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_produ...
entailment
def remove_from_products(self, products=None, all_products=False): """ Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from ...
Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from all (don't specify products in this case) :return: the Group, so you can do Gro...
entailment
def add_users(self, users=None): """ Add users (specified by email address) to this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to add to the group. :return: the Group, so you can ...
Add users (specified by email address) to this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to add to the group. :return: the Group, so you can do Group(...).add_users(...).add_to_products(...)
entailment
def remove_users(self, users=None): """ Remove users (specified by email address) from this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to remove from the group. :return: the Group...
Remove users (specified by email address) from this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to remove from the group. :return: the Group, so you can do Group(...).remove_users(...).add_to_prod...
entailment
def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """ assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics.
entailment
def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
Smooth scaling using MMX or SSE extensions if available
entailment
def identity(self, surface): """ Fast scale operation that does not sample the results """ return self._pygame.transform.scale(surface, self._output_size)
Fast scale operation that does not sample the results
entailment
def led_matrix(self, surface): """ Transforms the input surface into an LED matrix (1 pixel = 1 LED) """ scale = self._led_on.get_width() w, h = self._input_size pix = self._pygame.PixelArray(surface) img = self._pygame.Surface((w * scale, h * scale)) for...
Transforms the input surface into an LED matrix (1 pixel = 1 LED)
entailment
def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """ # Using list of snap points, convert RGB value to cube indexes r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)] # Simple colorcube transform return (r * 36) + (g * 6) + b + 16
Converts RGB values to the nearest equivalent xterm-256 color.
entailment
def to_surface(self, image, alpha=1.0): """ Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments. """ assert(0.0 <= alpha <= 1.0) if alpha < 1.0: im = image.co...
Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments.
entailment
def display(self, image): """ Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file. """ assert(image.size == self.size) self._last_image = image self._count += 1 filename = self._file_template.format(self._count) image = self.preprocess(image) ...
Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file.
entailment
def display(self, image): """ Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) surface = self...
Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF.
entailment
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) self._clock.tick(self._fps) self._pygame.event.pump() ...
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
entailment
def _char_density(self, c, font=ImageFont.load_default()): """ Count the number of black pixels in a rendered character. """ image = Image.new('1', font.getsize(c), color=255) draw = ImageDraw.Draw(image) draw.text((0, 0), c, fill="white", font=font) return collec...
Count the number of black pixels in a rendered character.
entailment
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ # Characters aren't square, so scale the output by the aspect ratio of a charater height = int(height * self._char_width / float(self._char_height)) image = image.resize...
Return an iterator that produces the ascii art.
entailment
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = ...
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art.
entailment
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") pixels = list(image.getdata()) for y in range(0, height - 1, 2): for x in range(width)...
Return an iterator that produces the ascii art.
entailment
def _CSI(self, cmd): """ Control sequence introducer """ sys.stdout.write('\x1b[') sys.stdout.write(cmd)
Control sequence introducer
entailment
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes...
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks.
entailment
def chunk_sequence(sequence, chunk_length): """Yield successive n-sized chunks from l.""" for index in range(0, len(sequence), chunk_length): yield sequence[index:index + chunk_length]
Yield successive n-sized chunks from l.
entailment
def _filter_invalid_routes(routes, board, railroad): """ Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct...
Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct exit path This fltering after the fact keeps the path findi...
entailment
def find(path, level=None, message=None, time_lower=None, time_upper=None, case_sensitive=False): # pragma: no cover """ Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志 """ if level: level = level.upper() # level name has...
Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志
entailment
def get_logger_by_name(name=None, rand_name=False, charset=Charset.HEX): """ Get a logger by name. :param name: None / str, logger name. :param rand_name: if True, ``name`` will be ignored, a random name will be used. """ if rand_name: name = rand_str(charset) logger = logging.getLo...
Get a logger by name. :param name: None / str, logger name. :param rand_name: if True, ``name`` will be ignored, a random name will be used.
entailment
def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
invoke ``self.logger.debug``
entailment
def info(self, msg, indent=0, **kwargs): """invoke ``self.info.debug``""" return self.logger.info(self._indent(msg, indent), **kwargs)
invoke ``self.info.debug``
entailment
def warning(self, msg, indent=0, **kwargs): """invoke ``self.logger.warning``""" return self.logger.warning(self._indent(msg, indent), **kwargs)
invoke ``self.logger.warning``
entailment
def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``""" return self.logger.error(self._indent(msg, indent), **kwargs)
invoke ``self.logger.error``
entailment
def critical(self, msg, indent=0, **kwargs): """invoke ``self.logger.critical``""" return self.logger.critical(self._indent(msg, indent), **kwargs)
invoke ``self.logger.critical``
entailment
def show(self, msg, indent=0, style="", **kwargs): """ Print message to console, indent format may apply. """ if self.enable_verbose: new_msg = self.MessageTemplate.with_style.format( indent=self.tab * indent, style=style, msg=m...
Print message to console, indent format may apply.
entailment
def remove_all_handler(self): """ Unlink the file handler association. """ for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) self._handler_cache.append(handler)
Unlink the file handler association.
entailment
def recover_all_handler(self): """ Relink the file handler association you just removed. """ for handler in self._handler_cache: self.logger.addHandler(handler) self._handler_cache = list()
Relink the file handler association you just removed.
entailment
def from_protobuf(cls, proto: LinkItemProto) -> LinkItem: """ Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises Va...
Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises ValueError: name of LinkItem does not exist inside the protobuf or is empty
entailment
def to_protobuf(self) -> LinkItemProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto """ result = LinkItemProto() result.name = self._name result.time.CopyFrom(datetime_to_timestamp(sel...
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
entailment
def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """ ltfh = FileHandler(fname) self._log.addHandler(ltfh)
Adds a handler to save to a file. Includes debug stuff.
entailment
def delete_dir_rec(path: Path): """ Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path """ if not path.exists() or not path.is_dir(): return for sub in path.iterdir(): if sub.is_dir(): delete_dir_rec(sub) else: ...
Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path
entailment
def create_dir_rec(path: Path): """ Create a folder recursive. :param path: path :type path: ~pathlib.Path """ if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
Create a folder recursive. :param path: path :type path: ~pathlib.Path
entailment
def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp """ protime = Timestamp() protime.FromDatetime(time) ...
Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp
entailment
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] """ for trigger, entry_point in plugins.items(): try: p...
Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint]
entailment
def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2): """ Determines whether two windows overlap """ return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and yl2 < yl1+ny1 and yl2+ny2 > yl1)
Determines whether two windows overlap
entailment
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ ...
Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename
entailment
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_dat...
Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format.
entailment
def createJSON(g, full=True): """ Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals """ data = dict() if 'gps_attached' not in g.cpars: data['gps_attached'] = 1 else: data['gps...
Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals
entailment
def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals """ if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers ar...
Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals
entailment
def execCommand(g, command, timeout=10): """ Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : s...
Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : starts a run stop : stops a run abort ...
entailment
def isRunActive(g): """ Polls the data server to see if a run is active """ if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: ...
Polls the data server to see if a run is active
entailment
def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO...
Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it.
entailment
def getRunNumber(g): """ Polls the data server to find the current run number. Throws exceptions if it can't determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'summary' response = url...
Polls the data server to find the current run number. Throws exceptions if it can't determine it.
entailment
def checkSimbad(g, target, maxobj=5, timeout=5): """ Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or raises an exception if it times out """ url = 'http://simbad.u-strasbg.fr/simbad/sim-script' q = 'set limit ' + str(maxobj) + \ '...
Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or raises an exception if it times out
entailment
def run(self): """ Version of run that traps Exceptions and stores them in the fifo """ try: threading.Thread.run(self) except Exception: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0][:-1] tback ...
Version of run that traps Exceptions and stores them in the fifo
entailment
def rand_str(charset, length=32): """ Generate random string. """ return "".join([random.choice(charset) for _ in range(length)])
Generate random string.
entailment
def get_root(w): """ Simple method to access root for a widget """ next_level = w while next_level.master: next_level = next_level.master return next_level
Simple method to access root for a widget
entailment
def addStyle(w): """ Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style """ # access global container in root widget root = get_root(w) g = root.globals fsize = g.cpars['font_size'] family = g.cpars['font_family'] ...
Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style
entailment
def init(main_dir: Path, logfile_path: Path, log_level: str): """ Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str ...
Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str
entailment
def download_from_plugin(plugin: APlugin): """ Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9....
Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9. write new savestate :param plugin: plugin :ty...
entailment
def run(plugin_name: str, options: List[str] = None) -> PluginState: """ Run a plugin so use the download routine and clean up after. :param plugin_name: name of plugin :type plugin_name: str :param options: parameters which will be send to the plugin initialization :type options: List[str] ...
Run a plugin so use the download routine and clean up after. :param plugin_name: name of plugin :type plugin_name: str :param options: parameters which will be send to the plugin initialization :type options: List[str] :return: success :rtype: ~unidown.plugin.plugin_state.PluginState
entailment
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAI...
Check for app updates and print/log them.
entailment
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYP...
Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version
entailment
def setupNodding(self): """ Setup Nodding for GTC """ g = get_root(self).globals if not self.nod(): # re-enable clear mode box if not drift if not self.isDrift(): self.clear.enable() # clear existing nod pattern se...
Setup Nodding for GTC
entailment
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.a...
Encodes current parameters to JSON compatible dictionary
entailment
def loadJSON(self, json_string): """ Loads in an application saved in JSON format. """ g = get_root(self).globals data = json.loads(json_string)['appdata'] # first set the parameters which change regardless of mode # number of exposures numexp = data.get('...
Loads in an application saved in JSON format.
entailment
def check(self, *args): """ Callback to check validity of instrument parameters. Performs the following tasks: - spots and flags overlapping windows or null window parameters - flags windows with invalid dimensions given the binning parameter - sets the corre...
Callback to check validity of instrument parameters. Performs the following tasks: - spots and flags overlapping windows or null window parameters - flags windows with invalid dimensions given the binning parameter - sets the correct number of enabled windows - d...
entailment
def freeze(self): """ Freeze all settings so they cannot be altered """ self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.di...
Freeze all settings so they cannot be altered
entailment
def unfreeze(self): """ Reverse of freeze """ self.app.enable() self.clear.enable() self.nod.enable() self.led.enable() self.dummy.enable() self.readSpeed.enable() self.expose.enable() self.number.enable() self.wframe.enable...
Reverse of freeze
entailment
def getRtplotWins(self): """" Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup...
Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup. Note that we have to take care here ...
entailment
def timing(self): """ Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per ...
Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per frame (seconds) cycleTime : sa...
entailment
def loadJSON(self, json_string): """ Sets the values of the run parameters given an JSON string """ g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: ...
Sets the values of the run parameters given an JSON string
entailment
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ g = get_root(self).globals dtype = g.observe.rtype() if dtype == 'bias': target = 'BIAS' elif dtype == 'flat': target = 'FLAT' elif dtype == 'dark'...
Encodes current parameters to JSON compatible dictionary
entailment
def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False. """ ok = True msg = '' g = get_root(self).globals dtype = g.observe.rtyp...
Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False.
entailment
def freeze(self): """ Freeze all settings so that they can't be altered """ self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') ...
Freeze all settings so that they can't be altered
entailment
def unfreeze(self): """ Unfreeze all settings so that they can be altered """ g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob...
Unfreeze all settings so that they can be altered
entailment