Example #1
0
    def __init__(self, id, name, capacity=1, \
                 processingTime=None, repairman='None',\
                 scrapQuantity={},
                 operatorPool='None',operationType='None',\
                 setupTime=None, loadTime=None,
                 canDeliverOnInterruption=False, 
                 technology=None,
                 **kw):
        if not processingTime:
          processingTime = {'distributionType': 'Fixed',
                            'mean': 1}
        # initialize using the default method of the object 
        Machine.__init__(self,id=id,name=name,\
                                    capacity=capacity,\
                                    processingTime=processingTime,
                                    repairman=repairman,
                                    canDeliverOnInterruption=canDeliverOnInterruption,
                                    operatorPool=operatorPool,operationType=operationType,\
                                    setupTime=setupTime, loadTime=loadTime,     
                                    technology=technology              
                                    )

        # set the attributes of the scrap quantity distribution
        if not scrapQuantity:
            scrapQuantity = {'Fixed':{'mean': 0}}
            
        self.scrapRng=RandomNumberGenerator(self, scrapQuantity)
        from Globals import G
        G.BatchScrapMachineList.append(self)
Example #2
0
 def initialize(self):
     Machine.initialize(self)
     # initiate the Broker responsible to control the request/release
     # initialize the operator pool if any
     if self.operatorPool != "None":
         self.operatorPool.initialize()
         self.broker = Broker(self)
         activate(self.broker, self.broker.run())
         for operator in self.operatorPool.operators:
             operator.coreObjectIds.append(self.id)
             operator.coreObjects.append(self)
     # the time that the machine started/ended its wait for the operator
     self.timeWaitForOperatorStarted = 0
     self.timeWaitForOperatorEnded = 0
     self.totalTimeWaitingForOperator = 0
     # the time that the machine started/ended its wait for the operator
     self.timeWaitForLoadOperatorStarted = 0
     self.timeWaitForLoadOperatorEnded = 0
     self.totalTimeWaitingForLoadOperator = 0
     # the time that the operator started/ended loading the machine
     self.timeLoadStarted = 0
     self.timeLoadEnded = 0
     self.totalLoadTime = 0
     # the time that the operator started/ended setting-up the machine
     self.timeSetupStarted = 0
     self.timeSetupEnded = 0
     self.totalSetupTime = 0
     # Current entity load/setup/loadOperatorwait/operatorWait related times
     self.operatorWaitTimeCurrentEntity = 0  # holds the time that the machine was waiting for the operator
     self.loadOperatorWaitTimeCurrentEntity = 0  # holds the time that the machine waits for operator to load the it
     self.loadTimeCurrentEntity = 0  # holds the time to load the current entity
     self.setupTimeCurrentEntity = 0  # holds the time to setup the machine before processing the current entity
Example #3
0
    def GetMachines(self):
        machines_file = self.alternative_machines_file
        if machines_file == "":
            machines_file = HeeksCNC.heekscnc_path + "/nc/machines2.txt"

        print "machines_file = ", machines_file

        f = open(machines_file)

        machines = []

        while True:
            line = f.readline()
            if len(line) == 0:
                break
            line = line.rstrip("\n")

            machine = Machine()
            space_pos = line.find(" ")
            if space_pos == -1:
                machine.file_name = line
                machine.description = line
            else:
                machine.file_name = str(line)[0:space_pos]
                machine.description = line[space_pos:]
            machines.append(machine)

        return machines
Example #4
0
    def __init__(self, id, name, capacity=1, processingTime=None,
                  failureDistribution='No', MTTF=0, MTTR=0, availability=0, repairman='None',\
                  operatorPool='None',operationType='None',
                  setupTime=None, loadTime=None):
        Machine.__init__(self, id, name, capacity=capacity,
                         processingTime=processingTime,
                         failureDistribution=failureDistribution, MTTF=MTTF,
                         MTTR=MTTR, availability=availability,
                         repairman=repairman, operatorPool=operatorPool,
                         operationType=operationType, setupTime=setupTime,
                         loadTime=loadTime,)

        # type of the machine
        self.type = "OperatedMachine"
        # sets the operator resource of the Machine
        #     check if the operatorPool is a List or a OperatorPool type Object
        #     if it is a list then initiate a OperatorPool type object containing
        #     the list of operators provided
        '''
            change! if the  list is empty create operator pool with empty list
        '''
        if (type(operatorPool) is list): #and len(operatorPool)>0:
            id = id+'_OP'
            name=self.objName+'_operatorPool'
            self.operatorPool=OperatorPool(id, name, operatorsList=operatorPool)
        else:
            self.operatorPool=operatorPool
        # update the operatorPool coreObjects list
        if self.operatorPool!='None':
            self.operatorPool.coreObjectIds.append(self.id)
            self.operatorPool.coreObjects.append(self)
        # holds the Operator currently processing the Machine
        self.currentOperator=None
        # define if load/setup/removal/processing are performed by the operator 
        self.operationType=operationType
        # boolean to check weather the machine is being operated
        self.toBeOperated = False

        # examine if there are multiple operation types performed by the operator
        #     there can be Setup/Processing operationType
        #     or the combination of both (MT-Load-Setup-Processing) 
        self.multOperationTypeList=[]   
        if self.operationType.startswith("MT"):
            OTlist = operationType.split('-')
            self.operationType=OTlist.pop(0)
            self.multOperationTypeList = OTlist
        else:
            self.multOperationTypeList.append(self.operationType)
        #     lists to hold statistics of multiple runs
        self.WaitingForOperator=[]
        self.WaitingForLoadOperator=[]
        self.Loading = []
        self.SettingUp =[]
