code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _handle_class_instance(self, klass): if (klass in self.blacklisted_plugins or not self.instantiate_classes or klass == IPlugin): return elif self.unique_instances and self._unique_class(klass): self.plugins.append(klass()) elif not self.unique_instances: self.plugins.append(klass())
handles class instances. If a class is blacklisted, returns. If uniuqe_instances is True and the class is unique, instantiates the class and adds the new object to plugins. If not unique_instances, creates and adds new instance to plugin state
def _unique_class(self, cls): return not any(isinstance(obj, cls) for obj in self.plugins)
internal method to check if any of the plugins are instances of a given cls
def add_blacklisted_plugins(self, plugins): plugins = util.return_list(plugins) self.blacklisted_plugins.extend(plugins)
add blacklisted plugins. `plugins` may be a single object or iterable.
def set_blacklisted_plugins(self, plugins): plugins = util.return_list(plugins) self.blacklisted_plugins = plugins
sets blacklisted plugins. `plugins` may be a single object or iterable.
def load_modules(self, filepaths): # removes filepaths from processed if they are not in sys.modules self._update_loaded_modules() filepaths = util.return_set(filepaths) modules = [] for filepath in filepaths: filepath = self._clean_filepath(filepath) # check to see if already processed and move onto next if so if self._processed_filepath(filepath): continue module_name = util.get_module_name(filepath) plugin_module_name = util.create_unique_module_name(module_name) try: module = load_source(plugin_module_name, filepath) # Catch all exceptions b/c loader will return errors # within the code itself, such as Syntax, NameErrors, etc. except Exception: exc_info = sys.exc_info() self._log.error(msg=self._error_string.format(filepath), exc_info=exc_info) continue self.loaded_modules.add(module.__name__) modules.append(module) self.processed_filepaths[module.__name__] = filepath return modules
Loads the modules from their `filepaths`. A filepath may be a directory filepath if there is an `__init__.py` file in the directory. If a filepath errors, the exception will be caught and logged in the logger. Returns a list of modules.
def collect_plugins(self, modules=None): if modules is None: modules = self.get_loaded_modules() else: modules = util.return_list(modules) plugins = [] for module in modules: module_plugins = [(item[1], item[0]) for item in inspect.getmembers(module) if item[1] and item[0] != '__builtins__'] module_plugins, names = zip(*module_plugins) module_plugins = self._filter_modules(module_plugins, names) plugins.extend(module_plugins) return plugins
Collects all the plugins from `modules`. If modules is None, collects the plugins from the loaded modules. All plugins are passed through the module filters, if any are any, and returned as a list.
def set_module_plugin_filters(self, module_plugin_filters): module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters = module_plugin_filters
Sets the internal module filters to `module_plugin_filters` `module_plugin_filters` may be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names.
def add_module_plugin_filters(self, module_plugin_filters): module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters.extend(module_plugin_filters)
Adds `module_plugin_filters` to the internal module filters. May be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names.
def _get_modules(self, names): loaded_modules = [] for name in names: loaded_modules.append(sys.modules[name]) return loaded_modules
An internal method that gets the `names` from sys.modules and returns them as a list
def add_to_loaded_modules(self, modules): modules = util.return_set(modules) for module in modules: if not isinstance(module, str): module = module.__name__ self.loaded_modules.add(module)
Manually add in `modules` to be tracked by the module manager. `modules` may be a single object or an iterable.
def _filter_modules(self, plugins, names): if self.module_plugin_filters: # check to make sure the number of plugins isn't changing original_length_plugins = len(plugins) module_plugins = set() for module_filter in self.module_plugin_filters: module_plugins.update(module_filter(plugins, names)) if len(plugins) < original_length_plugins: warning = """Module Filter removing plugins from original data member! Suggest creating a new list in each module filter and returning new list instead of modifying the original data member so subsequent module filters can have access to all the possible plugins.\n {}""" self._log.info(warning.format(module_filter)) plugins = module_plugins return plugins
Internal helper method to parse all of the plugins and names through each of the module filters
def _clean_filepath(self, filepath): if (os.path.isdir(filepath) and os.path.isfile(os.path.join(filepath, '__init__.py'))): filepath = os.path.join(filepath, '__init__.py') if (not filepath.endswith('.py') and os.path.isfile(filepath + '.py')): filepath += '.py' return filepath
processes the filepath by checking if it is a directory or not and adding `.py` if not present.
def _processed_filepath(self, filepath): processed = False if filepath in self.processed_filepaths.values(): processed = True return processed
checks to see if the filepath has already been processed
def _update_loaded_modules(self): system_modules = sys.modules.keys() for module in list(self.loaded_modules): if module not in system_modules: self.processed_filepaths.pop(module) self.loaded_modules.remove(module)
Updates the loaded modules by checking if they are still in sys.modules
def clear(self): self.axes.cla() self.conf.ntrace = 0 self.conf.xlabel = '' self.conf.ylabel = '' self.conf.title = ''
clear plot
def unzoom_all(self, event=None): if len(self.conf.zoom_lims) > 0: self.conf.zoom_lims = [self.conf.zoom_lims[0]] self.unzoom(event)
zoom out full data range
def unzoom(self, event=None, set_bounds=True): lims = None if len(self.conf.zoom_lims) > 1: lims = self.conf.zoom_lims.pop() ax = self.axes # print 'base unzoom ', lims, set_bounds if lims is None: # auto scale self.conf.zoom_lims = [None] xmin, xmax, ymin, ymax = self.data_range ax.set_xlim((xmin, xmax), emit=True) ax.set_ylim((ymin, ymax), emit=True) if set_bounds: ax.update_datalim(((xmin, ymin), (xmax, ymax))) ax.set_xbound(ax.xaxis.get_major_locator( ).view_limits(xmin, xmax)) ax.set_ybound(ax.yaxis.get_major_locator( ).view_limits(ymin, ymax)) else: self.set_viewlimits() self.canvas.draw()
zoom out 1 level, or to full data range
def get_right_axes(self): "create, if needed, and return right-hand y axes" if len(self.fig.get_axes()) < 2: ax = self.axes.twinx() return self.fig.get_axes()[1f get_right_axes(self): "create, if needed, and return right-hand y axes" if len(self.fig.get_axes()) < 2: ax = self.axes.twinx() return self.fig.get_axes()[1]
create, if needed, and return right-hand y axes
def set_title(self, s, delay_draw=False): "set plot title" self.conf.relabel(title=s, delay_draw=delay_drawf set_title(self, s, delay_draw=False): "set plot title" self.conf.relabel(title=s, delay_draw=delay_draw)
set plot title
def set_xlabel(self, s, delay_draw=False): "set plot xlabel" self.conf.relabel(xlabel=s, delay_draw=delay_drawf set_xlabel(self, s, delay_draw=False): "set plot xlabel" self.conf.relabel(xlabel=s, delay_draw=delay_draw)
set plot xlabel
def set_ylabel(self, s, delay_draw=False): "set plot ylabel" self.conf.relabel(ylabel=s, delay_draw=delay_drawf set_ylabel(self, s, delay_draw=False): "set plot ylabel" self.conf.relabel(ylabel=s, delay_draw=delay_draw)
set plot ylabel
def set_y2label(self, s, delay_draw=False): "set plot ylabel" self.conf.relabel(y2label=s, delay_draw=delay_drawf set_y2label(self, s, delay_draw=False): "set plot ylabel" self.conf.relabel(y2label=s, delay_draw=delay_draw)
set plot ylabel
def save_figure(self, event=None, transparent=False, dpi=600): file_choices = "PNG (*.png)|*.png|SVG (*.svg)|*.svg|PDF (*.pdf)|*.pdf" try: ofile = self.conf.title.strip() except: ofile = 'Image' if len(ofile) > 64: ofile = ofile[:63].strip() if len(ofile) < 1: ofile = 'plot' for c in ' :";|/\\': # " ofile = ofile.replace(c, '_') ofile = ofile + '.png' orig_dir = os.path.abspath(os.curdir) dlg = wx.FileDialog(self, message='Save Plot Figure as...', defaultDir = os.getcwd(), defaultFile=ofile, wildcard=file_choices, style=wx.FD_SAVE|wx.FD_CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if hasattr(self, 'fig'): self.fig.savefig(path, transparent=transparent, dpi=dpi) else: self.canvas.print_figure(path, transparent=transparent, dpi=dpi) if (path.find(self.launch_dir) == 0): path = path[len(self.launch_dir)+1:] self.write_message('Saved plot to %s' % path) os.chdir(orig_dir)
save figure image to file
def onLeftDown(self, event=None): if event is None: return self.cursor_mode_action('leftdown', event=event) self.ForwardEvent(event=event.guiEvent)
left button down: report x,y coords, start zooming mode
def onLeftUp(self, event=None): if event is None: return self.cursor_mode_action('leftup', event=event) self.canvas.draw_idle() self.canvas.draw() self.ForwardEvent(event=event.guiEvent)
left button up
def ForwardEvent(self, event=None): if event is not None: event.Skip() if self.HasCapture(): try: self.ReleaseMouse() except: pass
finish wx event, forward it to other wx objects
def onRightDown(self, event=None): if event is None: return # note that the matplotlib event location have to be converted if event.inaxes is not None and self.popup_menu is not None: pos = event.guiEvent.GetPosition() wx.CallAfter(self.PopupMenu, self.popup_menu, pos) self.cursor_mode_action('rightdown', event=event) self.ForwardEvent(event=event.guiEvent)
right button down: show pop-up
def onRightUp(self, event=None): if event is None: return self.cursor_mode_action('rightup', event=event) self.ForwardEvent(event=event.guiEvent)
right button up: put back to cursor mode
def __date_format(self, x): if x < 1: x = 1 span = self.axes.xaxis.get_view_interval() tmin = max(1.0, span[0]) tmax = max(2.0, span[1]) tmin = time.mktime(dates.num2date(tmin).timetuple()) tmax = time.mktime(dates.num2date(tmax).timetuple()) nhours = (tmax - tmin)/3600.0 fmt = "%m/%d" if nhours < 0.1: fmt = "%H:%M\n%Ssec" elif nhours < 4: fmt = "%m/%d\n%H:%M" elif nhours < 24*8: fmt = "%m/%d\n%H:%M" try: return time.strftime(fmt, dates.num2date(x).timetuple()) except: return "?"
formatter for date x-data. primitive, and probably needs improvement, following matplotlib's date methods.
def xformatter(self, x, pos): " x-axis formatter " if self.use_dates: return self.__date_format(x) else: return self.__format(x, type='x'f xformatter(self, x, pos): " x-axis formatter " if self.use_dates: return self.__date_format(x) else: return self.__format(x, type='x')
x-axis formatter
def __onKeyEvent(self, event=None): if event is None: return key = event.guiEvent.GetKeyCode() if (key < wx.WXK_SPACE or key > 255): return ckey = chr(key) mod = event.guiEvent.ControlDown() if self.is_macosx: mod = event.guiEvent.MetaDown() if mod: if ckey == 'C': self.canvas.Copy_to_Clipboard(event) elif ckey == 'S': self.save_figure(event) elif ckey == 'K': self.configure(event) elif ckey == 'Z': self.unzoom(event) elif ckey == 'P': self.canvas.printer.Print(event)
handles key events on canvas
def __onMouseButtonEvent(self, event=None): if event is None: return button = event.button or 1 handlers = {(1, 'button_press_event'): self.onLeftDown, (1, 'button_release_event'): self.onLeftUp, (3, 'button_press_event'): self.onRightDown, } # (3,'button_release_event'): self.onRightUp} handle_event = handlers.get((button, event.name), None) if hasattr(handle_event, '__call__'): handle_event(event) event.guiEvent.Skip()
general mouse press/release events. Here, event is a MplEvent from matplotlib. This routine just dispatches to the appropriate onLeftDown, onLeftUp, onRightDown, onRightUp.... methods.
def zoom_motion(self, event=None): try: x, y = event.x, event.y except: return self.report_motion(event=event) if self.zoom_ini is None: return ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini if event.xdata is not None: self.x_lastmove = event.xdata if event.ydata is not None: self.y_lastmove = event.ydata x0 = min(x, ini_x) ymax = max(y, ini_y) width = abs(x-ini_x) height = abs(y-ini_y) y0 = self.canvas.figure.bbox.height - ymax zdc = wx.ClientDC(self.canvas) zdc.SetLogicalFunction(wx.XOR) zdc.SetBrush(wx.TRANSPARENT_BRUSH) zdc.SetPen(wx.Pen('White', 2, wx.SOLID)) zdc.ResetBoundingBox() if not is_wxPhoenix: zdc.BeginDrawing() # erase previous box if self.rbbox is not None: zdc.DrawRectangle(*self.rbbox) self.rbbox = (x0, y0, width, height) zdc.DrawRectangle(*self.rbbox) if not is_wxPhoenix: zdc.EndDrawing()
motion event handler for zoom mode
def zoom_leftdown(self, event=None): self.x_lastmove, self.y_lastmove = None, None self.zoom_ini = (event.x, event.y, event.xdata, event.ydata) self.report_leftdown(event=event)
leftdown event handler for zoom mode
def lasso_leftdown(self, event=None): try: self.report_leftdown(event=event) except: return if event.inaxes: # set lasso color color='goldenrod' cmap = getattr(self.conf, 'cmap', None) if isinstance(cmap, dict): cmap = cmap['int'] try: if cmap is not None: rgb = (int(i*255)^255 for i in cmap._lut[0][:3]) color = '#%02x%02x%02x' % tuple(rgb) except: pass self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lassoHandler) self.lasso.line.set_color(color)
leftdown event handler for lasso mode
def rename(self, new_folder_name): headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id payload = '{ "DisplayName": "' + new_folder_name + '"}' r = requests.patch(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
Renames the Folder to the provided name. Args: new_folder_name: A string of the replacement name. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: A new Folder representing the folder with the new name on Outlook.
def get_subfolders(self): headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' r = requests.get(endpoint, headers=headers) if check_response(r): return self._json_to_folders(self.account, r.json())
Retrieve all child Folders inside of this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`]
def delete(self): headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id r = requests.delete(endpoint, headers=headers) check_response(r)
Deletes this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token.
def move_into(self, destination_folder): # type: (Folder) -> None headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/move' payload = '{ "DestinationId": "' + destination_folder.id + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
Move the Folder into a different folder. This makes the Folder provided a child folder of the destination_folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Args: destination_folder: A :class:`Folder <pyOutlook.core.folder.Folder>` that should become the parent Returns: A new :class:`Folder <pyOutlook.core.folder.Folder>` that is now inside of the destination_folder.
def create_child_folder(self, folder_name): headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' payload = '{ "DisplayName": "' + folder_name + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
Creates a child folder within the Folder it is called from and returns the new Folder object. Args: folder_name: The name of the folder to create Returns: :class:`Folder <pyOutlook.core.folder.Folder>`
def messages(self): headers = self.headers r = requests.get('https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/messages', headers=headers) check_response(r) return Message._json_to_messages(self.account, r.json())
Retrieves the messages in this Folder, returning a list of :class:`Messages <pyOutlook.core.message.Message>`.
def gformat(val, length=11): try: expon = int(log10(abs(val))) except (OverflowError, ValueError): expon = 0 length = max(length, 7) form = 'e' prec = length - 7 if abs(expon) > 99: prec -= 1 elif ((expon > 0 and expon < (prec+4)) or (expon <= 0 and -expon < (prec-1))): form = 'f' prec += 4 if expon > 0: prec -= expon fmt = '{0: %i.%i%s}' % (length, prec, form) return fmt.format(val)
Format a number with '%g'-like format, except that a) the length of the output string will be the requested length. b) positive numbers will have a leading blank. b) the precision will be as high as possible. c) trailing zeros will not be trimmed. The precision will typically be length-7. Arguments --------- val value to be formatted length length of output string Returns ------- string of specified length. Notes ------ Positive values will have leading blank.
def pack(window, sizer, expand=1.1): "simple wxPython pack function" tsize = window.GetSize() msize = window.GetMinSize() window.SetSizer(sizer) sizer.Fit(window) nsize = (10*int(expand*(max(msize[0], tsize[0])/10)), 10*int(expand*(max(msize[1], tsize[1])/10.))) window.SetSize(nsizef pack(window, sizer, expand=1.1): "simple wxPython pack function" tsize = window.GetSize() msize = window.GetMinSize() window.SetSizer(sizer) sizer.Fit(window) nsize = (10*int(expand*(max(msize[0], tsize[0])/10)), 10*int(expand*(max(msize[1], tsize[1])/10.))) window.SetSize(nsize)
simple wxPython pack function
def MenuItem(parent, menu, label='', longtext='', action=None, default=True, **kws): item = menu.Append(-1, label, longtext, **kws) kind = item.GetKind() if kind == wx.ITEM_CHECK: item.Check(default) if callable(action): parent.Bind(wx.EVT_MENU, action, item) return item
Add Item to a Menu, with action m = Menu(parent, menu, label, longtext, action=None)
def Setup(self, event=None): if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() data.SetMarginTopLeft( (15, 15) ) data.SetMarginBottomRight( (15, 15) ) dlg = wx.PageSetupDialog(None, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() tl = data.GetMarginTopLeft() br = data.GetMarginBottomRight() self.printerData = wx.PrintData(data.GetPrintData()) dlg.Destroy()
set up figure for printing. Using the standard wx Printer Setup Dialog.
def Preview(self, title=None, event=None): if title is None: title = self.title if self.canvas is None: self.canvas = self.parent.canvas po1 = PrintoutWx(self.parent.canvas, title=title, width=self.pwidth, margin=self.pmargin) po2 = PrintoutWx(self.parent.canvas, title=title, width=self.pwidth, margin=self.pmargin) self.preview = wx.PrintPreview(po1, po2, self.printerData) if ((is_wxPhoenix and self.preview.IsOk()) or (not is_wxPhoenix and self.preview.Ok())): self.preview.SetZoom(85) frameInst= self.parent while not isinstance(frameInst, wx.Frame): frameInst= frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, "Preview") frame.Initialize() frame.SetSize((850, 650)) frame.Centre(wx.BOTH) frame.Show(True)
generate Print Preview with wx Print mechanism
def Print(self, title=None, event=None): pdd = wx.PrintDialogData() pdd.SetPrintData(self.printerData) pdd.SetToPage(1) printer = wx.Printer(pdd) if title is None: title = self.title printout = PrintoutWx(self.parent.canvas, title=title, width=self.pwidth, margin=self.pmargin) print_ok = printer.Print(self.parent, printout, True) if not print_ok and not printer.GetLastError() == wx.PRINTER_CANCELLED: wx.MessageBox("""There was a problem printing. Perhaps your current printer is not set correctly?""", "Printing", wx.OK) printout.Destroy()
Print figure using wx Print mechanism
def set_float(val): out = None if not val in (None, ''): try: out = float(val) except ValueError: return None if numpy.isnan(out): out = default return out
utility to set a floating value, useful for converting from strings
def SetAction(self, action, **kws): "set callback action" if hasattr(action,'__call__'): self.__action = Closure(action, **kwsf SetAction(self, action, **kws): "set callback action" if hasattr(action,'__call__'): self.__action = Closure(action, **kws)
set callback action
def __GetMark(self): " keep track of cursor position within text" try: self.__mark = min(wx.TextCtrl.GetSelection(self)[0], len(wx.TextCtrl.GetValue(self).strip())) except: self.__mark = f __GetMark(self): " keep track of cursor position within text" try: self.__mark = min(wx.TextCtrl.GetSelection(self)[0], len(wx.TextCtrl.GetValue(self).strip())) except: self.__mark = 0
keep track of cursor position within text
def __SetMark(self, mark=None): "set mark for later" if mark is None: mark = self.__mark self.SetSelection(mark, markf __SetMark(self, mark=None): "set mark for later" if mark is None: mark = self.__mark self.SetSelection(mark, mark)
set mark for later
def SetValue(self, value=None, act=True): " main method to set value " if value is None: value = wx.TextCtrl.GetValue(self).strip() self.__CheckValid(value) self.__GetMark() if value is not None: wx.TextCtrl.SetValue(self, self.format % set_float(value)) if self.is_valid and hasattr(self.__action, '__call__') and act: self.__action(value=self.__val) elif not self.is_valid and self.bell_on_invalid: wx.Bell() self.__SetMark(f SetValue(self, value=None, act=True): " main method to set value " if value is None: value = wx.TextCtrl.GetValue(self).strip() self.__CheckValid(value) self.__GetMark() if value is not None: wx.TextCtrl.SetValue(self, self.format % set_float(value)) if self.is_valid and hasattr(self.__action, '__call__') and act: self.__action(value=self.__val) elif not self.is_valid and self.bell_on_invalid: wx.Bell() self.__SetMark()
main method to set value
def OnChar(self, event): key = event.GetKeyCode() entry = wx.TextCtrl.GetValue(self).strip() pos = wx.TextCtrl.GetSelection(self) # really, the order here is important: # 1. return sends to ValidateEntry if key == wx.WXK_RETURN: if not self.is_valid: wx.TextCtrl.SetValue(self, self.format % set_float(self.__bound_val)) else: self.SetValue(entry) return # 2. other non-text characters are passed without change if (key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255): event.Skip() return # 3. check for multiple '.' and out of place '-' signs and ignore these # note that chr(key) will now work due to return at #2 has_minus = '-' in entry ckey = chr(key) if ((ckey == '.' and (self.__prec == 0 or '.' in entry) ) or (ckey == '-' and (has_minus or pos[0] != 0)) or (ckey != '-' and has_minus and pos[0] == 0)): return # 4. allow digits, but not other characters if chr(key) in self.__digits: event.Skip()
on Character event
def OnText(self, event=None): "text event" try: if event.GetString() != '': self.__CheckValid(event.GetString()) except: pass event.Skip(f OnText(self, event=None): "text event" try: if event.GetString() != '': self.__CheckValid(event.GetString()) except: pass event.Skip()
text event
def __CheckValid(self, value): "check for validity of value" val = self.__val self.is_valid = True try: val = set_float(value) if self.__min is not None and (val < self.__min): self.is_valid = False val = self.__min if self.__max is not None and (val > self.__max): self.is_valid = False val = self.__max except: self.is_valid = False self.__bound_val = self.__val = val fgcol, bgcol = self.fgcol_valid, self.bgcol_valid if not self.is_valid: fgcol, bgcol = self.fgcol_invalid, self.bgcol_invalid self.SetForegroundColour(fgcol) self.SetBackgroundColour(bgcol) self.Refresh(f __CheckValid(self, value): "check for validity of value" val = self.__val self.is_valid = True try: val = set_float(value) if self.__min is not None and (val < self.__min): self.is_valid = False val = self.__min if self.__max is not None and (val > self.__max): self.is_valid = False val = self.__max except: self.is_valid = False self.__bound_val = self.__val = val fgcol, bgcol = self.fgcol_valid, self.bgcol_valid if not self.is_valid: fgcol, bgcol = self.fgcol_invalid, self.bgcol_invalid self.SetForegroundColour(fgcol) self.SetBackgroundColour(bgcol) self.Refresh()
check for validity of value
def plot(self, xdata, ydata, side='left', title=None, xlabel=None, ylabel=None, y2label=None, use_dates=False, **kws): allaxes = self.fig.get_axes() if len(allaxes) > 1: for ax in allaxes[1:]: if ax in self.data_range: self.data_range.pop(ax) self.fig.delaxes(ax) self.data_range = {} self.conf.zoom_lims = [] self.conf.axes_traces = {} self.clear() axes = self.axes if side == 'right': axes = self.get_right_axes() self.conf.ntrace = 0 self.conf.yscale = 'linear' self.conf.user_limits[axes] = [None, None, None, None] if xlabel is not None: self.set_xlabel(xlabel, delay_draw=True) if ylabel is not None: self.set_ylabel(ylabel, delay_draw=True) if y2label is not None: self.set_y2label(y2label, delay_draw=True) if title is not None: self.set_title(title, delay_draw=True) if use_dates is not None: self.use_dates = use_dates return self.oplot(xdata, ydata, side=side, **kws)
plot (that is, create a new plot: clear, then oplot)
def plot_many(self, datalist, side='left', title=None, xlabel=None, ylabel=None, **kws): def unpack_tracedata(tdat, **kws): if (isinstance(tdat, dict) and 'xdata' in tdat and 'ydata' in tdat): xdata = tdat.pop('xdata') ydata = tdat.pop('ydata') out = kws out.update(tdat) elif isinstance(tdat, (list, tuple)): out = kws xdata = tdat[0] ydata = tdat[1] return (xdata, ydata, out) opts = dict(side=side, title=title, xlabel=xlabel, ylabel=ylabel, delay_draw=True) opts.update(kws) x0, y0, opts = unpack_tracedata(datalist[0], **opts) self.plot(x0, y0, **opts) for dat in datalist[1:]: x, y, opts = unpack_tracedata(dat, delay_draw=True) self.oplot(x, y, **opts) conf = self.conf if conf.show_legend: conf.draw_legend() conf.relabel() self.draw() self.canvas.Refresh()
plot many traces at once, taking a list of (x, y) pairs
def add_text(self, text, x, y, side='left', size=None, rotation=None, ha='left', va='center', family=None, **kws): axes = self.axes if side == 'right': axes = self.get_right_axes() dynamic_size = False if size is None: size = self.conf.legendfont.get_size() dynamic_size = True t = axes.text(x, y, text, ha=ha, va=va, size=size, rotation=rotation, family=family, **kws) self.conf.added_texts.append((dynamic_size, t)) self.draw()
add text at supplied x, y position
def add_arrow(self, x1, y1, x2, y2, side='left', shape='full', color='black', width=0.01, head_width=0.03, overhang=0, **kws): dx, dy = x2-x1, y2-y1 axes = self.axes if side == 'right': axes = self.get_right_axes() axes.arrow(x1, y1, dx, dy, shape=shape, length_includes_head=True, fc=color, edgecolor=color, width=width, head_width=head_width, overhang=overhang, **kws) self.draw()
add arrow supplied x, y position
def set_xylims(self, limits, axes=None, side='left'): "set user-defined limits and apply them" if axes is None: axes = self.axes if side == 'right': axes = self.get_right_axes() self.conf.user_limits[axes] = limits self.unzoom_all(f set_xylims(self, limits, axes=None, side='left'): "set user-defined limits and apply them" if axes is None: axes = self.axes if side == 'right': axes = self.get_right_axes() self.conf.user_limits[axes] = limits self.unzoom_all()
set user-defined limits and apply them
def clear(self): for ax in self.fig.get_axes(): ax.cla() self.conf.ntrace = 0 self.conf.xlabel = '' self.conf.ylabel = '' self.conf.y2label = '' self.conf.title = '' self.conf.data_save = {}
clear plot
def toggle_deriv(self, evt=None, value=None): "toggle derivative of data" if value is None: self.conf.data_deriv = not self.conf.data_deriv expr = self.conf.data_expr or '' if self.conf.data_deriv: expr = "deriv(%s)" % expr self.write_message("plotting %s" % expr, panel=0) self.conf.process_data(f toggle_deriv(self, evt=None, value=None): "toggle derivative of data" if value is None: self.conf.data_deriv = not self.conf.data_deriv expr = self.conf.data_expr or '' if self.conf.data_deriv: expr = "deriv(%s)" % expr self.write_message("plotting %s" % expr, panel=0) self.conf.process_data()
toggle derivative of data
def set_logscale(self, event=None, xscale='linear', yscale='linear', delay_draw=False): "set log or linear scale for x, y axis" self.conf.set_logscale(xscale=xscale, yscale=yscale, delay_draw=delay_drawf set_logscale(self, event=None, xscale='linear', yscale='linear', delay_draw=False): "set log or linear scale for x, y axis" self.conf.set_logscale(xscale=xscale, yscale=yscale, delay_draw=delay_draw)
set log or linear scale for x, y axis
def toggle_legend(self, evt=None, show=None): "toggle legend display" if show is None: show = not self.conf.show_legend self.conf.show_legend = show self.conf.draw_legend(f toggle_legend(self, evt=None, show=None): "toggle legend display" if show is None: show = not self.conf.show_legend self.conf.show_legend = show self.conf.draw_legend()
toggle legend display
def toggle_grid(self, evt=None, show=None): "toggle grid display" if show is None: show = not self.conf.show_grid self.conf.enable_grid(showf toggle_grid(self, evt=None, show=None): "toggle grid display" if show is None: show = not self.conf.show_grid self.conf.enable_grid(show)
toggle grid display
def configure(self, event=None): if self.win_config is not None: try: self.win_config.Raise() except: self.win_config = None if self.win_config is None: self.win_config = PlotConfigFrame(parent=self, config=self.conf, trace_color_callback=self.trace_color_callback) self.win_config.Raise()
show configuration frame
def BuildPanel(self): self.fig = Figure(self.figsize, dpi=self.dpi) # 1 axes for now self.gridspec = GridSpec(1,1) kwargs = {'facecolor': self.conf.bgcolor} if matplotlib.__version__ < "2.0": kwargs = {'axisbg': self.conf.bgcolor} self.axes = self.fig.add_subplot(self.gridspec[0], **kwargs) self.canvas = FigureCanvas(self, -1, self.fig) self.printer.canvas = self.canvas self.set_bg(self.conf.framecolor) self.conf.canvas = self.canvas self.canvas.SetCursor(wxCursor(wx.CURSOR_CROSS)) self.canvas.mpl_connect("pick_event", self.__onPickEvent) # overwrite ScalarFormatter from ticker.py here: self.axes.xaxis.set_major_formatter(FuncFormatter(self.xformatter)) self.axes.yaxis.set_major_formatter(FuncFormatter(self.yformatter)) # This way of adding to sizer allows resizing sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 2, wx.LEFT|wx.TOP|wx.BOTTOM|wx.EXPAND, 0) self.SetAutoLayout(True) self.autoset_margins() self.SetSizer(sizer) self.Fit() canvas_draw = self.canvas.draw def draw(*args, **kws): self.autoset_margins() canvas_draw(*args, **kws) self.canvas.draw = draw self.addCanvasEvents()
builds basic GUI panel and popup menu
def _updateCanvasDraw(self): fn = self.canvas.draw def draw2(*a,**k): self._updateGridSpec() return fn(*a,**k) self.canvas.draw = draw2
Overload of the draw function that update axes position before each draw
def get_default_margins(self): trans = self.fig.transFigure.inverted().transform # Static margins l, t, r, b = self.axesmargins (l, b), (r, t) = trans(((l, b), (r, t))) # Extent dl, dt, dr, db = 0, 0, 0, 0 for i, ax in enumerate(self.fig.get_axes()): (x0, y0),(x1, y1) = ax.get_position().get_points() try: (ox0, oy0), (ox1, oy1) = ax.get_tightbbox(self.canvas.get_renderer()).get_points() (ox0, oy0), (ox1, oy1) = trans(((ox0 ,oy0),(ox1 ,oy1))) dl = min(0.2, max(dl, (x0 - ox0))) dt = min(0.2, max(dt, (oy1 - y1))) dr = min(0.2, max(dr, (ox1 - x1))) db = min(0.2, max(db, (y0 - oy0))) except: pass return (l + dl, t + dt, r + dr, b + db)
get default margins
def autoset_margins(self): if not self.conf.auto_margins: return # coordinates in px -> [0,1] in figure coordinates trans = self.fig.transFigure.inverted().transform # Static margins if not self.use_dates: self.conf.margins = l, t, r, b = self.get_default_margins() self.gridspec.update(left=l, top=1-t, right=1-r, bottom=b) # Axes positions update for ax in self.fig.get_axes(): try: ax.update_params() except ValueError: pass ax.set_position(ax.figbox)
auto-set margins left, bottom, right, top according to the specified margins (in pixels) and axes extent (taking into account labels, title, axis)
def update_line(self, trace, xdata, ydata, side='left', draw=False, update_limits=True): x = self.conf.get_mpl_line(trace) x.set_data(xdata, ydata) datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()] self.conf.set_trace_datarange(datarange, trace=trace) axes = self.axes if side == 'right': axes = self.get_right_axes() if update_limits: self.set_viewlimits() if draw: self.draw()
update a single trace, for faster redraw
def __onPickEvent(self, event=None): legline = event.artist trace = self.conf.legend_map.get(legline, None) visible = True if trace is not None and self.conf.hidewith_legend: line, legline, legtext = trace visible = not line.get_visible() line.set_visible(visible) if visible: legline.set_zorder(10.00) legline.set_alpha(1.00) legtext.set_zorder(10.00) legtext.set_alpha(1.00) else: legline.set_alpha(0.50) legtext.set_alpha(0.50)
pick events
def get_userid_by_email(self, email): ''' get userid by email ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, email=email ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf get_userid_by_email(self, email): ''' get userid by email ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, email=email ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get userid by email
def get_user_id_by_user(self, username): ''' get user id by username ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, username=username ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf get_user_id_by_user(self, username): ''' get user id by username ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, username=username ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get user id by username
def get_user_by_userid(self, userid): ''' get user by user id ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf get_user_by_userid(self, userid): ''' get user by user id ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get user by user id
def get_user_presence(self, userid): ''' check on presence of a user ''' response, status_code = self.__pod__.Presence.get_v2_user_uid_presence( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf get_user_presence(self, userid): ''' check on presence of a user ''' response, status_code = self.__pod__.Presence.get_v2_user_uid_presence( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
check on presence of a user
def set_user_presence(self, userid, presence): ''' set presence of user ''' response, status_code = self.__pod__.Presence.post_v2_user_uid_presence( sessionToken=self.__session__, uid=userid, presence=presence ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf set_user_presence(self, userid, presence): ''' set presence of user ''' response, status_code = self.__pod__.Presence.post_v2_user_uid_presence( sessionToken=self.__session__, uid=userid, presence=presence ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
set presence of user
def search_user(self, search_str, search_filter, local): ''' add a user to a stream ''' response, status_code = self.__pod__.Users.post_v1_user_search( sessionToken=self.__session__, searchRequest={'query': search_str, 'filters': search_filter} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf search_user(self, search_str, search_filter, local): ''' add a user to a stream ''' response, status_code = self.__pod__.Users.post_v1_user_search( sessionToken=self.__session__, searchRequest={'query': search_str, 'filters': search_filter} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
add a user to a stream
def p12parse(self): ''' parse p12 cert and get the cert / priv key for requests module ''' # open it, using password. Supply/read your own from stdin. p12 = crypto.load_pkcs12(open(self.p12, 'rb').read(), self.pwd) # grab the certs / keys p12cert = p12.get_certificate() # (signed) certificate object p12private = p12.get_privatekey() # private key. # dump private key and cert symphony_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12private) symphony_crt = crypto.dump_certificate(crypto.FILETYPE_PEM, p12cert) # write tmpfiles crtpath = self.write_tmpfile(symphony_crt) keypath = self.write_tmpfile(symphony_key) # return cert and privkey return crtpath, keypatf p12parse(self): ''' parse p12 cert and get the cert / priv key for requests module ''' # open it, using password. Supply/read your own from stdin. p12 = crypto.load_pkcs12(open(self.p12, 'rb').read(), self.pwd) # grab the certs / keys p12cert = p12.get_certificate() # (signed) certificate object p12private = p12.get_privatekey() # private key. # dump private key and cert symphony_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12private) symphony_crt = crypto.dump_certificate(crypto.FILETYPE_PEM, p12cert) # write tmpfiles crtpath = self.write_tmpfile(symphony_crt) keypath = self.write_tmpfile(symphony_key) # return cert and privkey return crtpath, keypath
parse p12 cert and get the cert / priv key for requests module
def list_features(self): ''' list features the pod supports ''' response, status_code = self.__pod__.System.get_v1_admin_system_features_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf list_features(self): ''' list features the pod supports ''' response, status_code = self.__pod__.System.get_v1_admin_system_features_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
list features the pod supports
def user_feature_update(self, userid, payload): ''' update features by user id ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update( sessionToken=self.__session__, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf user_feature_update(self, userid, payload): ''' update features by user id ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update( sessionToken=self.__session__, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
update features by user id
def get_user_avatar(self, userid): ''' get avatar by user id ''' response, status_code = self.__pod__.User.get_v1_admin_user_uid_avatar( sessionToken=self.__session, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf get_user_avatar(self, userid): ''' get avatar by user id ''' response, status_code = self.__pod__.User.get_v1_admin_user_uid_avatar( sessionToken=self.__session, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get avatar by user id
def user_avatar_update(self, userid, payload): ''' updated avatar by userid ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_avatar_update( sessionToken=self.__session, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf user_avatar_update(self, userid, payload): ''' updated avatar by userid ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_avatar_update( sessionToken=self.__session, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
updated avatar by userid
def list_apps(self): ''' list apps ''' response, status_code = self.__pod__.AppEntitlement.get_v1_admin_app_entitlement_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf list_apps(self): ''' list apps ''' response, status_code = self.__pod__.AppEntitlement.get_v1_admin_app_entitlement_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
list apps
def stream_members(self, stream_id): ''' get stream members ''' response, status_code = self.__pod__.Streams.get_v1_admin_stream_id_membership_list( sessionToken=self.__session__, id=stream_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf stream_members(self, stream_id): ''' get stream members ''' response, status_code = self.__pod__.Streams.get_v1_admin_stream_id_membership_list( sessionToken=self.__session__, id=stream_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get stream members
def sessioninfo(self): ''' session info ''' response, status_code = self.__pod__.Session.get_v2_sessioninfo( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf sessioninfo(self): ''' session info ''' response, status_code = self.__pod__.Session.get_v2_sessioninfo( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
session info
def list_connections(self, status=None): ''' list connections ''' if status is None: status = 'ALL' response, status_code = self.__pod__.Connection.get_v1_connection_list( sessionToken=self.__session__, status=status ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf list_connections(self, status=None): ''' list connections ''' if status is None: status = 'ALL' response, status_code = self.__pod__.Connection.get_v1_connection_list( sessionToken=self.__session__, status=status ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
list connections
def connection_status(self, userid): ''' get connection status ''' response, status_code = self.__pod__.Connection.get_v1_connection_user_userId_info( sessionToken=self.__session__, userId=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf connection_status(self, userid): ''' get connection status ''' response, status_code = self.__pod__.Connection.get_v1_connection_user_userId_info( sessionToken=self.__session__, userId=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
get connection status
def create_connection(self, userid): ''' create connection ''' req_hook = 'pod/v1/connection/create' req_args = '{ "userId": %s }' % userid status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf create_connection(self, userid): ''' create connection ''' req_hook = 'pod/v1/connection/create' req_args = '{ "userId": %s }' % userid status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
create connection
def PKCS_GET_query(self, req_hook, req_args): ''' Generic GET query method ''' # GET request methods only require sessionTokens headers = {'content-type': 'application/json', 'sessionToken': self.__session__} # HTTP GET query method using requests module try: if req_args is None: response = requests.get(self.__url__ + req_hook, headers=headers, cert=(self.__crt__, self.__key__), verify=True) else: response = requests.get(self.__url__ + req_hook + str(req_args), headers=headers, cert=(self.__crt__, self.__key__), verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in PKCS_RESTful.GET_query()' # return the token self.logger.debug('%s: %s' % (response.status_code, response.text)) return response.status_code, response.texf PKCS_GET_query(self, req_hook, req_args): ''' Generic GET query method ''' # GET request methods only require sessionTokens headers = {'content-type': 'application/json', 'sessionToken': self.__session__} # HTTP GET query method using requests module try: if req_args is None: response = requests.get(self.__url__ + req_hook, headers=headers, cert=(self.__crt__, self.__key__), verify=True) else: response = requests.get(self.__url__ + req_hook + str(req_args), headers=headers, cert=(self.__crt__, self.__key__), verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in PKCS_RESTful.GET_query()' # return the token self.logger.debug('%s: %s' % (response.status_code, response.text)) return response.status_code, response.text
Generic GET query method
def ib_group_member_list(self, group_id): ''' ib group member list ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf ib_group_member_list(self, group_id): ''' ib group member list ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
ib group member list
def ib_group_member_add(self, group_id, userids): ''' ib group member add ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add' req_args = {'usersListId': userids} req_args = json.dumps(req_args) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf ib_group_member_add(self, group_id, userids): ''' ib group member add ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add' req_args = {'usersListId': userids} req_args = json.dumps(req_args) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
ib group member add
def ib_group_policy_list(self): ''' ib group policy list ''' req_hook = 'pod/v1/admin/policy/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf ib_group_policy_list(self): ''' ib group policy list ''' req_hook = 'pod/v1/admin/policy/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
ib group policy list
def start_monitoring(self): if self.__monitoring is False: self.__monitoring = True self.__monitoring_action()
Enable periodically monitoring.
def GET_query(self, req_hook, req_args): ''' Generic GET query method ''' # GET request methods only require sessionTokens headers = {'content-type': 'application/json', 'sessionToken': self.__session__} # HTTP GET query method using requests module try: if req_args is None: response = requests.get(self.__url__ + req_hook, headers=headers, verify=True) else: response = requests.get(self.__url__ + req_hook + str(req_args), headers=headers, verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in RESTful.GET_query()' # return the token return response.status_code, response.texf GET_query(self, req_hook, req_args): ''' Generic GET query method ''' # GET request methods only require sessionTokens headers = {'content-type': 'application/json', 'sessionToken': self.__session__} # HTTP GET query method using requests module try: if req_args is None: response = requests.get(self.__url__ + req_hook, headers=headers, verify=True) else: response = requests.get(self.__url__ + req_hook + str(req_args), headers=headers, verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in RESTful.GET_query()' # return the token return response.status_code, response.text
Generic GET query method
def POST_query(self, req_hook, req_args): ''' Generic POST query method ''' # HTTP POST queries require keyManagerTokens and sessionTokens headers = {'Content-Type': 'application/json', 'sessionToken': self.__session__, 'keyManagerToken': self.__keymngr__} # HTTP POST query to keymanager authenticate API try: if req_args is None: response = requests.post(self.__url__ + req_hook, headers=headers, verify=True) else: response = requests.post(self.__url__ + req_hook, headers=headers, data=req_args, verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in RESTful.POST_query()' # return the token return response.status_code, response.texf POST_query(self, req_hook, req_args): ''' Generic POST query method ''' # HTTP POST queries require keyManagerTokens and sessionTokens headers = {'Content-Type': 'application/json', 'sessionToken': self.__session__, 'keyManagerToken': self.__keymngr__} # HTTP POST query to keymanager authenticate API try: if req_args is None: response = requests.post(self.__url__ + req_hook, headers=headers, verify=True) else: response = requests.post(self.__url__ + req_hook, headers=headers, data=req_args, verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in RESTful.POST_query()' # return the token return response.status_code, response.text
Generic POST query method
def parse_MML(self, mml): ''' parse the MML structure ''' hashes_c = [] mentions_c = [] soup = BeautifulSoup(mml, "lxml") hashes = soup.find_all('hash', {"tag": True}) for hashe in hashes: hashes_c.append(hashe['tag']) mentions = soup.find_all('mention', {"uid": True}) for mention in mentions: mentions_c.append(mention['uid']) msg_string = soup.messageml.text.strip() self.logger.debug('%s : %s : %s' % (hashes_c, mentions_c, msg_string)) return hashes_c, mentions_c, msg_strinf parse_MML(self, mml): ''' parse the MML structure ''' hashes_c = [] mentions_c = [] soup = BeautifulSoup(mml, "lxml") hashes = soup.find_all('hash', {"tag": True}) for hashe in hashes: hashes_c.append(hashe['tag']) mentions = soup.find_all('mention', {"uid": True}) for mention in mentions: mentions_c.append(mention['uid']) msg_string = soup.messageml.text.strip() self.logger.debug('%s : %s : %s' % (hashes_c, mentions_c, msg_string)) return hashes_c, mentions_c, msg_string
parse the MML structure
def parse_msg(self, datafeed): ''' parse messages ''' message_parsed = [] for message in datafeed: mid = message['id'] streamId = message['streamId'] mstring = message['message'] fromuser = message['fromUserId'] timestamp = message['timestamp'] timestamp_c = date.fromtimestamp(int(timestamp) / 1000.0) hashes, mentions, msg_string = self.parse_MML(mstring) message_broke = {'messageId': mid, 'streamId': streamId, 'fromUser': fromuser, 'timestamp': timestamp, 'timestamp_c': timestamp_c, 'hashes': hashes, 'mentions': mentions, 'messageStr': msg_string} message_parsed.append(message_broke) self.logger.debug(message_parsed) return message_parsef parse_msg(self, datafeed): ''' parse messages ''' message_parsed = [] for message in datafeed: mid = message['id'] streamId = message['streamId'] mstring = message['message'] fromuser = message['fromUserId'] timestamp = message['timestamp'] timestamp_c = date.fromtimestamp(int(timestamp) / 1000.0) hashes, mentions, msg_string = self.parse_MML(mstring) message_broke = {'messageId': mid, 'streamId': streamId, 'fromUser': fromuser, 'timestamp': timestamp, 'timestamp_c': timestamp_c, 'hashes': hashes, 'mentions': mentions, 'messageStr': msg_string} message_parsed.append(message_broke) self.logger.debug(message_parsed) return message_parsed
parse messages
def member_add(self, stream_id, user_id): ''' add a user to a stream ''' req_hook = 'pod/v1/room/' + str(stream_id) + '/membership/add' req_args = '{ "id": %s }' % user_id status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf member_add(self, stream_id, user_id): ''' add a user to a stream ''' req_hook = 'pod/v1/room/' + str(stream_id) + '/membership/add' req_args = '{ "id": %s }' % user_id status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
add a user to a stream
def create_room(self, payload): ''' create a stream in a non-inclusive manner ''' response, status_code = self.__pod__.Streams.post_v2_room_create( # V2RoomAttributes payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, responsf create_room(self, payload): ''' create a stream in a non-inclusive manner ''' response, status_code = self.__pod__.Streams.post_v2_room_create( # V2RoomAttributes payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
create a stream in a non-inclusive manner