示例#1
0
        def form_snapshots_and_detections(db_objs):
            snapshot_tmp = Snapshot()
            snapshot_tmp.snapshot_id = db_objs[0]['snapshot_id']
            snapshot_tmp.runguid = db_objs[0]['runguid']
            snapshot_tmp.imagepath = db_objs[0]['imagepath']

            snapshot_tmp.view_matrix = np.array(db_objs[0]['view_matrix'],
                                                dtype=np.float64)
            snapshot_tmp.proj_matrix = np.array(db_objs[0]['proj_matrix'],
                                                dtype=np.float64)

            snapshot_tmp.width = db_objs[0]['width']
            snapshot_tmp.height = db_objs[0]['height']

            detectionList = []
            for obj in db_objs:
                detection_tmp = Detection()
                detection_tmp.detection_id = obj['detection_id']
                detection_tmp.type = obj['type']
                detection_tmp.pos = obj['pos']  # need to process this position
                detection_tmp.bbox = obj['bbox']  # geometry.Box
                detection_tmp.vehicle_class = obj['class']
                detection_tmp.handle = obj['handle']
                detection_tmp.best_bbox = obj['best_bbox']
                detection_tmp.fullbox = obj['fullbox']
                detection_tmp.bbox3d_min = obj['bbox3d_min']
                detection_tmp.bbox3d_max = obj['bbox3d_max']
                detection_tmp.rotation = obj['rot']
                detection_tmp.coverage = obj['coverage']
                detectionList.append(detection_tmp)

            snapshot_tmp.detections = detectionList

            return snapshot_tmp
 def run(self):
     print("Running ChatBot...\n")
     res = random.sample(self.intros,1)
     res = res[0]
     lines = []
     lines.append(res)
     try: 
         while True:
             sleep(0.6)
             userResponse = input("ChatBot: " + res + '\nYou: ')
             lines.append(userResponse)
             if len(lines) is 4: #Must be even
                 ss = Snapshot()
                 [ss.append(l) for l in lines]
                 self.database.addSnapshot(ss)
                 lines = lines[2:] #Chop off oldest exchange
             res = self.database.getFinale(userResponse)                        
             lines.append(res)
     except (KeyboardInterrupt, EOFError):
         try:
             sleep(2) #Get remaining interrupts
         except:
             pass
         res = random.sample(self.exits,1)
         print(res[0])
         self.database.writeDatabase()
 def create_snapshot(self):
     snapshot = Snapshot()
     [snapshot.addInstance(id=instance.id,
                           status=instance.status,
                           name=instance.name)
      for instance in self.nova_client.servers.list()]
     return snapshot
示例#4
0
 def create_snapshot(self):
     snapshot = Snapshot()
     [snapshot.addImage(id=image.id,
                        disk_format=image.disk_format,
                        name=image.name,
                        checksum=image.checksum)
      for image in self.glance_client.images.list()]
     return snapshot
示例#5
0
 def create_snapshot(self):
     snapshot = Snapshot()
     [snapshot.addVolume(id=volume.id,
                         status=volume.status,
                         display_name=volume.display_name,
                         attachments=volume.attachments)
      for volume in self.cinder_client.volumes.list()]
     return snapshot
示例#6
0
 def addShanpshotImage(self, image, updateRGB):
     self.removeIndex()
     new = Snapshot()
     new.myCopy(self.snapshots[self.currentIndex])
     new.setImage(image)
     if updateRGB:
         new.setRGB()
         new.color = (0, 0, 0)
     self.appendSnapshot(new)
def parseInference(query):
    config = Config()
    attCouples = Enumerable(
        query.split(';')).select(lambda x: x.split('=')).to_list()
    row = Enumerable(
        config.evidences()).select(lambda x: getVals(x, attCouples)).to_list()
    row.append(None)
    return Snapshot(row)
示例#8
0
 def __init__(self, window=None):
     '''
     Constructor
     '''
     Frame.Frame.__init__(self)
     self._renderer = None
     self._snapshot = Snapshot()
     self._camera = Camera()
     self._setup = False
     self._lmb = False
     # Make the game window
     title = "Astrophysics Visualisation"
     windowed = True
     
     screenSize = (1800,1024)
     if window == None:
         window = pyglet.window.Window(screenSize[0], screenSize[1],caption = title)
     self._window = window
