def get_keyspaces(self,machine_id):
		"""Returns all keyspaces in form of list """
		print "->>>in get keyspace function"
		sys = SystemManager(machine_id)
		keyspace_list = sys.list_keyspaces()
		sys.close()
		return keyspace_list
Esempio n. 2
0
def main():
    # 创建数据库链接
    db = pymysql.connect('localhost', 'root', '123456', 'dict')

    # 创建套接字
    s = socket()
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    s.bind(ADDR)
    s.listen(5)

    # 忽略子进程信号
    signal.signal(signal.SIGCHLD, signal.SIG_IGN)

    while True:
        try:
            c, addr = s.accept()
            print('Connect from', addr)
        except KeyboardInterrupt:
            s.close()
            sys.close('服务器退出')
        except Exception as e:
            print(e)
            continue

        # 创建子进程
        pid = os.fork()
        if pid == 0:
            s.close()
            do_child(c, db)
        else:
            c.close()
            continue
Esempio n. 3
0
	def solve(self):
		# solve t for y: ds = v1*dt + (1/2)a(dt)^2
		
		self.y.t = quad(0.5*self.y.a, self.y.v1, -1*self.y.s)
		if not self.y.t:
			print("No solution")
			close(0)
		if len(self.y.t) == 2:
			
			options = ["Which of these is right for time", self.y.t[0], self.y.t[1]]

			option = options[cutie.select(options, caption_indices=[0],selected_index=1)]
			if option == self.y.t[0]:
				self.y.t = self.y.t[0]
			else:
				self.y.t = self.y.t[1]
			print("\033[4A")
			print("\033[K")
			print("\033[K")
			print("\033[K")
			print("\033[K")
			print("\033[5A")
		else:
			self.y.t = self.y.t[0]

		# add to x
		self.x.t = self.y.t
		#solve for ds for x: ds = v1*dt
		self.x.s = self.x.v1*self.x.t
		# solve for v2 for y
		self.y.v2 = sqrt(2*self.y.a*self.y.s + self.y.v1*self.y.v1)
	def keyspace_create(self,machine_id,name):
		"""Create keyspace with given name on specified machine_id """
		print "->>>in create keyspace function"
		sys = SystemManager(machine_id)
		sys.create_keyspace(name, SIMPLE_STRATEGY, {'replication_factor': '1'})
		sys.close()
		return 1
Esempio n. 5
0
def worker():
    #worker_id = random.randrange(1,10005)
    #print("I am worker #%s" % (worker_id))
    context = zmq.Context()
    # recieve work
    worker_receiver = context.socket(zmq.PULL)
    worker_receiver.connect("tcp://127.0.0.1:8677")
    # send work
    worker_sender = context.socket(zmq.PUSH)
    worker_sender.connect("tcp://127.0.0.1:8678")

    while True:
        message = str(worker_receiver.recv(), "utf-8")
        print("Request received: %s" % message)
        #data = work['num']
        #result = { 'worker' : worker_id, 'num' : data}
        #if data%2 == 0:
        #    worker_sender.send_json(result)

        sensor_data = "123456789"

        msg = {
            'worker': 1,
            'data': sensor_data,
        }
        msg_json = json.dumps(msg)
        worker_sender.send_string(msg_json)
        time.sleep(1)

    worker_receiver.close()
    sys.close()
Esempio n. 6
0
    def __init__(self):
        myLib = '%s/DarumaFramework/libDarumaFramework.so' % \
                os.path.split(os.path.abspath(os.path.realpath(__file__)))[0].strip() 
        #self.iDrv = cdll.LoadLibrary('./usr/lib/libDarumaFramework.so')
        self.iDrv = cdll.LoadLibrary(myLib) 
        try:
            pass 
        except OSError:
            logDebug('NO INITIALIZE: OSError! Lib not found') 
            print 'Library file not found! %s' % myLib 
            sys.close(1)
        except e:
            logDebug('NO INITIALIZE: %s - %s' % (e.errno, e.errstr) )
            print '%s - %s' % (e.errno, e.errstr) 
            sys.close(1)


        #if '/usr/lib' not in sys.path: sys.path.append('/usr/local/lib/liblebin.so')  
        #logDebug('sys.path: %s ' % sys.path) 

        
        self.Status = None
        self.COO    = ' '*6
        self.CCF    = ' '*6
        self.TOTAL  = ' '*12
        self.GT     = ' '*60
        self.SERIE  = ' '*60
        self.STATUSECF = ' '*14
        logDebug('LOAD INIT BASE')
