text
stringlengths
81
112k
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...
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...
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...
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(...) def add_role(self, grou...
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(...) def remove_role(self, ...
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...
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...
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 def _validate(cls, group_name): """ Validates the group name Input values must be strings (standard or unicode). Throws Ar...
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...
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...
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(...) de...
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...
Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """ assert(self._scale == 2) re...
Smooth scaling using MMX or SSE extensions if available def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
Fast scale operation that does not sample the results def identity(self, surface): """ Fast scale operation that does not sample the results """ return self._pygame.transform.scale(surface, self._output_size)
Transforms the input surface into an LED matrix (1 pixel = 1 LED) 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) ...
Converts RGB values to the nearest equivalent xterm-256 color. 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)] # Si...
Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments. def to_surface(self, image, alpha=1.0): """ Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according...
Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file. 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_te...
Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. def display(self, image): """ Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. """ ...
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface. 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) ...
Count the number of black pixels in a rendered character. 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.tex...
Return an iterator that produces the ascii art. 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...
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art. 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 s...
Return an iterator that produces the ascii art. 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, ...
Control sequence introducer def _CSI(self, cmd): """ Control sequence introducer """ sys.stdout.write('\x1b[') sys.stdout.write(cmd)
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks. 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 ...
Yield successive n-sized chunks from l. 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]
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...
Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志 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...
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. 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_nam...
invoke ``self.logger.debug`` def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
invoke ``self.info.debug`` def info(self, msg, indent=0, **kwargs): """invoke ``self.info.debug``""" return self.logger.info(self._indent(msg, indent), **kwargs)
invoke ``self.logger.warning`` def warning(self, msg, indent=0, **kwargs): """invoke ``self.logger.warning``""" return self.logger.warning(self._indent(msg, indent), **kwargs)
invoke ``self.logger.error`` def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``""" return self.logger.error(self._indent(msg, indent), **kwargs)
invoke ``self.logger.critical`` def critical(self, msg, indent=0, **kwargs): """invoke ``self.logger.critical``""" return self.logger.critical(self._indent(msg, indent), **kwargs)
Print message to console, indent format may apply. 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...
Unlink the file handler association. 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)
Relink the file handler association you just removed. 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()
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 def...
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto def to_protobuf(self) -> LinkItemProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto ...
Adds a handler to save to a file. Includes debug stuff. def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """ ltfh = FileHandler(fname) self._log.addHandler(ltfh)
Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path 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...
Create a folder recursive. :param path: path :type path: ~pathlib.Path 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)
Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :...
Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param...
Determines whether two windows overlap 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)
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 def saveJSON(g, data, backup=False): """ Saves th...
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. def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.global...
Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals def createJSON(g, full=True): """ Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Contai...
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 def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments ...
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 ...
Polls the data server to see if a run is active 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(...
Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. 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 DriverEr...
Polls the data server to find the current run number. Throws exceptions if it can't determine it. 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('getRunNum...
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 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 ra...
Version of run that traps Exceptions and stores them in the fifo 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() ...
Generate random string. def rand_str(charset, length=32): """ Generate random string. """ return "".join([random.choice(charset) for _ in range(length)])
Simple method to access root for a widget 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
Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style def addStyle(w): """ Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style """ # access global container in r...
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 def init(main_dir: Path, logfile_path: Path, log_level: str): """ Ini...
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...
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 def run(p...
Check for app updates and print/log them. 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 ...
Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_re...
Setup Nodding for GTC 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...
Encodes current parameters to JSON compatible dictionary def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( ...
Loads in an application saved in JSON format. 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 # ...
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...
Freeze all settings so they cannot be altered 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() ...
Reverse of freeze 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() ...
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 ...
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...
Sets the values of the run parameters given an JSON string 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 ...
Encodes current parameters to JSON compatible dictionary 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'...
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. def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the ...
Freeze all settings so that they can't be altered 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') ...
Unfreeze all settings so that they can be altered 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...
Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recursion since update gets called from ipars. def checkUpdate(self, *args): """ Updates values after first checking instrument parameters are OK. This is no...
Checks values def check(self): """ Checks values """ status = True g = get_root(self).globals if self.mag.ok(): self.mag.config(bg=g.COL['main']) else: self.mag.config(bg=g.COL['warn']) status = False if self.airmass.o...
Updates values. You should run a check on the instrument and target parameters before calling this. def update(self, *args): """ Updates values. You should run a check on the instrument and target parameters before calling this. """ g = get_root(self).globals exp...
Computes counts per pixel, total counts, sky counts etc given current magnitude, seeing etc. You should run a check on the instrument parameters before calling this. expTime : exposure time per frame (seconds) cycleTime : sampling, cadence (seconds) ap_scale : apertur...
Disable the button, if in non-expert mode. def disable(self): """ Disable the button, if in non-expert mode. """ w.ActButton.disable(self) g = get_root(self).globals if self._expert: self.config(bg=g.COL['start']) else: self.config(bg=g.CO...
Turns on 'expert' status whereby the button is always enabled, regardless of its activity status. def setExpert(self): """ Turns on 'expert' status whereby the button is always enabled, regardless of its activity status. """ w.ActButton.setExpert(self) g = get_ro...
Carries out action associated with start button def act(self): """ Carries out action associated with start button """ g = get_root(self).globals # check binning against overscan msg = """ HiperCAM has an o/scan of 50 pixels. Your binning does not fit int...
Carries out the action associated with the Load button def act(self): """ Carries out the action associated with the Load button """ g = get_root(self).globals fname = filedialog.askopenfilename( defaultextension='.json', filetypes=[('json files', '.json'...
Carries out the action associated with the Save button def act(self): """ Carries out the action associated with the Save button """ g = get_root(self).globals g.clog.info('\nSaving current application to disk') # check instrument parameters if not g.ipars.check...
Carries out the action associated with the Unfreeze button def act(self): """ Carries out the action associated with the Unfreeze button """ g = get_root(self).globals g.ipars.unfreeze() g.rpars.unfreeze() g.observe.load.enable() self.disable()
Set expert level def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # now set whether buttons are permanently enabled or not if level == 0 or level == 1: self.load.setNonExpert() ...
Main entry point for consumer metaclasses. Usage:: from py_meta_utils import (AbstractMetaOption, McsArgs, MetaOptionsFactory, process_factory_meta_options) class YourMetaOptionsFactory(MetaOptionsFactory): _options = [AbstractMetaOption] class...
Acts just like ``getattr`` would on a constructed class object, except this operates on the pre-construction class dictionary and base classes. In other words, first we look for the attribute in the class dictionary, and then we search all the base classes (in method resolution order), finally returning the...
Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ ...
Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name. def qualname(self) -> str: """ Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name. """ if self.module: ...
Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run) def is_abstract(self) -> bool: """ Whether or not the class-under-construction was declared as abstract (**NOTE:** this property...
Returns the value for ``self.name`` given the class-under-construction's class ``Meta``. If it's not found there, and ``self.inherit == True`` and there is a base class that has a class ``Meta``, use that value, otherwise ``self.default``. :param Meta: the class ``Meta`` (if any) from the class...
Returns a list of :class:`MetaOption` instances that this factory supports. def _get_meta_options(self) -> List[MetaOption]: """ Returns a list of :class:`MetaOption` instances that this factory supports. """ return [option if isinstance(option, MetaOption) else option() ...
Where the magic happens. Takes one parameter, the :class:`McsArgs` of the class-under-construction, and processes the declared ``class Meta`` from it (if any). We fill ourself with the declared meta options' name/value pairs, give the declared meta options a chance to also contribute to the clas...
Iterate over our supported meta options, and set attributes on the factory instance (self) for each meta option's name/value. Raises ``TypeError`` if we discover any unsupported meta options on the class-under-construction's ``class Meta``. def _fill_from_meta(self, Meta: Type[object], base_cla...
Get a reference to a remote object using CORBA def get_object(self, binding_name, cls): """ Get a reference to a remote object using CORBA """ return self._state.get_object(self, binding_name, cls)
Get a reference to a remote object using CORBA def get_object(conn, binding_name, object_cls): """ Get a reference to a remote object using CORBA """ try: obj = conn.rootContext.resolve(binding_name) narrowed = obj._narrow(object_cls) except CORBA.TRANSIE...