Exemple #1
0
  def __init__( self, parsetFilename, partition, testname ):
    self.partition = partition
    self.testname = testname

    # configure the correlator before the parsets are added such that they will use the right paths
    testfilename = self.testname

    for c in " :":
      testfilename = testfilename.replace(c,"_")

    self.logdir = "%s/%s" % (Locations.files["logdir"],testfilename)

    self.results = {
      "started":    False,
      "terminated": False,
      "logdir":     self.logdir,
    }

    self.parset = Parset()
    self.olapparset_filename = "%s/OLAP.parset" % (Locations.files["configdir"],)
    self.rtcpparset_filename = parsetFilename

    for f in [self.olapparset_filename, self.rtcpparset_filename]:
      self.parset.readFile( Locations.resolvePath( f ) )
Exemple #2
0
    def __init__(self, no_of_lives=4, score=0):

        #Setup some Game constants
        self.GAME_LENGTH = 60000.0  # 60 seconds
        self.GAME_TIME_BONUS = 1000  #maximum points available as time bonus points
        self.FLY_POINTS = 100
        self.HOME_POINTS = 250
        self.MOVE_POINTS = 10

        #Create frogs and other objects and package them in lists
        frog_x_positions = [x * 50 for x in range(no_of_lives)]
        self.frogs = [
            Moveable(x, 430, 'data/frog.png', 'data/splat.png', 0)
            for x in frog_x_positions
        ]
        self.frog = self.frogs[0]
        self.frog.x, self.frog.y = 305, 405

        cars = [
            Moveable(x, 300, 'data/car.png', None, 3)
            for x in range(0, 640, 213)
        ]
        lorries = [
            Moveable(x, 350, 'data/blue-lorry.png', None, 2)
            for x in [200, 520]
        ]
        bikes = [
            Moveable(x, 250, 'data/bike.png', None, 7) for x in [300, 620]
        ]

        self.vehicles = []
        self.vehicles.extend(cars)
        self.vehicles.extend(lorries)
        self.vehicles.extend(bikes)

        logs1 = [
            RiverMoveable(x, 50, 'data/log.png', None, -4)
            for x in [0, 128, 256, 384, 512]
        ]
        turtles = [RiverMoveable(x, 100, 'data/turtle.png', 'data/sink_turtle.png', 2, 0.75)\
                    for x in [50, 178, 306,434,562]]
        logs2 = [
            RiverMoveable(x, 150, 'data/log.png', None, -4)
            for x in [0, 128, 256, 384, 512]
        ]
        self.river_objects = []
        self.river_objects.extend(logs1)
        self.river_objects.extend(turtles)
        self.river_objects.extend(logs2)

        bank_locations = [
            Locations(x, y)
            for (x, y) in [(210, 15), (360, 15), (510, 15), (50, 15), (
                70, 215), (220, 215), (380, 215), (530, 215), (200,
                                                               415), (440,
                                                                      415)]
        ]
        self.homes = [Home(x, 0) for x in [50, 200, 350, 500]]

        self.fly_locations = []
        self.fly_locations.extend(bank_locations)

        self.croc_locations = self.homes
        self.croc_locations.append(Locations(-50,
                                             -50))  # Add an offscreen location

        self.flies = [TimedMoveable(x, 15, 'data/fly.png', None, None,  1.5, self.fly_locations)\
                  for x in [210, 360, 510]]
        self.crocs = [
            TimedMoveable(50, 0, 'data/croc.png', None, None, 3, self.homes)
        ]

        splash = ['data/splash1.png', 'data/splash2.png', 'data/splash3.png']
        self.animations = [Animation(splash, 150)]

        self.score = score
        self.no_of_lives = no_of_lives
        '''game_data = {'frog':frog,'frogs':frogs, 'vehicles':vehicles, 'river_objects':river_objects,\
Exemple #3
0
from Locations import Locations
from Product import Product
from Url import Url
from cheapestprice import cheapest_price as cheapest
from sql import add_to_table as db

if (__name__ == "__main__"):
    # set the loop to run by default
    loopcond = True
    while (loopcond):
        # first arg is the product name
        product = input("Enter a product: ")

        # get the locations and location ids
        l = Locations()
        provinces = l.get_provinces()
        province_ids = l.get_province_ids()

        # generate a string of provinces to prompt user with
        provinces_string = "\n"
        for province_no in provinces:
            provinces_string += str(province_no) + ": " + (
                provinces[province_no] + "\n")

        # second arg is the province number
        province_num = input("Enter a province number from:" +
                             provinces_string)

        # generate the kijiji url
        websiteObject = Url()
Exemple #4
0
def handle_command(command, channel):
    """
        Executes bot command if the command is known
        These are the available commands:
        peek <product> in <location> 
        peek <product> in <location> saveas <db>
        locations
        help
    """
    # Default response is help text for the user
    default_response = "Uknown command. Try *{}* for list of commands and usage.".format(
        "help")

    # Finds and executes the given command, filling in response
    response = None

    # get the location, locations and locaiton ids
    l = Locations()
    provinces = l.get_provinces()
    province_ids = l.get_province_ids()

    # locations
    if (command == "locations"):
        # print a message of the available locations
        provinces_string = "\n"
        for province_no in provinces:
            provinces_string += str(
                province_no) + ": " + provinces[province_no] + "\n"
        response = "Choose a locaton number from" + provinces_string

    # help
    elif (command == "help"):
        # print out all the usable commands
        response = "Here are list of commands to get you started." + (
            "\n\n*{}* _product name_ *{}* _location number_".format(
                "peek", "in")
        ) + ("\nEXAMPLE: To get the lowest gtx 1070 in Ontario") + (
            "\n peek gtx 1070 in 0"
        ) + (
            "\n\n*{}* _product name_ *{}* _location number_ *{}* _database name_"
            .format("peek", "in", "saveas")
        ) + (
            "\n EXAMPLE: Find cheapest scarlett 2i2 in BC put it in 'mytable.db'"
        ) + ("\n peek scarlett 2i2 in 2 saveas mytable") + ("\n\n*{}*".format(
            "locations")) + ("\n Lists all the location numbers")

    # peek <product name> in <location number>"
    # startswith peek
    # has " in "
    # product name = command[index(peek): index(in)]
    # location = command[index(in):]
    # remove beggining and end spaces from both
    elif (command.startswith("peek ") and " in " in command):
        peek_right_index = command.find("peek ") + len("peek ")
        in_left_index = command.find(" in ")
        in_right_index = command.find(" in ") + len(" in ")

        # product is between peek and in
        product = command[peek_right_index:in_left_index]

        # check if a valid location filter is used
        after_in = command[in_right_index:]

        #print (after_in)
        # if a valid location filter is used
        if (after_in.strip().isdigit()):
            province_num = int(after_in.strip())
            website = url(product, province_num, provinces, province_ids)
            (product_name, product_price, link,
             date) = cheapest(website, product)

            response = "The cheapest " + product + " in " + provinces[
                province_num] + (" is the \n" +
                                 "<{}|{}>".format(link, product_name) +
                                 "\n") + ("costing $" + str(product_price) +
                                          ", posted " + date)

        # check if the after_in is of the form <number> ... saveas <text>
        elif (" saveas " in after_in):

            saveas_left_index = after_in.find(" saveas ")
            saveas_right_index = after_in.find(" saveas ") + len(" saveas ")

            before_saveas = after_in[:saveas_left_index]
            # check if valid location is used
            if (after_in[:saveas_left_index].strip().isdigit()):

                # get the province num
                province_num = int(after_in[:saveas_left_index].strip())
                website = url(product, province_num, provinces, province_ids)
                (product_name, product_price, link,
                 date) = cheapest(website, product)

                table_name = after_in[saveas_right_index:]
                db(product_name, product_price, provinces[province_num], link,
                   date, table_name)
                response = "Added cheapest " + product + " in " + (
                    provinces[province_num]
                ) + (" \n" + "<{}|{}>".format(link, product_name) + "\n") + (
                    "costing $" + str(product_price) + ", posted " + date +
                    ("\nto the database named " +
                     ("*{}*".format(table_name) + "!")))

    # Sends the response back to the channel
    slack_client.api_call("chat.postMessage",
                          channel=channel,
                          text=response or default_response)
Exemple #5
0
import re
from Location import Location
from Locations import Locations


# Calculates moving average
def movingAverage(avg, new_sample, n):
    avg -= avg / n
    avg += new_sample / n
    return avg


if __name__ == "__main__":

    # Saves locations and cost information
    colLocations = Locations()
    try:
        myFile = open(
            'C:\\Users\\josh.dombal\\PycharmProjects\\JobLocationFinder\\costOfLiving',
            mode='r')

        f = open('locationInfo.txt', 'w')
        count = 0
        job1 = None
        # Runs through each line costOfLiving.txt and scrapes info about jobs for each location
        for line in myFile:
            count += 1
            locat = Location()
            #print(line)
            new = [x.strip() for x in line.split(',')]
            #print(new)
Exemple #6
0
def build(objtId, p):
    if (p.__class__.__name__ == 'AttackerParameters'):
        return Attacker(objtId, p.name(), p.description(), p.image(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'PersonaParameters'):
        return Persona(objtId, p.name(), p.activities(), p.attitudes(),
                       p.aptitudes(), p.motivations(),
                       p.skills(), p.intrinsic(), p.contextual(), p.image(),
                       p.assumption(), p.type(), p.tags(),
                       p.environmentProperties(), p.codes())
    if (p.__class__.__name__ == 'AssetParameters'):
        return Asset(objtId, p.name(), p.shortCode(), p.description(),
                     p.significance(), p.type(), p.critical(),
                     p.criticalRationale(), p.tags(), p.interfaces(),
                     p.environmentProperties())
    if (p.__class__.__name__ == 'TemplateAssetParameters'):
        return TemplateAsset(objtId, p.name(), p.shortCode(), p.description(),
                             p.significance(), p.type(), p.surfaceType(),
                             p.accessRight(), p.properties(), p.rationale(),
                             p.tags(), p.interfaces())
    if (p.__class__.__name__ == 'TemplateRequirementParameters'):
        return TemplateRequirement(objtId, p.name(), p.asset(), p.type(),
                                   p.description(), p.rationale(),
                                   p.fitCriterion())
    if (p.__class__.__name__ == 'TemplateGoalParameters'):
        return TemplateGoal(objtId, p.name(), p.definition(), p.rationale(),
                            p.concerns(), p.responsibilities())
    if (p.__class__.__name__ == 'SecurityPatternParameters'):
        return SecurityPattern(objtId, p.name(), p.context(), p.problem(),
                               p.solution(), p.requirements(),
                               p.associations())
    if (p.__class__.__name__ == 'ComponentParameters'):
        return Component(objtId, p.name(), p.description(), p.interfaces(),
                         p.structure(), p.requirements(), p.goals(),
                         p.associations())
    if (p.__class__.__name__ == 'ComponentViewParameters'):
        return ComponentView(objtId, p.name(), p.synopsis(), p.components(),
                             p.connectors(), p.attackSurfaceMetric())
    if (p.__class__.__name__ == 'ValueTypeParameters'):
        return ValueType(objtId, p.name(), p.description(), p.type(),
                         p.score(), p.rationale())
    if (p.__class__.__name__ == 'ClassAssociationParameters'):
        return ClassAssociation(objtId, p.environment(), p.headAsset(),
                                p.headDimension(), p.headNavigation(),
                                p.headType(), p.headMultiplicity(),
                                p.headRole(), p.tailRole(),
                                p.tailMultiplicity(), p.tailType(),
                                p.tailNavigation(), p.tailDimension(),
                                p.tailAsset(), p.rationale())
    if (p.__class__.__name__ == 'GoalAssociationParameters'):
        return GoalAssociation(objtId, p.environment(), p.goal(),
                               p.goalDimension(), p.type(), p.subGoal(),
                               p.subGoalDimension(), p.alternative(),
                               p.rationale())
    if (p.__class__.__name__ == 'DependencyParameters'):
        return Dependency(objtId, p.environment(), p.depender(), p.dependee(),
                          p.dependencyType(), p.dependency(), p.rationale())
    if (p.__class__.__name__ == 'GoalParameters'):
        return Goal(objtId, p.name(), p.originator(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ObstacleParameters'):
        return Obstacle(objtId, p.name(), p.originator(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'DomainPropertyParameters'):
        return DomainProperty(objtId, p.name(), p.description(), p.type(),
                              p.originator(), p.tags())
    if (p.__class__.__name__ == 'ThreatParameters'):
        return Threat(objtId, p.name(), p.type(), p.method(), p.tags(),
                      p.environmentProperties())
    if (p.__class__.__name__ == 'VulnerabilityParameters'):
        return Vulnerability(objtId, p.name(), p.description(), p.type(),
                             p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'RiskParameters'):
        return Risk(objtId, p.name(), p.threat(), p.vulnerability(), p.tags(),
                    p.misuseCase())
    if (p.__class__.__name__ == 'ResponseParameters'):
        return Response(objtId, p.name(), p.risk(), p.tags(),
                        p.environmentProperties(), p.responseType())
    if (p.__class__.__name__ == 'CountermeasureParameters'):
        return Countermeasure(objtId, p.name(), p.description(), p.type(),
                              p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'TaskParameters'):
        return Task(objtId, p.name(), p.shortCode(), p.objective(),
                    p.assumption(), p.author(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'UseCaseParameters'):
        return UseCase(objtId, p.name(), p.author(), p.code(), p.actors(),
                       p.description(), p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'MisuseCaseParameters'):
        return MisuseCase(objtId, p.name(), p.environmentProperties(),
                          p.risk())
    if (p.__class__.__name__ == 'DotTraceParameters'):
        return DotTrace(p.fromObject(), p.fromName(), p.toObject(), p.toName())
    if (p.__class__.__name__ == 'EnvironmentParameters'):
        return Environment(objtId, p.name(), p.shortCode(), p.description(),
                           p.environments(), p.duplicateProperty(),
                           p.overridingEnvironment(), p.tensions())
    if (p.__class__.__name__ == 'RoleParameters'):
        return Role(objtId, p.name(), p.type(), p.shortCode(), p.description(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ResponsibilityParameters'):
        return Responsibility(objtId, p.name())
    if (p.__class__.__name__ == 'ExternalDocumentParameters'):
        return ExternalDocument(objtId, p.name(), p.version(), p.date(),
                                p.authors(), p.description())
    if (p.__class__.__name__ == 'InternalDocumentParameters'):
        return InternalDocument(objtId, p.name(), p.description(), p.content(),
                                p.codes(), p.memos())
    if (p.__class__.__name__ == 'CodeParameters'):
        return Code(objtId, p.name(), p.type(), p.description(),
                    p.inclusionCriteria(), p.example())
    if (p.__class__.__name__ == 'MemoParameters'):
        return Memo(objtId, p.name(), p.description())
    if (p.__class__.__name__ == 'DocumentReferenceParameters'):
        return DocumentReference(objtId, p.name(), p.document(),
                                 p.contributor(), p.description())
    if (p.__class__.__name__ == 'ConceptReferenceParameters'):
        return ConceptReference(objtId, p.name(), p.dimension(),
                                p.objectName(), p.description())
    if (p.__class__.__name__ == 'PersonaCharacteristicParameters'):
        return PersonaCharacteristic(objtId, p.persona(), p.qualifier(),
                                     p.behaviouralVariable(),
                                     p.characteristic(), p.grounds(),
                                     p.warrant(), p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'TaskCharacteristicParameters'):
        return TaskCharacteristic(objtId, p.task(), p.qualifier(),
                                  p.characteristic(), p.grounds(), p.warrant(),
                                  p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'ImpliedProcessParameters'):
        return ImpliedProcess(objtId, p.name(), p.description(), p.persona(),
                              p.network(), p.specification(), p.channels())
    if (p.__class__.__name__ == 'LocationsParameters'):
        return Locations(objtId, p.name(), p.diagram(), p.locations(),
                         p.links())
    else:
        raise UnknownParameterClass(str(objtId))
Exemple #7
0
 def __init__(self, x_pos,  y_pos):
     '''
     Constructor
     '''
     Locations.__init__(self,x_pos,y_pos)
Exemple #8
0
class Simulator:
	photoVoltaics = PhotoVoltaics()
	comsumptions = Comsumptions()
	users = Users()
	locations = Locations()
	totalNoUsers = 10
	# File Handle
	profileCSV = None
	def setup(self):
		print(Config.C_NORMAL+"Program Initialization...")
		# Load files
		self.loadFile()
		# Generate user data
		self.generateUsers()
		print("Initialization finished"+Config.C_VAUE+"=w="+Config.C_NORMAL)

	def loadFile(self):
		print("Load Location CSV files...")
		locationsCSV = Utils.loadCsv(Config.LOCATION_PROFILE_FILEPATH)
		print("Load Location CSV finished\nCreating location data...")
		for subtowm,latitude,longitude,dsp in zip(locationsCSV.neighbourhood,locationsCSV.latitude,locationsCSV.longitude,locationsCSV.DSP):
			self.locations.append(Location(latitude,longitude,subtowm,dsp))
		print("Location load finish.")

		print("Load PV CSV files...")
		self.profileCSV = Utils.loadCsv(Config.PV_PROFILE_CSV_FILEPATH)
		# Create & Load PV data
		print("PV file load finished\nCreating PV data...")
		for date,production,time in zip(self.profileCSV.date,self.profileCSV.production,self.profileCSV.time):
			self.photoVoltaics.append(PhotoVoltaic(date,time,production))
		# print(self.profileCSV.iloc[0,0])
		# Create & Load Comsumption data
		print("Load Comsumptions file...")
		comsuptionsFileCount = 0
		comsuptionsDataCount = 0 
		for filename in os.listdir(Config.CONSUMPTION_PROFILE_FILEPATH):
			file = Utils.loadCsv(Config.CONSUMPTION_PROFILE_FILEPATH+filename)
			print("Processing File:"+Config.C_VAUE+"{0}...".format(filename)+Config.C_NORMAL)
			comsumption = Comsumption([])
			for i in range(0,Config.CONSUMPTION_COL):
				# Parse comsumption data
				for j in range(3,Config.CONSUMPTION_ROW):
					data = file.iloc[i,j]
					comsumption.appendComsumption(data)
					comsuptionsDataCount+=1
			self.comsumptions.append(comsumption)
			comsuptionsFileCount+=1
		# debug msg
		print("Comsumptions File load finish,total:{0}.".format(comsuptionsFileCount))
		print("Comsumptions data created,total:{0}.".format(comsuptionsDataCount))
		print("File loading process finish.")
	# Assigned random comsuption & generate amounts of user data
	"""def generateUsers(self,amount):
		print("Generating {0} users data...".format(amount+1))
		idx = 0
		while idx < amount+1:	
			self.users.append(self.generateUser(idx))
			idx+=1
		print("User data generation finished")
	"""	
	def generateUsers(self):
		print("Please enter amount of user data wants to generated")
		numOfUser = input ("Numbers -> ")
		self.totalNoUsers = int(numOfUser)
		print("Please enter persentage of user have PVs")
		persentage = input ("Persentage -> ")
		persentageInUse = float(persentage)/float(100.00)
		idx = 0
		while idx < int(self.totalNoUsers)+1:
			if(idx < int(self.totalNoUsers) * float(persentageInUse)):
				self.users.append(self.generateUser(idx,True))
				idx+=1
			else:
				self.users.append(self.generateUser(idx,False))
				idx+=1

	# Generating a user data
	def generateUser(self,userId,isHavePV):
		cFactor = random.gauss(Config.CMAXMEAN,Config.CMAXDEV)
		while (cFactor > Config.CMAXMAX or cFactor < Config.CMINMAX):
			cFactor = random.gauss(Config.CMAXMEAN,Config.CMAXDEV)
		# Calc PVFactor
		meanCapacityPV = (Config.MINCAPACITYPV + Config.MAXCAPACITYPV) / 2
		devCapacityPV = (Config.MAXCAPACITYPV - meanCapacityPV) / 3
		pvFactor = None
		pvFactor_t = random.gauss(meanCapacityPV,devCapacityPV)
		if(pvFactor_t < Config.MINCAPACITYPV):
			pvFactor = Config.MINCAPACITYPV
		elif(pvFactor_t > Config.MAXCAPACITYPV):
			pvFactor = Config.MAXCAPACITYPV
		else:
			pvFactor = pvFactor_t		
		if(isHavePV == True): 
			pv = self.photoVoltaics.getpvFactorizedPv(pvFactor)	
		else: 
			pv = self.photoVoltaics.getpvFactorizedPv(0)
		# print(pv[100].getProduction())
		# randomly assign Location
		location = self.locations.random()
		# new user object
		comsumption = self.comsumptions.random()

		user = User(userId,pvFactor,cFactor,pv,comsumption,location)
		# debug
		# print(comsumption.getComsumptions()[0])
		# print(len(user.getComsumptions()))
		
		
			
		return user
	
	# generate PV graph for a user
	def generateUserGraph(self,id,start_index,end_index):
		# id = 0
		user = self.users.getUser(id)
		pvs = user.getPv()
		comsumptions = user.getComsumptions()
		x = []
		y = []
		y2 = []
		y3 = []
		# time = []
		for i in range(start_index,end_index):
			#time.append(pvs[i].getTime())
			# date = pvs[i].getDate()
			production = pvs[i].getProduction()
			x.append(i)
			y.append(production)
			comsuption = comsumptions[i]
			y2.append(comsuption)
			feedin = user.getFeedin(pvs[i],comsuption)
			y3.append(feedin)

		chart.plot(x,y,color='blue')
		chart.plot(x,y2,color='red')
		chart.plot(x,y3,color='green')
		chart.xlabel("Time/15 Min")
		chart.ylabel("production PV(blue)comsuption(red)feedin(green)")
		chart.title('Userid: {0}'.format(id))
		# chart.xticks(x,time)
		chart.show()
		self.menu()
	# Generate Comsumption data for a user
	#def generateUserComsumption(self,start_index,end_index):
	#	id = 0
	#	user = self.users.getUser(id)
	#	comsumptions = user.getComsumptions()
	#	x = []
	#	y = []
	#	# time = []
	#	for i in range(start_index,end_index):
	#		#time.append(pvs[i].getTime())
	#		# date = pvs[i].getDate()
	#		comsuption = comsumptions[i]
	#		x.append(i)
	#		y.append(comsuption)
	#	
	#	chart.plot(x,y)
	#	chart.xlabel("Time/15 Min")
	#	chart.ylabel("comsuption C")
	#	# chart.xticks(x,time)
	#	chart.show()
	def debugPurchesAndFeedin(self):
		id = 0
		time = 5
		user = self.users.getUser(id)
		pv = user.getPvByIndex(time)
		c = user.getComsumptionByIndex(time)
		price = user.getPrice(time)
		feedIn = user.getFeedin(pv,c)
		purches = user.getPurchase(pv,c)
		print("Price: {0} Feedin: {1} purches: {2}".format(price,feedIn,purches))
	# debug pv
	def debugPV(self):
		print(self.photoVoltaics)

	def generateCSVRefenceFile(self):
		FileCSV.overwriteCsv()
		for i in range(0,35040):
			if(i%2 == 0): 
				for j in range(1,self.totalNoUsers):
					print("time idx = {0}".format(i))
					user = self.users.getUser(j)
					FileCSV.csv_feedin_purchase_1(user, i)
					# Packet.sendPacketHistory(user,timeIdx)


	def sendPacketByUserId(self,userId,timeIdx):
		print("time idx = {0}".format(timeIdx))
		user = self.users.getUser(userId)
		Packet.sendPacketHistory(user,timeIdx)
	# Send user data (ordered)
	def sendPacket(self):
		Packet.printServerInfo()
		for i in range(0,35040):
			for j in range(1,self.totalNoUsers):
				self.sendPacketByUserId(j,i)
	# Send user data (un ordered) by time intergral 
	# note the intergrals is minutes, default is 15
	def sendPacketByInterval(self,minutesIntergral):
		Packet.printServerInfo()
		generatedIdx = []
		# mins = datetime.datetime.now().strftime('%M')
		while True:
			minutes = datetime.datetime.now().strftime('%M')
			#second = datetime.datetime.now().strftime('%S')	
			if int(minutes) % minutesIntergral == 0:	
			#if int(second) % minutesIntergral == 0:
				for i in range(1,self.totalNoUsers):
					print(i)
					idx = random.choice(range(1,self.totalNoUsers))
					while idx in generatedIdx:
						idx = random.choice(range(1,self.totalNoUsers))
					generatedIdx.append(idx)
					self.sendPacketByUserId(idx, Utils.currentTimeToTimeIdx())
				generatedIdx.clear()
				time.sleep(60)
	# Send user data (un ordered)
	def sendPacketRamble(self):
		Packet.printServerInfo()
		generatedIdx = []
		for i in range(0,35040):
			if i == 35049:
				i = 0
			for j in range(1,self.totalNoUsers):
				idx = random.choice(range(1,self.totalNoUsers))
				while idx in generatedIdx:
					idx = random.choice(range(1,self.totalNoUsers))
				#print("user id {0}".format(idx))
				self.sendPacketByUserId(idx,Utils.currentTimeToTimeIdx())
				# Fix problem that i forgot to add current idx into the list.
				generatedIdx.append(idx)
				#time.sleep(0.1)
			generatedIdx.clear()
	def menu(self):
		mode = '0'
		while mode == '0':
			print("=====================")
			print("Simulator Program")
			print("HOST: " + Config.C_VAUE + "{0}".format(Config.HOST_ADDR) + Config.C_NORMAL)
			print("PORT: " + Config.C_VAUE + "{0}".format(Config.HOST_PORT) + Config.C_NORMAL)
			print("CLIENT_NAME: " + Config.C_VAUE + "{0}".format(Config.HOST_CLIENT) + Config.C_NORMAL)
			print("=====================")
			print("1.Send data by sequence (Ordered)")
			print("2.Send data by unsequenced (Un Ordered)")
			print("3.Send data by interval (15 Mins)")
			print("4.Display data chart")
			print("5.Generate CSV File")
			print("6.Exit Program")
			mode = input ("Selection -> ")
			if(mode == '1'):
				self.sendPacket()
			elif(mode == '2'):
				self.sendPacketRamble()
			elif(mode == '3'):
				minutes = 15
				self.sendPacketByInterval(minutes)
			elif(mode == '4'):
				userId = input ("Which user ? (please enter id) ->")
				timeIntergralstart = input ("time intergral start ? (please enter as interger number) ->")
				timeIntergralend = input ("time intergral end ? (please enter as interger number) ->")
				self.generateUserGraph(int(userId),int(timeIntergralstart),int(timeIntergralend))
				#self.generateUserComsumption(int(userId),int(timeIntergral))
			elif(mode == '5'):
				self.generateCSVRefenceFile()
			elif(mode == '6'):
				sys.exit()
				return
			else:
				print("Sorry, invaild option.")
				self.menu()
			
	def __init__(self):
		try:
			self.setup()
			# Graph
			#self.generateUserGraph(0,96)
			#self.generateUserComsumption(0,96)
			#self.debugPurchesAndFeedin()
			# Send data
			#self.sendPacket()
			#self.sendPacketByInterval(15)
			# Main Menu
			self.menu()
		except Exception as e:
			print("Sorry, an error has occur :( \n"+Config.C_VAUE+"{0}".format(e))
			self.menu()
Exemple #9
0
          os._exit(0)
      else:
        # parent process
        for i in xrange( starttimeout ):
          sleep( 1 )
          try:
            sendCommand( self.partition, "" )
          except:
            continue
          else:  
            break
        else:
          raise Exception("Correlator did not start.")

      # inject the parset
      self.parset.setFilename( Locations.resolvePath( "%s/RTCP-${OBSID}.parset" % (self.logdir,), self.parset ) );
      info( "Sending parset '%s' to correlator." % (self.parset.filename,) )
      self.parset.save()
      sendCommand( self.partition, "parset %s" % (self.parset.filename,) )

      # quit immediately after processing the parset
      sendCommand( self.partition, "quit" )

      # wait for correlator to finish
      def isStopped():
        ret = os.waitpid( pid, os.WNOHANG )

        if ret[1] > 0:
          raise Exception("Correlator did not start.")

        return ret != (0,0)