Esempio n. 7
0
def main():
    while True:
        #dados = s.recv(1024)
        #dados = base64_deco(dados)
        dados = base64_deco(s.recv(1024))
        if dados[:-1] == '/exit':
            sys.close()
            s.close()
Esempio n. 8
0
def checkVersion():
    nextVersion = str(VERSION).split('.')[0] + '.' + str(int(str(VERSION).split('.')[1]) + 1)
    if len(nextVersion) == 4:
        nextVersion = str(int(str(VERSION).split('.')[0]) + 1) + '.0'
    r = get("https://github.com/Djsurry/projectile-solver/relg/veases/tag/v{}".format(nextVersion))
    if r.status_code != 404:
        print("WARNGING! YOU ARE USING OUT OF DATE SOFTWARE!\nGO TO https://github.com/Djsurry/projectile-solver to download the latest version")
        close()
	def keyspace_delete(self,machine_id,name):
		"""Delete keyspace with given name on specified machine_id """
		print "->>>in delete keyspace function"
		sys = SystemManager(machine_id)
		key = keyspace()
		if (key.keyspace_contains(machine_id,name)):
			sys.drop_keyspace(name)
		sys.close()
		return 1
	def keyspace_contains(self,machine_id,name):
		"""Returns true if keyspace with given name is on specified machine_id """
		print "->>>in contain keyspace function"
		sys = SystemManager(machine_id)
		keyspace_list = sys.list_keyspaces()
		sys.close()
		for i in keyspace_list:
			if (i == name):
				return True
		return False
	def colum_family_create(self,machine_id,keyspace_name,column_family_name):
		"""Create a column family in a given keyspace """
		if (self.keyspace_contains(keyspace_name) == False):
			print "Error : Keyspace with this name dosenot exist."
			return False
		sys = SystemManager(machine_id)
		sys.create_column_family(keyspace_name, column_family_name)
		self.keyspace_columnfamily_list('localhost:9160')
		sys.close()
		return True
	def colum_family_delete(self,machine_id,keyspace_name,column_family_name):
		"""Create a column family in a given keyspace """
		if (self.keyspace_contains(keyspace_name,column_family_name) == False):
			print "Error : Keyspace:column family could not be found."
			return False
		sys = SystemManager(machine_id)
		sys.drop_column_family(keyspace_name, column_family_name)
		self.keyspace_columnfamily_list('localhost:9160')
		sys.close()
		return True
Esempio n. 13
0
def main():
        prompt = "Enter number of names to be generated: \n"
        try:
                answer = int(raw_input(prompt))
                print generate_names(answer)
                raw_input()
                close(0)
        except Exception:
                print "Try again. \n"
                main()
Esempio n. 14
0
def sig_handler(signum, frame):
    print("Termina aplicacion")
    StopApp = True
    IsClientConnected = False
    conn.close()
    ##mySocket.shutdown(1)
    ##mySocket.close()
    cmd.close()
    evt.close()
    sys.close()
	def keyspace_create(self,machine_id,keyspace_name):
		"""Create keyspace with given name on specified machine_id """
		if (self.keyspace_contains(keyspace_name) == True):
			print "Error : Keyspace with this name already exist."
			return False
		sys = SystemManager(machine_id)
		print sys.create_keyspace(keyspace_name, SIMPLE_STRATEGY, {'replication_factor': '1'})
		self.keyspace_columnfamily_list('localhost:9160')
		sys.close()
		return True
	def keyspace_delete(self,machine_id,keyspace_name):
		"""Delete keyspace with given name on specified machine_id """
		if (self.keyspace_contains(keyspace_name) == False):
			print "Error : Keyspace with this name dosenot exist."
			return False
		sys = SystemManager(machine_id)
		sys.drop_keyspace(keyspace_name)
		self.keyspace_columnfamily_list('localhost:9160')
		sys.close()
		return True
Esempio n. 17
0
def send_commands(conn):
    while True:
        cmd = input()
        if cmd == 'quit':
            sys.close()
            sys.exit()
        if len(str.encode(cmd)) > 0:
            conn.send(str.encode(cmd))
            client_response = str(conn.recv(1024), "utf-8")
            print(client_response, end="")