Example #5
0
def main():
    argc = len(sys.argv)
    if argc == 1 or argc > 3:
        usage()
    if argc == 2 and sys.argv == '-d':
        usage()
    if sys.argv[1] == '-d':
        DEBUG = True
        code_file = sys.argv[2]
    else:
        code_file = sys.argv[1]
    machine = Machine(code_file, DEBUG)
    ticks = machine.run()
    print("Program completed in %d ticks" % ticks)
Example #6
0
 def removeEntity(self, entity=None):
     activeEntity = Machine.removeEntity(self, entity)
     scrapQuantity=self.scrapRng.generateNumber()  
     activeEntity.numberOfUnits-=int(scrapQuantity)  # the scrapQuantity should be integer at whatever case
     if activeEntity.numberOfUnits<0:
         activeEntity.numberOfUnits==0
     return activeEntity
Example #7
0
 def getEntity(self):
     activeObject=self.getActiveObject()
     activeEntity=Machine.getEntity(self)     #run the default code
     
     # read the processing/setup/load times from the corresponding remainingRoute entry
     processingTime=activeEntity.remainingRoute[0].get('processingTime',{})
     self.distType=processingTime.get('distributionType','Fixed')
     self.procTime=float(processingTime.get('mean', 0))
     
     setupTime=activeEntity.remainingRoute[0].get('setupTime',{})
     self.distType=setupTime.get('distributionType','Fixed')
     self.setupTime=float(setupTime.get('mean', 0))
     
     import Globals
     # read the list of next stations
     nextObjectIds=activeEntity.remainingRoute[1].get('stationIdsList',[])
     nextObjects = []
     for nextObjectId in nextObjectIds:
         nextObject=Globals.findObjectById(nextObjectId)
         nextObjects.append(nextObject)
     # update the next list of the object
     for nextObject in nextObjects:
         # append only if not already in the list
         if nextObject not in activeObject.next:
             activeObject.next.append(nextObject)
     removedStep = activeEntity.remainingRoute.pop(0)      #remove data from the remaining route of the entity
     return activeEntity  
Example #8
0
 def getEntity(self):
     activeObject=self.getActiveObject()
     activeEntity=Machine.getEntity(self)     #run the default code
     # read the processing time from the corresponding remainingRoute entry
     processingTime=activeEntity.remainingRoute[0].get('processingTime',{})
     processingTime=self.getOperationTime(processingTime)
     self.rng=RandomNumberGenerator(self, processingTime)
     self.procTime=self.rng.generateNumber()
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Processing',entity=activeEntity)
     # read the setup time from the corresponding remainingRoute entry
     setupTime=activeEntity.remainingRoute[0].get('setupTime',{})
     setupTime=self.getOperationTime(setupTime)
     self.stpRng=RandomNumberGenerator(self, setupTime)
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Setup',entity=activeEntity)
     activeEntity.currentStep = activeEntity.remainingRoute.pop(0)      #remove data from the remaining route of the entity
     if activeEntity.currentStep:
         # update the task_id of the currentStep dict within the schedule
         try:
             activeEntity.schedule[-1]["task_id"] = activeEntity.currentStep["task_id"]
             # if there is currentOperator then update the taskId of corresponding step of their schedule according to the task_id of the currentStep
             if self.currentOperator:
                 self.currentOperator.schedule[-1]["task_id"] = activeEntity.currentStep["task_id"]
         except KeyError:
             pass
     return activeEntity
Example #9
0
 def canAcceptAndIsRequested(self,callerObject):
     giverObject=callerObject
     assert giverObject, 'there must be a caller for canAcceptAndIsRequested'
     if self.isInRouteOf(giverObject):
         if Machine.canAcceptAndIsRequested(self,giverObject):
             self.readLoadTime(giverObject)
             return True
     return False