示例#9
0
def parseELF(fname, **kwargs):
    f = ELFFile(open(fname, 'rb'))
    sections = list(f.iter_sections())
    tables = [ s for s in sections if isinstance(s, SymbolTableSection) ]
    symbols = { sym.name: sym.entry for table in tables for sym in table.iter_symbols() }

    blobs, offsets = [], []
    for s in Constants.kAppAOTSymbols:
        s = symbols[s]
        section = next(S for S in sections if 0 <= s.st_value - S['sh_addr'] < S.data_size)
        blob = section.data()[(s.st_value - section['sh_addr']):][:s.st_size]
        assert len(blob) == s.st_size
        blobs.append(blob), offsets.append(s.st_value)

    vm = Snapshot(blobs[0], offsets[0], blobs[1], offsets[1])
    isolate = Snapshot(blobs[2], offsets[2], blobs[3], offsets[3], vm)

    return isolate
示例#10
0
	def save_snapshot(self, description: str = "", highlights: dict = {}):
		"""
		Metoda zapisująca aktualny stan tablicy z danymi.

		Parametry:
		description - opis zmian dokonanych w zapisywanym stanie.
		highlights - słownik z węzłami oznaczonymi innym kolorem.
		"""
		self.snapshots.append(Snapshot(deepcopy(self.data), description, highlights))
	def __init__(self, parent=None):
		super().__init__(parent, QGridLayout)
		self.nodz_nodes = []
		self.nodz = None
		self.setup_ui()

		self.render_snapshot(
			Snapshot([],"Test",{})
		)
示例#12
0
    def setup_ui(self):
        """
		Inicjalizacja interfejsu użytkownika.
		"""
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        self.setStyleSheet(Styles.description_background)

        self.render_snapshot(Snapshot([], "", {}))
示例#13
0
def parseMachO(fname, **kwargs):
    f = lief.parse(fname)
    # sections = f.sections
    symbols = {s.name: s for s in f.symbols}
    symbols_infos = sorted([(s.name, s.value) for s in f.symbols], key=lambda info: info[1])
    sc = f.symbol_command
    blobs, offsets = [], []
    for sn in Constants.kAppAOTSymbols:
        s = symbols[sn]
        next_offset = find_next_offset(symbols_infos, sn)
        s_size = next_offset - s.value
        print(f'{sn}, start {s.value}, end {s.value + s_size - 2}, size {s_size}')
        
        blob = f.get_content_from_virtual_address(s.value, s_size)
        blobs.append(bytes(blob))
        offsets.append(s.value)

    vm = Snapshot(blobs[0], offsets[0], blobs[1], offsets[1])
    isolate = Snapshot(blobs[2], offsets[2], blobs[3], offsets[3], vm)

    return isolate
示例#14
0
class CardCapture:

  def __init__(self):
    self.cr = cr2.CardRecognition()
    self.snap = Snapshot()

  def get(self):
    # get image from webcam
    path = self.snap.capture();
    
    # send image to cr
    cards = self.cr.get_cards(path)
    
    cards = [ Card(cd[0],cd[1]) for cd in cards ]
    #print(cards)
    return cards
def getData():
    data = list()
    with open('data/FixedDataset.csv') as csv_file:
        csv_reader = csv.DictReader(csv_file, delimiter=';')
        for sample in csv_reader:
            data.append(
                Snapshot([
                    int(sample['x1']),
                    int(sample['y1']),
                    int(sample['z1']),
                    int(sample['x2']),
                    int(sample['y2']),
                    int(sample['z2']),
                    int(sample['x3']),
                    int(sample['y3']),
                    int(sample['z3']),
                    int(sample['x4']),
                    int(sample['y4']),
                    int(sample['z4']), sample['class']
                ]))
    return data