Esempio n. 18
0
 def keyspace_delete(self, machine_id, keyspace_name):
     """Delete keyspace with given name on specified machine_id """
     if (self.keyspace_contains(keyspace_name) == False):
         print "Error : Keyspace with this name dosenot exist."
         return False
     sys = SystemManager(machine_id)
     sys.drop_keyspace(keyspace_name)
     self.keyspace_columnfamily_list('localhost:9160')
     sys.close()
     return True
Esempio n. 19
0
 def colum_family_create(self, machine_id, keyspace_name,
                         column_family_name):
     """Create a column family in a given keyspace """
     if (self.keyspace_contains(keyspace_name) == False):
         print "Error : Keyspace with this name dosenot exist."
         return False
     sys = SystemManager(machine_id)
     sys.create_column_family(keyspace_name, column_family_name)
     self.keyspace_columnfamily_list('localhost:9160')
     sys.close()
     return True
Esempio n. 20
0
def port_peed(self):
    for self.speed in range(step=1):
        port_speed[self.speed].byteorder()
        port_speed[self.speed].reload()
    for speed in range(step=2):
        port_speed[self.speed].byteorder()
    for speed in range(step=3):
        port_speed[self.speed].byteorder()
    if len(port_speed) > 3:
        print("Error! only 3 levels")
        sys.close()
Esempio n. 21
0
 def keyspace_create(self, machine_id, keyspace_name):
     """Create keyspace with given name on specified machine_id """
     if (self.keyspace_contains(keyspace_name) == True):
         print "Error : Keyspace with this name already exist."
         return False
     sys = SystemManager(machine_id)
     print sys.create_keyspace(keyspace_name, SIMPLE_STRATEGY,
                               {'replication_factor': '1'})
     self.keyspace_columnfamily_list('localhost:9160')
     sys.close()
     return True
Esempio n. 22
0
 def colum_family_delete(self, machine_id, keyspace_name,
                         column_family_name):
     """Create a column family in a given keyspace """
     if (self.keyspace_contains(keyspace_name,
                                column_family_name) == False):
         print "Error : Keyspace:column family could not be found."
         return False
     sys = SystemManager(machine_id)
     sys.drop_column_family(keyspace_name, column_family_name)
     self.keyspace_columnfamily_list('localhost:9160')
     sys.close()
     return True
def create_column_families():
    sys = pycassa.system_manager.SystemManager('esb-a-test.sensors.elex.be')
    #sys.create_keyspace('test', pycassa.system_manager.NETWORK_TOPOLOGY_STRATEGY, {'erfurt': '1', 'sensors': '1', 'sofia': '1', 'diegem': '1'})
    sys.create_column_family('test',
                             'INDEXCF',
                             super=False,
                             comparator_type=pycassa.system_manager.UTF8_TYPE)
    sys.create_column_family('test',
                             'DATACF',
                             super=False,
                             comparator_type=pycassa.system_manager.UTF8_TYPE)
    sys.close()
	def keyspace_columnfamily_list(self,machine_id):
		"""Returns dictionary of all keyspace with their column family on specified machine_id """
		sys = SystemManager(machine_id)
		keyspace.complete_list.clear()
		keyspace_list = sys.list_keyspaces()
		for key in keyspace_list:
			x=[]
			result = sys.get_keyspace_column_families(key, use_dict_for_col_metadata=True)
			for i in result:
				x.append(i)
			keyspace.complete_list[key] = x
		sys.close()
		return keyspace.complete_list
Esempio n. 25
0
def readAsk(fileIn):
    cliche = ''
    try:
        fileIn = open(fileIn, 'r')
        inLines = fileIn.readlines()
        for line in inLines:
            cliche = line
    except IOError as e:
        print e
        sys.close(1)
    finally:
        fileIn.close()
    return cliche
Esempio n. 26
0
 def keyspace_columnfamily_list(self, machine_id):
     """Returns dictionary of all keyspace with their column family on specified machine_id """
     sys = SystemManager(machine_id)
     keyspace.complete_list.clear()
     keyspace_list = sys.list_keyspaces()
     for key in keyspace_list:
         x = []
         result = sys.get_keyspace_column_families(
             key, use_dict_for_col_metadata=True)
         for i in result:
             x.append(i)
         keyspace.complete_list[key] = x
     sys.close()
     return keyspace.complete_list
Esempio n. 27
0
	def keyspace_get_list(self,machine_id):
		"""Returns all keyspaces in form of list """
		keyspace.error = "Unknown error occur please check your inputs"
		try:
			sys = SystemManager(machine_id)
		except Exception as e:
			print e
			return False
		try:
			keyspace_list = sys.list_keyspaces()
		except Exception as e:
			print e	
			return False
		sys.close()
		return keyspace_list