Example #10
0
    def __init__(self, id, name, capacity=1, \
                 processingTime=None, repairman='None',\
                 scrapQuantity={}, **kw):
        if not processingTime:
          processingTime = {'distributionType': 'Fixed',
                            'mean': 1}
        # initialize using the default method of the object 
        Machine.__init__(self,id=id,name=name,\
                                    capacity=capacity,\
                                    processingTime=processingTime,
                                    repairman=repairman)

        # set the attributes of the scrap quantity distribution
        if not scrapQuantity:
            scrapQuantity = {'distributionType': 'Fixed',
                            'mean': 0}
            
        self.scrapRng=RandomNumberGenerator(self, **scrapQuantity)
        from Globals import G
        G.BatchScrapMachineList.append(self)
Example #11
0
 def removeEntity(self, entity=None):
     receiverObject=self.receiver  
     activeEntity=Machine.removeEntity(self, entity)         #run the default method  
     removeReceiver=True 
     # search in the internalQ. If an entity has the same receiver do not remove
     for ent in self.Res.users:
         nextObjectIds=ent.remainingRoute[0].get('stationIdsList',[])
         if receiverObject.id in nextObjectIds:
             removeReceiver=False      
     # if not entity had the same receiver then the receiver will be removed    
     if removeReceiver:
         self.next.remove(receiverObject)
     return activeEntity
Example #12
0
 def getEntity(self):
     activeObject=self.getActiveObject()
     activeEntity=Machine.getEntity(self)     #run the default code
     
     # read the processing/setup/load times from the corresponding remainingRoute entry
     processingTime=activeEntity.remainingRoute[0].get('processingTime',{})
     self.distType=processingTime.get('distributionType','Fixed')
     self.procTime=float(processingTime.get('mean', 0))
     
     setupTime=activeEntity.remainingRoute[0].get('setupTime',{})
     self.distType=setupTime.get('distributionType','Fixed')
     self.setupTime=float(setupTime.get('mean', 0))
     removedStep = activeEntity.remainingRoute.pop(0)      #remove data from the remaining route of the entity
     return activeEntity
Example #13
0
 def getEntity(self):
     activeObject=self.getActiveObject()
     activeEntity=Machine.getEntity(self)     #run the default code
     
     # read the processing/setup/load times from the corresponding remainingRoute entry
     processingTime=activeEntity.remainingRoute[0].get('processingTime',{})
     processingTime=self.getProcessingTime(processingTime)
     self.rng=RandomNumberGenerator(self, **processingTime)
     self.procTime=self.rng.generateNumber()
     
     setupTime=activeEntity.remainingRoute[0].get('setupTime',{})
     setupTime=self.getSetupTime(setupTime)
     self.stpRng=RandomNumberGenerator(self, **setupTime)
     
     removedStep = activeEntity.remainingRoute.pop(0)      #remove data from the remaining route of the entity
     return activeEntity
Example #14
0
from Salle import Salle
from Batiment import Batiment
from Machine import Machine

m1 = Machine("gle-paicvbn", 123, 0.6, 1, False, 0.4)
m2 = Machine("gode", 456, 0.1, 2, True, 0.2)
s1 = Salle("piscine", [m1, m2])
b1 = Batiment([s1])
print(b1)
print(m1.modifierEtatActuel(0.5))
m2.modifierEtatActuel(0)
print(b1)
Example #15
0
import logging
from AccountDAO_DB import AccountMongoDBService
from authorization import Authorization
from AccountOps import AccountOperations
from Machine import Machine
from SessionTimer import SessionTimer

logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    filename='runtime.log',
    level=logging.DEBUG)
logger = logging.getLogger("main")

#All service initializations
machine = Machine("10000")
data_svc = AccountMongoDBService()
auth_svc = Authorization(data_svc)
ops_svc = AccountOperations(data_svc, auth_svc, machine)


def call(func, args):
    func(args)


def start():

    SESSION_TIMEOUT = 120  #session length is 2 minutes.
    session_timer = None
    """entrypoint to atm demo.  Initializes services and begins the main program loop"""

    #Main loop
Example #16
0
#file des pieces a usiner pour la machine 2
queueM2 = Queue.Queue()
#file des pieces a ranger pour le robot
queueR = Queue.Queue()

#entrepots 
listeA = []
listeB = []
listeC = []

#lancement du robot
Rob = Robot(queueR,listeA, listeB, listeC,tempsRA,tempsRB,tempsRC, n_param)
Rob.start()

#lancement de la machine 1
M1 = Machine(1,["A","B"],queueM1,queueM2,queueR,tempsM1a, tempsM1b,0,Rob, dock_only)
M1.start()