示例#16
0
 def list_snapshots(self, vm):
     ssh = paramiko.SSHClient()
     ssh.load_system_host_keys()
     ssh.connect(self.ip, username=self.user, password=self.password)
     stdin, stdout, stderr = ssh.exec_command('xe snapshot-list snapshot-of='+vm.id+' params=all')
     ret = stdout.read()
     ssh.close()
     vm.snapshots = []
     name = ""
     id=""
     descr=""
     time=""
     for l in ret.split("\n"):
         if "uuid ( RO)" in l:
             id = l.split(" : ")[-1]
         elif "snapshot-time" in l:
             time = l.split(": ")[-1]
         elif "name-label" in l:
             name = l.split(": ")[-1]
         elif "name-description" in l:
             descr = l.split(": ")[-1]
             vm.snapshots.append(Snapshot(id=id, name=name, descr=descr, time=time))
     vm.snapshots.sort(key = lambda x : x.name)
     return vm.snapshots
def preProcess(snaps):
    config = Config()
    data = np.empty([len(snaps),13])
    i = 0
    for snap in snaps:
        data[i, 0] = snap.x1
        data[i, 1] = snap.y1
        data[i, 2] = snap.z1
        data[i, 3] = snap.x2
        data[i, 4] = snap.y2
        data[i, 5] = snap.z2
        data[i, 6] = snap.x3
        data[i, 7] = snap.y3
        data[i, 8] = snap.z3
        data[i, 9] = snap.x4
        data[i, 10] = snap.y4
        data[i, 11] = snap.z4
        data[i, 12] = encodeClass(snap.harClass)
        i = i + 1
    data_tmp = normalize(data[:, np.arange(12)], norm = 'l2', axis = 0, return_norm = False)
    est = KBinsDiscretizer(n_bins = config.nOfBuckets(), encode='ordinal').fit(data_tmp)
    data_discretize = est.transform(data_tmp)
    data = np.concatenate((data_discretize, data[:, [12]]), axis = 1)
    return Enumerable(data).select(lambda x: Snapshot(x)).to_list()
示例#18
0
 def getCurrentSnapshot(self):
     """Returns current snapshot of this machine or None if machine currently has no snapshots"""
     imachine = self.getIMachine()
     if imachine.currentSnapshot is None:
         return None
     return Snapshot(imachine.currentSnapshot)
示例#19
0
 def __init__(self):
   self.cr = cr2.CardRecognition()
   self.snap = Snapshot()
示例#20
0
	def setUp(self):
		self.snapshot = Snapshot([], 'description', {})
示例#21
0
 def snapshot_vm(self, vm, snapname):
     try:
         snap = Snapshot(vm, snapname)
         snap.create()
         result = snap.test()  #проверяем заданным в конфиге типом проверки
         if not result:  #тесты вернули не True - vm недоступна
             raise ValueError('Incorrect testing result')
         print('Successfully created snapshot', snapname, 'for', vm.name,
               '(', vm.vmid, ')')
         #проверим что снапшотов не больше трех старых + 1 current
         with paramiko.SSHClient() as client:
             client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             client.connect(vm.node['hostname'],
                            username=vm.node['username'],
                            password=vm.node['password'])
             stdout = client.exec_command(
                 'pvesh get /nodes/{node}/qemu/{vmid}/snapshot --output-format json'
                 .format(node=vm.node['name'],
                         vmid=vm.vmid))[1]  #достаем список снапшотов для vm
             snapshot_list = json.loads(
                 stdout.read().decode('ascii').strip("\n"))
             snapshots = sorted(snapshot_list,
                                key=lambda k: k.get('snaptime', sys.maxsize)
                                )  #находим самый старый из них
         if len(snapshots) > 4:
             print('Deleting old snapshot', snapshots[0]['name'])
             oldsnap = Snapshot(
                 vm, snapshots[0]['name']
             )  #создаем для него прототип снапшота и вызываем их удаление
             oldsnap.delete()
     except:
         snap.delete(
         )  #если произошла ошибка, удалим наш неработающий снапшот
         print('ERROR: SNAPSHOT CREATION FAILED!', snapname, vm.name, '(',
               vm.vmid, ')')
         traceback.print_exc()