Esempio n. 28
0
def getInputs():
    active = True
    currentLevel = 0
    f = True
    inputs = ["", "", ""]
    while active:

        if not f:
            print("\033[4A")
        else:
            f = False
        if currentLevel == 0:
            print(f"\033[K\x1b[38;5;1m Height: {inputs[0]} \x1b[0m")
            print(f"\033[KAngle: {inputs[1]}")
            print(f"\033[KInitial Velocity: {inputs[2]}")
        elif currentLevel == 1:
            print(f"\033[KHeight: {inputs[0]}")
            print(f"\033[K\x1b[38;5;1m Angle: {inputs[1]} \x1b[0m")
            print(f"\033[KInitial Velocity: {inputs[2]}")
        elif currentLevel == 2:
            print(f"\033[KHeight: {inputs[0]}")
            print(f"\033[KAngle: {inputs[1]}")
            print(f"\033[K\x1b[38;5;1m Initial Velocity: {inputs[2]} \x1b[0m")

        char = readchar.readkey()
        if char == "\x03":
            close(0)
        elif char == "\x1b\x5b\x42":
            currentLevel = currentLevel + 1 if currentLevel != 2 else 0
        elif char == "\x1b\x5b\x41":
            currentLevel = currentLevel - 1 if currentLevel != 0 else 2
        elif char == "\x0d":
            if "" not in inputs:
                break
        elif char == "\x7f":
            inputs[currentLevel] = inputs[currentLevel][:-1]
        elif char in "1234567890.":
            if char == ".":
                if "." in inputs[currentLevel]:
                    continue
            if inputs[currentLevel] == "9" and currentLevel == 1:
                if char != "0":
                    continue
            if currentLevel == 1 and len(inputs[currentLevel]) == 2:
                continue
            inputs[currentLevel] += char
    clear(3)
    return inputs
Esempio n. 29
0
def startApp():
    url = makeUrl()
    while True:
        try:
            dk = '%s%s' % ('node getid ', next(url))
            try:
                print(url)
                (status, output) = commands.getstatusoutput(dk)
                print(output)
            except Exception as e:
                print(e)
        except StopIteration:
            sys.exit()
        except Exception as e:
            pass
            sys.close()
Esempio n. 30
0
 def start(self):
     wals = self.getWallpaper()
     sleep = self.sleep
     while True:
         try:
             os.system(
                 'gsettings set org.gnome.desktop.background picture-uri "%s"'
                 % (next(wals)))
             with open(self.lastpath, "w+") as fo:
                 fo.write(str(self.index))
             time.sleep(sleep)
         except StopIteration:
             SetWallpaper(self.rootdir, self.sleep)
         except Exception as e:
             print(e)
             pass
             sys.close()
Esempio n. 31
0
def main():
    while True:
        data = base64_deco(s.recv(1024))
        if data[:1] == '/exit':
            sys.close()
            s.close()
            close()
        # if 'cd '.encode() in data:
        #     os.chdir(data[3:].strip("\n"))

        sub = subprocess.Popen(data,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               stdin=subprocess.PIPE)
        output = sub.stderr.read() + sub.stdout.read()
        s.send(output)
Esempio n. 32
0
def systemToPC(nombre, ruta): #recibimos el nombre del archivo y la ruta
	sys=open("fiunamfs.img","rw")
	sys.seek(1024)
	for i in range(64):
		if sys.read(15)==nombre: #Leemos un espacio vacío
			#Leemos el inicio del espacio
			sys.seek(sys.tell()+10)
			ini=int(sys.read(5))
			#Crear objeto archivo nuevo en la ruta dada y copiar en él la información
			fin=int(sys.tell())
			sys.seek(ini)
			sys.seek(sys.tell()-14)
			sys.write(ini-fin) #guardamos el tamaño del archivo
		else:
			sys.seek(sys.tell()+49)
	sys.close()
	file.close()
Esempio n. 33
0
def pcToSystem(file): #Recibimos el archivo ya abierto listo para ser leído desde nuestra pc
	sys=open("fiunamfs.img","rw")
	sys.seek(1024)
	for i in range(64):
		if sys.read(15)=='AQUI_NO_VA_NADA': #Leemos un espacio vacío
			#Leemos el inicio del espacio
			sys.seek(sys.tell()+10)
			ini=int(sys.read(5))
			sys.write(file.read()) #Copiamos la informacion
			fin=int(sys.tell())
			sys.seek(ini)
			sys.seek(sys.tell()-14)
			sys.write(ini-fin) #guardamos el tamaño del archivo
		else:
			sys.seek(sys.tell()+49)
	sys.close()
	file.close()