#lancement de la machine 2
M2 = Machine(2,["B","C"],queueM2,queueM1,queueR,0,tempsM2b,tempsM2c,Rob,dock_only)
M2.start()

#---------Lancement de la generation de pieces---------

print("GENERATION LANCEE !")
gen = GenerateurObjet.GenerateurObjet(queueM1, queueM2, "Generateur", n_param, tempsGen, M1,M2,dock_only)
gen.start()

#enregistrement de la date de debut de fabrication
chronoDeb = time.time()
Example #17
0
def generateGcodeParallel(segmentGroups, outputFile, tolerance): # not used

	m = Machine()


	config = segmentGroups[0].operationConfig
	# Machine Settings
	safetyHeight = config['safetyHeight']	 # mm
	feedRate = config['feedRate']	 # mm/min
	plungeRate = config['plungeRate']	 # mm/min
	stepSize = config['stepSize']	 # mm
	targetDepth = config['targetDepth']	 # mm
	

	workingHeight = -stepSize

	
	m.setFeedrate(feedRate, feedRate,  plungeRate)
		
	
	workingHeight = 0
	while workingHeight > targetDepth:
		
		workingHeight = workingHeight - stepSize
		if workingHeight < targetDepth:
			workingHeight = targetDepth
	
	
		m.moveZ(safetyHeight)
		
			
		for segmentGroup in segmentGroups:
			
			curvePoints = segmentGroup.newCurvePoints
			
			if len(curvePoints) > 0:
				startPos = curvePoints[0]
	
				if distance( m.currentPos(), startPos) > tolerance :
					m.moveZ(safetyHeight)
	
				m.move(startPos)
				m.moveZ(workingHeight)
	
				
				for curvePoint in curvePoints:
					#line optimization
					
					m.move(curvePoint)
				
	
	m.moveZ(safetyHeight)

	gcode = m.getGcode()

	with open(outputFile, "w+") as outfile:
		outfile.write(gcode)

	print "Outputfile written !"
Example #18
0
    def __init__(self, nr_machines, policy, list_thresholds, list_lambdas,
                 list_alphas, list_betas, list_preventative_times,
                 list_corrective_times, list_preventative_costs,
                 list_corrective_costs, list_downtime_costs, list_travel_times,
                 dependency, warm_up_time):

        self.nr_machines = nr_machines
        self.policy = policy
        self.thresholds = list_thresholds

        # Both base lambdas and lambda's with dependency are created
        # If there is no dependency lambda's with dependency is equal to base lambdas and don't change during the simulation
        self.lambdas = list_lambdas.copy()
        self.dependency_lambdas = list_lambdas.copy()

        self.alphas = list_alphas
        self.betas = list_betas
        self.preventative_times = list_preventative_times
        self.corrective_times = list_corrective_times
        self.preventative_costs = list_preventative_costs
        self.corrective_costs = list_corrective_costs
        self.downtime_costs = list_downtime_costs
        self.travel_times = list_travel_times
        self.dependency = dependency

        self.machines = []

        # Initializing arrays/lists that will be used for calculating output variables

        # Stores total non-operational time for each machine during the whole simulation
        self.non_operational_times = np.zeros(nr_machines)

        # Stores response times for each machine during the whole simulation
        self.response_times = [[] for i in range(nr_machines)]

        # Stores total maintenance(preventive and corrective) costs for each machine during the whole simulation
        self.maintenance_costs = np.zeros(nr_machines)

        # Stores total downtime costs for each machine during the whole simulation
        self.total_downtime_costs = np.zeros(nr_machines)

        # Initializing time-stamped output variables that are going to be used in plotting
        self.maintenance_costs_stamped = [[] for i in range(nr_machines)]
        self.non_operational_times_stamped = [[] for i in range(nr_machines)]

        # Array to record most recent non operational starting time
        # (Either because of a failure or because of a start of the preventative maintenance)
        self.last_non_operational_times = np.zeros(nr_machines)

        # Initializing additional stats

        # Initializing a list that stores interarrival times of degradation events for each machine
        self.interarrivals = [[] for i in range(nr_machines)]

        # Stats to keep track of wasted or not wasted FSE travels
        self.correct_tour = []
        self.detour = []

        # Statistic to keep track of remaining degradation levels to failure at each decision point
        self.remaining_times = []

        # Statistic to keep track of remaining degradation levels to failure at each decision point
        self.number_of_repairs = np.zeros(nr_machines)

        # Statistic to keep track of jump sizes for each machine
        self.jump_sizes = [[] for i in range(nr_machines)]

        # Statistic to keep track of the last start of idle,travel,repair time for FSE
        self.last_idle_time = 0
        self.last_travel_time = 0
        self.last_repair_time = 0

        # Statistic to keep track of the total idle,travel,repair time for FSE
        self.total_idle_time = 0
        self.total_travel_time = 0
        self.total_repair_time = 0

        # Statistic to keep track of the total number of failed machines at each decision point
        self.failed_count = []

        # Statistic to keep track of the total number of skipped degradation events because of start of a repair on that machine
        self.removed_event_count = 0

        # Time statistics
        self.current_time = 0
        self.warm_up_time = warm_up_time  # Until the warm-up time is reached the output variables are not updated

        # Initializing the field service engineer
        self.fse = FSE()

        # Initializing FES to store all events
        self.fes = FES()

        for machine in range(nr_machines):

            # Adding the machines with their respective attributes to the list
            self.machines.append(
                Machine(machine, list_thresholds[machine],
                        list_lambdas[machine], list_alphas[machine],
                        list_betas[machine], list_preventative_times[machine],
                        list_corrective_times[machine],
                        list_preventative_costs[machine],
                        list_corrective_costs[machine],
                        list_downtime_costs[machine]))

            # Scheduling the first degradation for each machine
            self.schedule_degradation(machine)