示例#22
0
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
Simple backup tool
~~~~~~~~~~~~~~~~~~
Author: Vladimir Strackovski <*****@*****.**>
"""

import os
import sys
import json
from Snapshot import Snapshot

__author__ = 'vstrackovski'

cfgFile = os.path.dirname(os.path.realpath(__file__)) + '/backup.json'

if not os.path.isfile(cfgFile):
    message = "Configuration is expected to be stored in " + cfgFile + ", but no such file was found!\n"
    message += "Please run the setup tool (setup.py) to configure your backup instance."
    sys.exit('ERROR: ' + message)

with open(cfgFile) as data_file:
    configs = json.load(data_file)

for config in configs:
    snapshot = Snapshot(config['source'], config['destinations'])
    snapshot.make()
    snapshot.transfer()
示例#23
0
class AsVis(Frame.Frame):
    '''
    The top level object for visualising astrophysics 
    '''

    def __init__(self, window=None):
        '''
        Constructor
        '''
        Frame.Frame.__init__(self)
        self._renderer = None
        self._snapshot = Snapshot()
        self._camera = Camera()
        self._setup = False
        self._lmb = False
        # Make the game window
        title = "Astrophysics Visualisation"
        windowed = True
        
        screenSize = (1800,1024)
        if window == None:
            window = pyglet.window.Window(screenSize[0], screenSize[1],caption = title)
        self._window = window
        
    def Window(self):
        '''
        Return the pyglet window object used by the visualiser
        '''
        return self._window
        
    def Run(self):
        '''
        Start the draw loop
        '''
        pyglet.app.run()
        
    def Setup(self):
        '''
        Set up the main level - can usually be guaranteed to run before Run()
        '''
        glEnable(GL_DEPTH_TEST)
        if not self._setup:
            # This starts threads and stuff, so don't grunk up anything by 
            self._renderer = Renderer(self.Window(), self._camera)
            self._renderer.Setup()
            self._setup = True
    
    def LoadSnapshot(self, filename):
        '''
        Load a snapshot
        '''
        self._snapshot.Open(filename)
        self._renderer.LogText(self._snapshot.InfoText())
        self._renderer.Redraw()
            
    def Draw(self, dummy=None):
        if self._camera.ZoomActive():
            self._renderer.Redraw()
        self._renderer.Draw([self._snapshot])
        #if self._camera.ZoomActive():
        
    def Redraw(self):
        self._renderer.Redraw()
        
    def OnMouseMove(self, state):
        '''
        Parse mouse movement
        '''
        if self._lmb:
            self._renderer.Camera().OnMouseMove(state)
        self.Redraw()

    def OnKeyboard(self, state):
        '''
        Register the pressing or releasing of a keyboard key
        This can be overridden by the concrete class if desired, or left inactive
        state - a dictionary of the mouse state:
                   {"button": button, "mod": modifier keys used, "pressed":True or False}
        '''
        # 113 = Q, 101 = e, YES I KNOW I'M IN A HURRY OK
        # Escape
        pressed = state["pressed"]
        button = state["button"]
        #if button == pyglet.window.key.ESCAPE:
            # Upon returning the window will now quit too
        # Q
        if button == pyglet.window.key.Q:
            self._renderer.Camera().ZoomIn(pressed)
        # E
        if button == pyglet.window.key.E:
            self._renderer.Camera().ZoomOut(pressed)
            
        # Switch render modes
        # TODO: Unbreak this
        #if button == pyglet.window.key.P and not pressed:
        #    self._renderer.ToggleBillboarding()
        
    def OnMouseButton(self, state):
        if state["button"] % 2 == pyglet.window.mouse.LEFT:
            self._lmb = state["pressed"] # True if pressed, False if not
示例#24
0
 def addSnapshotColor(self, color):
     self.removeIndex()
     new = Snapshot()
     new.myCopy(self.snapshots[self.currentIndex])
     new.setColor(color)
     self.appendSnapshot(new)
示例#25
0
 def __init__(self):
     self.currentIndex = 0
     self.snapshots = []
     self.snapshots.append(Snapshot())
示例#26
0
 def createSnapshot(self):
     return Snapshot(self, self.position)
示例#27
0
 def addSnapshotRGB(self, rgbValue, rgbOperation):
     self.removeIndex()
     new = Snapshot()
     new.myCopy(self.snapshots[self.currentIndex])
     new.setRGB(rgbValue, rgbOperation)
     self.appendSnapshot(new)