Esempio n. 34
0
 def menu(self):
     opcion = None
     while opcion != "4":
         print("\n---Opciones---\n")
         print("1. Cargar alumno: ")
         print("2. Listar alumnos: ")
         print("3. Mostrar mayores a 7: ")
         print("4. Salir del programa. ")
         opcion = (input("Ingrese su opcion: "))
         if opcion == "1":
             self.cargar_alumno()
         elif opcion == "2":
             self.listar_alumnos()
         elif opcion == "3":
             self.mayor_7()
         elif opcion == "4":
             sys.close()
Esempio n. 35
0
	def keyspace_create(self,machine_id,keyspace_name,replication="1"):
		"""Create keyspace with given name on specified machine_id """
		keyspace.error = "Unknown error occur please check your inputs"
		if (self.keyspace_contains(keyspace.local_system,keyspace_name) == True):
			keyspace.error = "Desired Keyspace already exist with this name"
			return False
		try:
			sys = SystemManager(machine_id)
		except Exception as e:
			print e
			return False
		try:
			sys.create_keyspace(keyspace_name, SIMPLE_STRATEGY, {'replication_factor': replication})
		except Exception as e:
			print e	
			return False
		sys.close()
		return True
Esempio n. 36
0
	def keyspace_delete(self,machine_id,keyspace_name):
		"""Delete keyspace with given name on specified machine_id """
		keyspace.error = "Unknown error occur please check your inputs"
		if (self.keyspace_contains(keyspace.local_system,keyspace_name) == False):
			keyspace.error = "Desired Keyspace does not exist."
			return False
		try:
			sys = SystemManager(machine_id)
		except Exception as e:
			print e
			return False
		try:
			sys.drop_keyspace(keyspace_name)
		except Exception as e:
			print e
			return False
		sys.close()
		return True
Esempio n. 37
0
	def colum_family_delete(self,machine_id,keyspace_name,column_family_name):
		"""Create a column family in a given keyspace """
		keyspace.error = "Unknown error occur please check your inputs"
		if (self.keyspace_contains(keyspace.local_system,keyspace_name,column_family_name) == False):
			keyspace.error = "Desired Keyspace,Column Family pair could not be found."
			return False
		try:
			sys = SystemManager(machine_id)
		except Exception as e:
			print e
			return False
		try:
			sys.drop_column_family(keyspace_name, column_family_name)
		except Exception as e:
			print e		
			return False
		sys.close()
		return True
Esempio n. 38
0
def main():
    checkVersion()
    i = getInputs()
    p = Problem(isFloat(i[0]), isFloat(i[1]), isFloat(i[2]))
    p.solve()
    first = True
    choices = [
        "What would you like to know?",
        "Range",
        "Total Time",
        "X and Y at specific time",
        "X or Y at cooresponding distance",
        "Maximum height",
        "Speed at impact on ground",
        "Velocity at impact on ground",
        "New problem",
        "Quit",
    ]
    while True:
        choice = choices[cutie.select(choices, caption_indices=[0], selected_index=1)]
        if choice == "Range":
            p.range()
        elif choice == "Quit":
            close(0)
        elif choice == "Maximum height":
            p.maxHeight()
        elif choice == "X and Y at specific time":
            p.xyT()
        elif choice == "X or Y at cooresponding distance":
            p.xyD()
        elif choice == "Total Time":
            p.totalTime()
        elif choice == "Speed at impact on ground":
            p.speedAtGround()
        elif choice == "Velocity at impact on ground":
            p.velocityAtGround()
        elif choice == "New problem":
            system("clear")
            print("\n")
            main()
Esempio n. 39
0
def Socket():
    try:
        print(Fore.RED+"[*]Creazione Socket")
        with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
            Sleep()
            print(Style.RESET_ALL+"[*]Binding degli indirizzi..")
            s.bind((Ind,Port))

            Sleep()
            print("[*]Socket in ascolto..")
            s.listen()
            conn,addr=s.accept()
            Sleep()
            print("[*]Connessione ricevuta da ",addr)
            ''''data=conn.recv(4096)        
            data=data.decode("utf-8")'''
            Commands(s,conn)
    except KeyboardInterrupt as K:
        print(K)
    except Exception as errore:
        print(errore)
        sys.exit()
        sys.close()
	def keyspace_get_list(self,machine_id):
		"""Returns all keyspaces in form of list """
		sys = SystemManager(machine_id)
		keyspace_list = sys.list_keyspaces()
		sys.close()
		return keyspace_list