Example #19
0
 def initialize(self):
     from Globals import G
     self.previous=G.ObjList
     self.next=[]
     Machine.initialize(self)    #run default behaviour
Example #20
0
from SimPy.Simulation import now, activate, simulate, infinity, initialize
from EventGenerator import EventGenerator
from Machine import Machine
from Source import Source
from Exit import Exit
from Part import Part
from Queue import Queue
from Globals import G
import ExcelHandler
import Globals

G.trace = "Yes"

S = Source('S1', 'Source', mean=1, item=Part)
M1 = Machine('M1', 'Machine1', mean=0.75)
Q1 = Queue('Q1', 'Queue1', capacity=infinity)
M2 = Machine('M2', 'Machine2', mean=0.75)
Q2 = Queue('Q2', 'Queue2', capacity=infinity)
E = Exit('E1', 'Exit')

#define predecessors and successors for the objects
S.defineRouting([M1])
M1.defineRouting([S], [Q1])
Q1.defineRouting([M1], [M2])
M2.defineRouting([Q1], [Q2])
Q2.defineRouting([M2])

argumentDict = {'from': 'Q2', 'to': 'E1', 'safetyStock': 70, 'consumption': 20}
EG = EventGenerator(id="EV",
                    name="ExcessEntitiesMover",
Example #21
0
    def __setMachineList__(self):
        # Command Line Interface

        while True:
            print("\n\nSetting up slave machines.")
            print("----------Menu------------")
            print("d) Use default setting.")
            print("a) Add a new machine")
            print("v) View current Machine List")
            print("r) Remove Machine")
            print("q) Finish")

            cmd = input("What's your command ?  ")

            if cmd == 'd':
                print("\nThis is the default setting.")
                print("Name:localhost, IP:127.0.0.1, Port:9487")
                print("Name:slave1, IP:192.168.249.141, Port:9487")
                print("Name:slave2, IP:192.168.249.142, Port:9487")
                print("Name:slave3, IP:192.168.249.143, Port:9487")

                cmd = input("Confirm? y/n  ")
                if cmd == "y":
                    self.addMachine(
                        Machine("slave1", "192.168.249.141", "9487"))
                    self.addMachine(
                        Machine("slave2", "192.168.249.142", "9487"))
                    self.addMachine(
                        Machine("slave3", "192.168.249.143", "9487"))
                else:
                    print("Back to menu")

            elif cmd == 'a':
                while True:
                    print("\nAdd a machine")
                    name = input("Enter the name of the machine:  ")

                    while name == "q":
                        print("This is an illegal name. Try another.")
                        name = input("Enter the name of the machine:  ")

                    ip = input("Enter the ip address of the machine:  ")
                    port = input("Enter the port of the machine:  ")

                    print("\nName:" + name + ", IP:" + ip + ", Port:" + port)
                    cmd = input("Confirm? y/n  ")
                    if cmd == "y":
                        print("Input Accepted")
                        self.addMachine(Machine(name, ip, port))
                        break
                    else:
                        cmd = input("Re-entering or quit? r/q  ")
                        if cmd == "r":
                            pass
                        else:
                            break
            elif cmd == 'v':
                machines = self.__sqlDB.execute(
                    'SELECT name, ip FROM machine_list')
                for machine in machines:
                    print(machine)
            elif cmd == 'r':
                while True:

                    machines = self.__sqlDB.execute(
                        'SELECT name, ip FROM machine_list')
                    for machine in machines:
                        print(machine)
                    # end of for-loop

                    name = input(
                        'Enter the machine name to remove it or input q to quit  '
                    )
                    if name == 'q':
                        break
                    else:
                        pass

                    try:
                        self.__sqlDB.execute(
                            'DELETE from machine_list where name = ?',
                            (name, ))
                        self.__sqlDB.commit()
                    except sqlite3.Error as e:
                        print(e.args[0])
                # end of while-loop

            elif cmd == 'q':
                break
            else:
                print("\nIllegal command:" + cmd)

            # reload
            rows = self.__sqlDB.execute(
                'SELECT name, ip, content FROM machine_list')
            for row in rows:
                machine = self.__sqlContentToObject(row[2])
                self.__machineTable_name[row[0]] = machine
                self.__machineTable_ip[row[1]] = row[0]
                self.__machineList.append(machine)
Example #22
0
	def _getMachine(self):
		from Machine import Machine
		dval = self.d["values"]
		m = Machine(dval["name"],dval["hostname"], dval["user"])
		m.setPassword(dval["password"], encode = False)
		self.obj = m
Example #23
0
    def __setMachineList(self, __debug):
        # Command Line Interface

        if __debug in ['True', 'true']:
            while True:
                print("\n\nSetting up slave machines.")
                print("----------Menu------------")
                print("a) Add a new machine")
                print("v) View current Machine List")
                print("r) Remove Machine")
                print("q) Finish")

                cmd = input("What's your command ?  ")
                if cmd == 'a':
                    while True:
                        print("\nAdd a machine")
                        name = input("Enter the name of the machine:  ")

                        while name == "q":
                            print("This is an illegal name. Try another.")
                            name = input("Enter the name of the machine:  ")

                        ip = input("Enter the ip address of the machine:  ")
                        port = input("Enter the port of the machine:  ")

                        print("\nName:" + name + ", IP:" + ip + ", Port:" +
                              port)
                        cmd = input("Confirm? y/n  ")
                        if cmd == "y":
                            print("Input Accepted")
                            self.addMachine(Machine(name, ip, port))
                            break
                        else:
                            cmd = input("Re-entering or quit? r/q  ")
                            if cmd == "r":
                                pass
                            else:
                                break
                elif cmd == 'v':
                    machines = self.__sqlDB.execute(
                        'SELECT name, ip FROM machine_list')
                    for machine in machines:
                        print(machine)
                elif cmd == 'r':
                    while True:

                        machines = self.__sqlDB.execute(
                            'SELECT name, ip FROM machine_list')
                        for machine in machines:
                            print(machine)
                        # end of for-loop

                        name = input(
                            'Enter the machine name to remove it or input q to quit  '
                        )
                        if name == 'q':
                            break
                        else:
                            pass

                        try:
                            self.__sqlDB.execute(
                                'DELETE from machine_list where name = ?',
                                (name, ))
                            self.__sqlDB.commit()
                        except sqlite3.Error as e:
                            print(e.args[0])
                    # end of while-loop

                elif cmd == 'q':
                    break
                else:
                    print("\nIllegal command:" + cmd)
        else:
            pass

        # reload
        rows = self.__sqlDB.execute(
            'SELECT name, ip, content FROM machine_list')

        self.__machineTable_name.clear()
        self.__machineTable_ip.clear()
        self.__machineList.clear()
        self.__machineNameList.clear()

        for row in rows:
            machine = self.__sqlContentToObject(row[2])
            self.__machineTable_name[row[0]] = machine
            self.__machineTable_ip[row[1]] = row[0]
            self.__machineList.append(machine)
            self.__machineNameList.append(machine.getName())
from Machine import Machine
from IOManager import read_instruction

machine = Machine()

# 向内存中写入原始数据
store_place = 0
num_list = input('---------Data---------\n~$')
num_list = num_list.split(',')
for i in num_list:
    machine.memory.write(store_place, 0x00 + int(i), 1)
    store_place = store_place + 1

print('---------Code---------')
# 向内存中写入原始指令
instruction_store_place = store_place
machine.cpu.setPC(instruction_store_place)
instruction = read_instruction()
while instruction:
    machine.memory.write(instruction_store_place, instruction, 4)
    instruction_store_place = instruction_store_place + 4
    instruction = read_instruction()

print('---------TestData---------')
for i in range(store_place):
    print('0x%02x' % machine.memory.read(0x00000000 + i, 1), end=' ')
    if i % 16 == 15:
        print()
print()
print('---------TestCode---------')
for i in range(store_place, instruction_store_place, 4):
Example #25
0
from Machine import Machine

if __name__ == "__main__":
    machina = Machine()
    machina.initialise(20)
    try:
        while True:
            machina.cycle()
            print(machina)
            input()
    except KeyboardInterrupt:
        del machina
Example #26
0
 def canAcceptAndIsRequested(self):
     if Machine.canAcceptAndIsRequested(self):
         self.readLoadTime()
         return True
     return False
Example #27
0
 def __init__(self, text=None, dynamic=False, **kw):
     Machine.__init__(self, text, dynamic, **kw)
     self.EXCLUDE = ["PUSH", "POP"]
Example #28
0
from SimPy.Simulation import now, activate,simulate, infinity,initialize
from EventGenerator import EventGenerator
from Machine import Machine
from Source import Source
from Exit import Exit
from Part import Part
from Queue import Queue
from Globals import G
import ExcelHandler
import Globals


G.trace="Yes"           
            
S=Source('S1','Source', mean=1, item=Part)
M1=Machine('M1','Machine1', mean=0.75)
Q1=Queue('Q1','Queue1',capacity=infinity)
M2=Machine('M2','Machine2', mean=0.75)
Q2=Queue('Q2','Queue2',capacity=infinity)
E=Exit('E1','Exit')  

#define predecessors and successors for the objects    
S.defineRouting([M1])
M1.defineRouting([S],[Q1])
Q1.defineRouting([M1],[M2])
M2.defineRouting([Q1],[Q2])
Q2.defineRouting([M2])

argumentDict={'from':'Q2','to':'E1','safetyStock':70,'consumption':20}
EG=EventGenerator(id="EV", name="ExcessEntitiesMover" ,start=60, interval=60, method=Globals.moveExcess, argumentDict=argumentDict)
G.ObjList=[S,M1,M2,E,Q1,Q2,EG]
Example #29
0
parser.add_argument(
    "fqdn", help="The chosen Fully Qualified Domain Name for the server.")
parser.add_argument("rack_id",
                    help="The ID of the rack the machine is installed in.",
                    type=int)
parser.add_argument(
    "rack_row",
    help="The lowest row of the rack the machine is installed in.",
    type=int)
parser.add_argument("machine_size",
                    help="The height of the machine in rows.",
                    type=int)
parser.add_argument("username", help="The username for the server.")
args = parser.parse_args()

newMachine = Machine(str(args.ip))
newMachine.rack = str(args.rack_id)
newMachine.position = str(args.rack_row)
newMachine.units = str(args.machine_size)

print("""
 _____         _____ _     _
|     |___ ___|   __|_|___| |_
| | | | .'| . |   __| |_ -|   |
|_|_|_|__,|_  |__|  |_|___|_|_|
          |___|
""")

RequestURL.ADDRESS = newMachine.ip

print("Checking Initial Connection and Authenticating...")
Example #30
0
def main():
    regex_for_ip = r'(?:[0-254]){4}'
    machine1 = Machine()
    machine1.print_interface_list()
Example #31
0
    def __init__(self):
        self.__machines = []

        self.mcDal = MachineDal()

        for machineDoc in self.mcDal.getAllMachines():

            crd = Credentials(
                machineDoc["credentials"]["user"],
                machineDoc["credentials"]["password"],
                machineDoc["credentials"]["domain"])

            tmpMc = Machine(machineDoc["hostaddr"], crd)

            tmpMc.setDescription(machineDoc["description"])

            tmpMc.osType = machineDoc["osType"]
            tmpMc.osRelease = machineDoc["osRelease"]

            for port in machineDoc["ports"]:
                tmpMc.addPort(port)

            services = machineDoc["services"]

            for service in services.keys():
                tmpMc.addService(service, services[service])

            configs = machineDoc["configs"]

            for configKey in configs.keys():
                key = configs[configKey][0]
                value = configs[configKey][1]
                tmpMc.addConfigFile(configKey, key, value)

            self.__machines.append(tmpMc)
Example #32
0
job_dict_inner = {}
machine_dict_inner = {}
for i in range(len(sched_job_list)):
    job_dict_inner[i] = Job(sched_job_list[i][0], sched_job_list[i][1],
                            sched_job_list[i][2], sched_job_list[i][3],
                            sched_job_list[i][4], None, None, None)

i = 0
# load from machine_events .csv file
with open(
        'C:\\Users\\aarti\\PycharmProjects\\CCBD_ML\\another try\\machine_events .csv',
        'rb') as csvfile:
    data_reader = csv.reader(csvfile, delimiter=',')
    next(data_reader)
    for row in data_reader:
        machine_dict_inner[i] = Machine(float(row[0]), float(row[1]),
                                        float(row[2]), None, None)
        i = i + 1
# for jobs
jobc_obj = {}
machinec_obj = {}

for i in job_dict.keys():
    for j in job_dict[i]:
        if (i not in jobc_obj.keys()):
            job_dict_inner[j].setClusterNumber(i)
            jobc_obj[i] = [job_dict_inner[j]]
        else:
            job_dict_inner[j].setClusterNumber(i)
            jobc_obj[i].append(job_dict_inner[j])

for i in machine_dict.keys():
Example #33
0
class Account(KBEngine.Proxy):
	def __init__(self):

		KBEngine.Proxy.__init__(self)
		self.money
		self.barNum
		self.sevenNum
		self.starNum
		self.watermelonNum
		self.bellNum
		self.snakemelonNum
		self.orangeNum
		self.appleNum
		self.winScore
		self.resultItem = ''
		self.betPaid
		self.bigSmall = 0
		self.machine = Machine()

	def lessMoney(self, money):
		if money >= 0 and self.money >= money:
			self.money -= money
		else:
			raise ValueError("輸入金額錯誤")

	def addMoney(self, money):
		if money >= 0:
			self.money += money
		else:
			raise ValueError("輸入金額錯誤")

	def depositOne(self):
		ERROR_MSG('depositOne called: '+str(self.money))
		self.addMoney(1000)

	def depositTwo(self):
		ERROR_MSG('depositTwo called: '+str(self.money))
		self.addMoney(2000)

	def pressBarButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.barNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.barNum += 1

	def pressSevenButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.sevenNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.sevenNum += 1

	def pressStarButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.starNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.starNum += 1

	def pressWatermelonButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.watermelonNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.watermelonNum += 1

	def pressBellButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.bellNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.bellNum += 1

	def pressSnakemelonButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.snakemelonNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.snakemelonNum += 1

	def pressOrangeButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.orangeNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.orangeNum += 1

	def pressAppleButton(self):
		self._clearBeforePress()
		if self.winScore == 0 and self.money >=5 and self.appleNum<99:
			self.lessMoney(5)
			self.betPaid += 5
			self.appleNum += 1

	def pressWinScoreToMoneyButton(self):
		self._clearBeforePress()
		if self.winScore >0:
			self.addMoney(self.winScore)
			self.winScore = 0

	def pressStartButton(self):
		self._clearBeforePress()
		self.machine.start(self)

	def pressBigButton(self):
		self._clearBeforePress()
		if self.winScore >0:
			self.bigSmall = 2
			self.machine.bet_big_small(self)

	def pressSmallButton(self):
		self._clearBeforePress()
		if self.winScore >0:
			self.bigSmall = 1
			self.machine.bet_big_small(self)

	def pressClearButton(self):
		self._clearBeforePress()
		self.barNum = 0
		self.sevenNum = 0
		self.starNum = 0
		self.watermelonNum = 0
		self.bellNum = 0
		self.snakemelonNum = 0
		self.orangeNum = 0
		self.appleNum = 0
		self.addMoney(self.betPaid)
		self.betPaid = 0

	def _clearBeforePress(self):
		self.resultItem = ''
		self.bigSmall = 0

	def getAccountInfo(self):
		accountInfo = {'money':self.money, 'barNum':self.barNum, 'sevenNum':self.sevenNum, 'starNum':self.starNum,
						'watermelonNum':self.watermelonNum, 'bellNum':self.bellNum,'snakemelonNum':self.snakemelonNum,
						'orangeNum':self.orangeNum, 'appleNum':self.appleNum, 'winScore':self.winScore,
						'resultItem':self.resultItem, 'bigSmall':self.bigSmall}
		self.writeToDB()
		self.client.onGetAccountInfo(accountInfo)

	def onTimer(self, id, userArg):
		"""
		KBEngine method.
		使用addTimer后, 当时间到达则该接口被调用
		@param id		: addTimer 的返回值ID
		@param userArg	: addTimer 最后一个参数所给入的数据
		"""
		DEBUG_MSG(id, userArg)

	def onEntitiesEnabled(self):
		"""
		KBEngine method.
		该entity被正式激活为可使用, 此时entity已经建立了client对应实体, 可以在此创建它的
		cell部分。
		"""
		INFO_MSG("account[%i] entities enable. mailbox:%s" % (self.id, self.client))

	def onLogOnAttempt(self, ip, port, password):
		"""
		KBEngine method.
		客户端登陆失败时会回调到这里
		"""
		INFO_MSG(ip, port, password)
		return KBEngine.LOG_ON_ACCEPT

	def onClientDeath(self):
		"""
		KBEngine method.
		客户端对应实体已经销毁
		"""
		DEBUG_MSG("Account[%i].onClientDeath:" % self.id)
		self.destroy()