Esempio n. 41
0
            p = subprocess.Popen(cmd)
            p.wait()
        intf = intf + 'mon'
        #intf =  'mon0'

    if args.gpstrack:    
        gpsp = GpsPoller() # create the thread
        try:
            gpsp.start() # start it up
            main(intf)
        except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
            print "\nKilling Thread..."
            gpsp.running = False
            gpsp.join() # wait for the thread to finish what it's doing
            sys.exit()
    else:
        try:
            main(intf)
        except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
            print "\nKilling Thread..."
            sys.close()
            sys.exit()

print '\n \033[31m%d \033[0mClients | \033[33m%d \033[0mAPs' % (Numclients, Numap)
# awk '!seen[$0]++' pta.log > pta.csv
# Below code actually tidys the export and can import strait into other formats (maltego + mapping)
outfile = args.output + '.csv'
print G + '\n Creating CSV: ' + W + outfile
with open(args.output, 'rb') as inf, open(outfile, 'wb') as outf:
    outf.writelines(collections.OrderedDict.fromkeys(inf))
print G + '\n Elapsed Time: ' + W + '%s' % (time.time() - start)
Esempio n. 42
0
  client = True
  #Main Program Loop
  while(client):

              
        events = pygame.event.get()
        if events:

          #returns a signal and event for triggered events 
          signal, event = EventControl.pollingInput(events)
        
        if signal:
              if( signal == 'quit'):
                s.close()
                pygame.exit()
                sys.close()

              elif( signal == 'reload'):
                  
                    from gui import *
                    screen = DropDisplay()        
                

              elif signal == 'erase':
                screen.erase_screen()

                #TODO: fix hard coding...error hiding is the devil
                try:
                  os.remove('/home/blackpanther/Desktop/sdlHacking/working/log/client.log')
                except:
                  pass
Esempio n. 43
0
def classify(train_list,test_list,parent_dir):

   index_list = {}

   # initialize matrix
   matrix = output.Matrix(map_list.index.keys())

   for i,c in enumerate(map_list.index.keys()):

       subdir = str(i+1) + '-vs-all/' 
       dir = parent_dir + subdir
       #check if sub directory already exists 
       if not os.path.exists(dir):
          os.makedirs(dir) 
       
       train = open(dir + 'train','w')
       index_list[i+1] = c
       mapf.write("%s %d\n" % (c,i+1))

       for t in train_list:
          if re.search(c,t.cls):
             gold_class = 1
          else:
             gold_class = -1
          train.write("%s %d %s\n" % (t.instance,gold_class,t.features))
       train.close()

       test = open(dir + 'test','w')
       for t in test_list:
          if re.search(c,t.cls):
             gold_class = 1
          else:
             gold_class = -1
          test.write("%s %d %s\n" % (t.instance,gold_class,t.features))
       test.close()

       #run train.txt
       call_mallet(dir)
       
       #create sys_output from test.stdout
       temp = open(dir + 'stdout','r')
       sys = open(dir + 'sys_output','w')
       for l in temp.readlines():
           m = re.match('^(\S+) (\-?\d) (\-?\d):(\S+) (\-?\d):(\S+)',l)
           if m:
              sys.write("%s %s %s %s %s %s\n" % \
              (m.group(1),m.group(2),m.group(3),m.group(4),m.group(5),m.group(6)))           
              #store test probability into each table
              for t in test_list: 
                 if t.instance == m.group(1):   
                    if m.group(3) != '-1': 
                       prob = m.group(4)
                    else:
                       prob = m.group(6)
                    t.probs[i+1] = prob 
       temp.close()
       sys.close()
 
   #assign class with highest probability
   for t in test_list: 
       final = sorted(t.probs.items(),key=lambda x:float(x[1]),reverse=True)   
       index = final[0][0]
       sys_class = index_list[index] 
       matrix.set_value(t.cls,sys_class,1) 
       #output
       final_sys.write("%s %s" %(t.instance,t.cls))
       for cls,prob in final:
          final_sys.write(" %s %s" %(index_list[cls],prob))
       final_sys.write('\n')
 
   return matrix
# print('\n', employees_data)
for a in employees_data:
    for b in a:
        if b[0] == '':
            b.clear()
# print('\n', employees_data)
for a in employees_data:
    b = a[4][0]
    e = b[:2]
    c = b[3:5]
    d = b[6:]
    if int(e) > 31 or int(c) > 12 or int(d) > 16 or (
            int(e) > 29 and int(c) == 2) or (int(e) == 31 and
                                             (int(c) == (4 or 6 or 9 or 11))):
        print("\nIncorrect joining date.")
        close()
    if int(d) + 30 != int(time.time() / (60 * 60 * 24 * 365)):
        a[5].append(8)
        a[18].append(24)
        a[6][0] = int(a[6][0])
        a[7].append(a[5][0] - a[6][0])
        a[19][0] = int(a[19][0])
        a[20].append(a[18][0] - a[19][0])
        a[9][0] = int(a[9][0])
        a[14][0] = int(a[14][0])
        if int(e) < 15:
            l = (((13 - int(c)) / 12.0) * 10.0)
            if l >= int(l) + 0.5:
                m = math.ceil(l)
            else:
                m = math.floor(l)
Esempio n. 45
0
import os
import sys
import pyNastran
import numpy

from pyNastran.bdf.bdf import BDF, read_bdf, CaseControlDeck

# ドロップされたファイルのパスを取得
# ドロップされていない場合は例外で落とす
try:
    path_dropped = sys.argv[1]
except IndexError:
    print('Inputファイルを直接Dropしてください! キーを押すと終了します...')
    input()
    sys.close(1)

# メッセージ
print("Inputファイルを確認しました。")
print(path_dropped)

# BDFでモデルを読み込む
model_input = BDF()
model_input.read_bdf(path_dropped)

print("GRID番号を入力してください。")
print("(例) 99000001,1,99000002,2,99000003,3")
nodelist = input().split(',')
#list_input_node = [99000001,1,99000002,2,99000003,3,99000004,4,99000005,5]

model_output = BDF()
pid_pbush = 99000000
Esempio n. 46
0
def handleData():
    dHandle.input = dHandle.input.split("||")
    if dHandle.input[0].strip() == "turnoff":
        if dHandle.getState("Auto") == 0:
            dHandle.invertState("Auto")
        if dHandle.getState("Lampe") == 1:
            dHandle.invertState("Lampe")
    elif dHandle.input[0].strip() != "none":
        if len(dHandle.input[0].split("  ")[0].split(" ")) > 1:
            dHandle.energystate = {
                int(partvalue.split(" ")[0]): int(partvalue.split(" ")[1])
                for partvalue in dHandle.input[0].split("  ")
                if partvalue != "" and partvalue != "0"
            }
        else:
            try:
                dHandle.energystate = int(dHandle.input[0].strip())
            except ValueError:
                sys.close()
    else:
        dHandle.energystate = 0
    log(str(dHandle.energystate), "handleData")
    if len(dHandle.input) > 1:
        for reply in dHandle.input[1:]:
            if reply == "request accepted":
                log("request was accepted", "handleData")
                dHandle.invertState(dHandle.openrequests[0][1])
                with open(
                        "/var/www/html/output/" + dHandle.openrequests[0][0] +
                        ".req", "w") as requestWrite:
                    requestWrite.write("request accepted")
                log("success", "handleData")
                if dHandle.openrequests[0][1] == "Auto":
                    autooff = th.Thread(target=auto_off)
                    autooff.start()
            elif reply == "request denied - Energy from battery?":
                with open(
                        "/var/www/html/output/" + dHandle.openrequests[0][0] +
                        ".req", "w") as requestWrite:
                    requestWrite.write("requestdeniedenergyproblemusebattery")
                if " ".join(dHandle.openrequests[0]
                            ) not in dHandle.openexternalrequests:
                    dHandle.openexternalrequests.append(" ".join(
                        dHandle.openrequests[0]))
            elif reply == "request denied - Energy from public power grid?":
                with open(
                        "/var/www/html/output/" + dHandle.openrequests[0][0] +
                        ".req", "w") as requestWrite:
                    requestWrite.write(
                        "request denied - Energy from public power grid?")
                if " ".join(dHandle.openrequests[0]
                            ) not in dHandle.openexternalrequests:
                    dHandle.openexternalrequests.append(" ".join(
                        dHandle.openrequests[0]))
            del dHandle.openrequests[0]
            dHandle.output[5] = "none"
    if len(dHandle.openexternalrequests) > 0 and dHandle.output[5] == "none":
        log("There are open external requests", "handleData")
        log(str(dHandle.openexternalrequests), "handleData")
        removeItem = []
        for request in dHandle.openexternalrequests:
            path = "/var/www/html/input/" + request + ".req"
            file = Path(path)
            if file.is_file():
                time.sleep(0.05)
                with open(path, "r") as readRequest:
                    if readRequest.readlines()[0] == "accepted":
                        dHandle.invertState(request.split(" ")[1])
                        dHandle.output[5] = request.split(" ")[1] + " accepted"
                        removeItem.append(request)
                        if request.split(" ")[1] == "Auto":
                            autooff = th.Thread(target=auto_off)
                            autooff.start()
                    else:
                        dHandle.output[5] = request.split(" ")[1] + " declined"
                        removeItem.append(request)
                command = "rm '" + path + "'"
                os.system(command)
        for item in removeItem:
            dHandle.openexternalrequests.remove(item)
Esempio n. 47
0
 def report(self):
     report=QtGui.QMessageBox.question(self,'sales report','sales report must be shown here',QtGui.QMessageBox.Cancel)
     if report==QtGui.QMessageBox.close:
         sys.close()
Esempio n. 48
0
def classify(train_list, test_list, parent_dir):

    index_list = {}

    # initialize matrix
    matrix = output.Matrix(map_list.index.keys())

    for i, c in enumerate(map_list.index.keys()):

        subdir = str(i + 1) + '-vs-all/'
        dir = parent_dir + subdir
        #check if sub directory already exists
        if not os.path.exists(dir):
            os.makedirs(dir)

        train = open(dir + 'train', 'w')
        index_list[i + 1] = c
        mapf.write("%s %d\n" % (c, i + 1))

        for t in train_list:
            if re.search(c, t.cls):
                gold_class = 1
            else:
                gold_class = -1
            train.write("%s %d %s\n" % (t.instance, gold_class, t.features))
        train.close()

        test = open(dir + 'test', 'w')
        for t in test_list:
            if re.search(c, t.cls):
                gold_class = 1
            else:
                gold_class = -1
            test.write("%s %d %s\n" % (t.instance, gold_class, t.features))
        test.close()

        #run train.txt
        call_mallet(dir)

        #create sys_output from test.stdout
        temp = open(dir + 'stdout', 'r')
        sys = open(dir + 'sys_output', 'w')
        for l in temp.readlines():
            m = re.match('^(\S+) (\-?\d) (\-?\d):(\S+) (\-?\d):(\S+)', l)
            if m:
                sys.write("%s %s %s %s %s %s\n" % \
                (m.group(1),m.group(2),m.group(3),m.group(4),m.group(5),m.group(6)))
                #store test probability into each table
                for t in test_list:
                    if t.instance == m.group(1):
                        if m.group(3) != '-1':
                            prob = m.group(4)
                        else:
                            prob = m.group(6)
                        t.probs[i + 1] = prob
        temp.close()
        sys.close()

    #assign class with highest probability
    for t in test_list:
        final = sorted(t.probs.items(),
                       key=lambda x: float(x[1]),
                       reverse=True)
        index = final[0][0]
        sys_class = index_list[index]
        matrix.set_value(t.cls, sys_class, 1)
        #output
        final_sys.write("%s %s" % (t.instance, t.cls))
        for cls, prob in final:
            final_sys.write(" %s %s" % (index_list[cls], prob))
        final_sys.write('\n')

    return matrix
Esempio n. 49
0
 def keyspace_get_list(self, machine_id):
     """Returns all keyspaces in form of list """
     sys = SystemManager(machine_id)
     keyspace_list = sys.list_keyspaces()
     sys.close()
     return keyspace_list
Esempio n. 50
0
def create_column_families():
    sys = pycassa.system_manager.SystemManager('esb-a-test.sensors.elex.be')
    #sys.create_keyspace('test', pycassa.system_manager.NETWORK_TOPOLOGY_STRATEGY, {'erfurt': '1', 'sensors': '1', 'sofia': '1', 'diegem': '1'})
    sys.create_column_family('test', 'INDEXCF', super=False, comparator_type=pycassa.system_manager.UTF8_TYPE)
    sys.create_column_family('test', 'DATACF', super=False, comparator_type=pycassa.system_manager.UTF8_TYPE)
    sys.close()