def test_update_activity(self): activity1 = Activity("888", "party", datetime(2020, 2, 2, 3, 20), datetime(2020, 2, 2, 4, 30), "case") activity2 = Activity("000", "party", datetime(2020, 2, 2, 3, 20), datetime(2020, 2, 2, 4, 30), "case") self.assertTrue(self.db.update_activity(activity1)) self.assertFalse(self.db.update_activity(activity2))
def compose_activity(content): restrictions = [] activity_type = map_activity_type(content['scheduling_type']) if activity_type == ActivityUtil.TYPE_INSTANCES or 'instances_per_day' in content: instances_per_week = content[ 'instances_per_week'] if 'instances_per_week' in content else 7 generated_activities = [] duration = map_duration(content) for i in range(1, instances_per_week + 1): for j in range(1, content['instances_per_day'] + 1): generated_activities.append( Activity(name="%s [%d, %d]" % (content['name'], i, j), duration=duration, activity_type=activity_type, restrictions=restrictions, instances_per_week=instances_per_week, instances_per_day=content['instances_per_day'])) return generated_activities return Activity( content['name'], map_duration(content), map_activity_type(content['scheduling_type']), restrictions, )
def main(l, params): act = Activity(l) l = preProcessLog(l, act.a) print("") print("############## ACTIVITIES SET ##############") act = Activity(l) print(act.a) print("") print("############## LOG LIST ##############") log = Log(l) print(log.l) print("") print("############## FREQUENCY TABLE ##############") freq = FrequencyDirectlyFollows(log.l, act.a) print(freq.ft) print("") print("############## DEPENDENCY TABLE ##############") depen = Dependency(freq.ft, act.a) print(depen.dt) print("") print("############## CNET A_I AND A_O ##############") cnet = CNet(act.a, log.l, freq.ft, depen.dt, params) print(cnet.a_i) print(cnet.a_o) print("") print("############## CNET DEPENDENCY OUT ##############") print(cnet.depRelOut) print("") print("############## CNET DEPENDENCY IN ##############") print(cnet.depRelIn) print("") print("############## CNET OUTPUT BINDINGS ##############") print(cnet.outBind) print("") print("############## CNET INPUT BINDINGS ##############") print(cnet.inBind) print("") print("############## CNET IS VALID SEQUENCE ##############") print(cnet.isValidSequence(['a','b','b','e'], 4))
def __init__(self): if self.isMember(): filePath = "./user/profile.txt" f = open(filePath, "r") s = f.readlines() self.name = s[0].split('\n')[0] self.gender = s[1].split('\n')[0] self.birth = s[2].split('\n')[0] self.currentDate = s[3].split('\n')[0] self.height = s[4].split('\n')[0] self.weight = s[5].split('\n')[0] self.goal = Goal(self) self.workOut = WorkOut(self.gender) self.activity = Activity() f.close() else: self.name = None self.gender = None self.birth = None self.currentDate = None self.height = None self.weight = None self.goal = None self.workOut = None self.activity = None
def add_activity(self, name, children): if name == '?': self.add_black_box(children) else: new_activity = Activity(name, children) self.components.append(new_activity) self.G.add_node(new_activity)
def collect_ride_data(self, challenge): """ Pull the latest ride data from Strava via the API """ client = Client() client.access_token = self.strava_config['access-token'] #activities = client.get_club_activities(165009) activities = client.get_club_activities(challenge.get_group_id()) act_list = [] for activity in activities: if not activity.type == 'Ride' and not activity.type == 'VirtualRide': print 'Non-ride activity: %s, type: %s' % (activity.name, activity.type) continue act = Activity(activity.id) act.set_athlete(activity.athlete.id) act.set_name(activity.name) act.set_gmt_date(activity.start_date) # GMT Start date act.set_elapsed_time(activity.elapsed_time) act.set_distance(round(unithelper.kilometers(activity.distance).num, 2)) act.set_elevation(unithelper.meters(activity.total_elevation_gain).num) act.set_ride_type(activity.type) act.set_trainer_ride(activity.trainer) act_list.append(act) db_store = GTDataStore(challenge.get_db_path(), self.verbose) db_store.store_if_new(act_list)
def read(fileActivities): """Reads the input file The file must be a CSV file The attributes of each activities must follow this order : 1. ID 2. Name 3. Successors : set of activities' id delimited by the symbol ";" 4. Duration 5. Normal Cost 6. Top Cost 7. Reduction Cost 8. Ressources : set of integer delimited by the symbol ";" (First integer is the amount of the first ressource and so on) """ listActivities = [] f = csv.reader(open(fileActivities,"rb")) for line in f: ident = int(line[0]) name = line[1] successors = "" if (line[2] != ""): successors = map(int, line[2].split(";")) duration = int(line[3]) normalCost = int(line[4]) topCost = int(line[5]) reductionCost = int(line[6]) ressources = "" if (line[3] != ""): ressources = map(int, line[7].split(";")) act = Activity(ident, name, successors, duration, normalCost, topCost, reductionCost, ressources) listActivities.insert(act.ident, act) return listActivities
def add_activity(self, name, duration, node_from_name, node_to_name): self.add_nodes_to_nodes_dictionary(node_from_name, node_to_name) activity_to_add = Activity(name, duration, node_from_name, node_to_name) assert activity_to_add, 'could not create an Activity instance' updated_activity = self.update_the_activity_nodes_from_nodes_dictionary( activity_to_add, "left") assert updated_activity, 'could not update the activity' self.activity_list.append(updated_activity) self.calculate_activity_left_value_after_addition(activity_to_add)
def get(self): activity = Activity() from Authentication import Authentication authentication = Authentication(users) print(activity) return ({ "activity": str(activity), "user": str(authentication), "location": "home" })
def clone(self): pos = Instance() pos.name = "clone of " + self.name for act in self.activities: newAct = Activity(act.time, len(self.resources)) newAct.resources = act.resources[:] newAct.predecessors = act.predecessors.copy() newAct.successors = act.successors.copy() pos.activities.append(newAct) return pos
def __init__(self, dictionary): self.segmentType = dictionary['type'] self.startTime = parser.parse(dictionary['startTime']) self.endTime = parser.parse(dictionary['endTime']) if 'activities' in dictionary: self.activitiesArray = [ Activity(d) for d in dictionary['activities'] ] else: self.activitiesArray = []
def add_component(self, a_or_e, name, children): c = None if a_or_e == 'a': if name == '?': c = BlackBox(children) else: c = Activity(name, children) elif a_or_e == 'e': c = Entity(name, children) self.components.append(c) self.G.add_node(c, name=c.name, component_type=c.component_type)
def readFromExport(self, infile): line = string.strip(infile.readline()) while not string.strip(line) == '': parts = line.split(',') newAct = Activity(int(parts[0]), 0) if len(parts[1]) > 0: newAct.predecessors.update(map(int, parts[1].split())) if len(parts[2]) > 0: newAct.resources = map(int, parts[2].split()) self.activities.append(newAct) line = string.strip(infile.readline()) for (actId, act) in enumerate(self.activities): for pred in act.predecessors: self.activities[pred].successors.add(actId)
def add_activity(name, data): new_Activity = Activity(name, data) if name is 'gehen': Korpus.gehen = new_Activity elif name is 'joggen': Korpus.joggen = new_Activity elif name is 'laufen': Korpus.laufen = new_Activity elif name is 'rueckw': Korpus.rueckw = new_Activity elif name is 'stehen': Korpus.stehen = new_Activity elif name is 'treppe': Korpus.treppe = new_Activity Korpus.activity.append(new_Activity)
def populate_evening_activities(self): self.evening_activities_arr.append( Activity("skits", "8 pm", "Ruth Brown steps")) self.evening_activities_arr.append( Activity("evening fires", "8 pm", "The Lodge")) self.evening_activities_arr.append( Activity("singing", "8 pm", "Ruth Brown steps")) self.evening_activities_arr.append( Activity("poetry", "8 pm", "Ruth Brown steps")) self.evening_activities_arr.append( Activity("capture the chicken", "8 pm", "Greenie Hill")) self.evening_activities_arr.append( Activity("dances", "8 pm", "Boat Barn"))
class TestActivity(TestCase): start = datetime(2020, 2, 2, 12, 20) end = datetime(2020, 2, 2, 15, 20) id1 = "1" name1 = "act1" loc1 = "location1" act = Activity(id1, name1, start, end, loc1) def test_get_id(self): self.assertTrue(self.act.get_id() == "1") def test_get_name(self): self.assertTrue(self.act.get_name() == "act1") def test_get_start_time(self): self.assertTrue(self.act.get_start_time() == self.start) def test_get_end_time(self): self.assertTrue(self.act.get_end_time() == self.end) def test_get_location(self): self.assertTrue(self.act.get_location() == self.loc1)
def readFromPSPLIB(self, infile): # skip first lines (not interesting) infile.readline() infile.readline() infile.readline() # read instance information (number of jobs, number of resources) (numJobs, numResources) = self.readInstanceInfo(infile) # set up arrays self.resources = [0] * numResources for i in range(numJobs): self.activities.append(Activity(0, numResources)) # read precedence relations self.readPrecedences(infile) # read durations & resource cost self.readRequirements(infile) # read resource availability self.readResources(infile)
def activityImport(fichier): file = open(fichier, "r") try: #on lit le fichier reader = csv.reader(file) i = 0 #pour chaque ligne, on la transforme en activité et on l'insert dans la BD for row in reader: #on ignore la première ligne qui contient les en-tetes if (i != 0): act = Activity(row[5], row[4]) print(act) actInsertBD(act) i += 1 #except: # print("erreur, pas normal!!!") finally: file.close()
def populate_activities(self): self.activities_arr.append(Activity("archery", "10 am", "field")) self.activities_arr.append(Activity("soccer", "10 am", "field")) self.activities_arr.append(Activity("pickleball", "10 am", "field")) self.activities_arr.append(Activity("kickball", "10 am", "field")) self.activities_arr.append(Activity("adventuretime", "10 am", "field")) self.activities_arr.append(Activity("paddleboarding", "2 pm", "dock")) self.activities_arr.append(Activity("extreme-canoe", "10 am", "dock")) self.activities_arr.append(Activity("kayaking", "10 am", "dock")) self.activities_arr.append(Activity("sailing", "2 pm", "dock")) self.activities_arr.append(Activity("sail-racing", "10 am", "dock")) self.activities_arr.append(Activity("swimming", "2 pm", "dock")) self.activities_arr.append(Activity("pottery", "2 pm", "craft courts")) self.activities_arr.append( Activity("arts and crafts", "2 pm", "craft courts")) self.activities_arr.append(Activity("yoga", "2 pm", "field")) self.activities_arr.append(Activity("garden cookery", "2 pm", "garden")) self.activities_arr.append(Activity("Horsebackriding", "2 pm", "barn")) self.activities_arr.append(Activity("Horsebackriding", "10 am", "barn"))
self.activity_queue[0].get_question()) self.already_visible = True def get_activities_completed(self): return self.activity_count if __name__ == "__main__": import os import sys from Activity import Activity app = QtGui.QApplication(sys.argv) screenShape = QtGui.QDesktopWidget().screenGeometry() width = screenShape.width() / 3 height = screenShape.height() - 80 act = Activity(title='GOing to the mall') pat = Patient(width=width, height=height) pat.show() pat.send(act) # msg = QtGui.QMessageBox() # msg.setIcon(QtGui.QMessageBox.Warning) # msg.setText("This activity cannot be scheduled because it is past the time") # msg.setWindowTitle("Scheduling Error") # msg.setStandardButtons(QtGui.QMessageBox.Ok) # msg.exec_() sys.exit(app.exec_())
def _populate(self, stmt_data, auth, sub=False): # pdb.set_trace() args = {} #Must include verb - set statement verb try: raw_verb = stmt_data['verb'] except KeyError: raise exceptions.ParamError( "No verb provided, must provide 'verb' field") #Must include object - set statement object try: statementObjectData = stmt_data['object'] except KeyError: raise exceptions.ParamError( "No object provided, must provide 'object' field") try: raw_actor = stmt_data['actor'] except KeyError: raise exceptions.ParamError( "No actor provided, must provide 'actor' field") # Throw error since you can't set voided to True if 'voided' in stmt_data: if stmt_data['voided']: raise exceptions.Forbidden( 'Cannot have voided statement unless it is being voided by another statement' ) # If not specified, the object is assumed to be an activity if not 'objectType' in statementObjectData: statementObjectData['objectType'] = 'Activity' args['verb'] = self._build_verb_object(raw_verb) valid_agent_objects = ['agent', 'group'] # Check to see if voiding statement # if raw_verb['id'] == 'http://adlnet.gov/expapi/verbs/voided': if args['verb'].verb_id == 'http://adlnet.gov/expapi/verbs/voided': # objectType must be statementRef if want to void another statement if statementObjectData['objectType'].lower( ) == 'statementref' and 'id' in statementObjectData.keys(): stmt_ref = self._voidStatement(statementObjectData['id']) args['stmt_object'] = stmt_ref else: raise exceptions.ParamError( "There was a problem voiding the Statement") else: # Check objectType, get object based on type if statementObjectData['objectType'].lower() == 'activity': if auth is not None: args['stmt_object'] = Activity( json.dumps(statementObjectData), auth=auth.username).activity else: args['stmt_object'] = Activity( json.dumps(statementObjectData)).activity elif statementObjectData['objectType'].lower( ) in valid_agent_objects: args['stmt_object'] = Agent(initial=statementObjectData, create=True).agent elif statementObjectData['objectType'].lower() == 'substatement': sub_statement = SubStatement(statementObjectData, auth) args['stmt_object'] = sub_statement.statement elif statementObjectData['objectType'].lower() == 'statementref': try: existing_stmt = models.statement.objects.get( statement_id=statementObjectData['id']) except models.statement.DoesNotExist: raise exceptions.IDNotFoundError( "No statement with ID %s was found" % statementObjectData['id']) else: stmt_ref = models.StatementRef( ref_id=statementObjectData['id']) stmt_ref.save() args['stmt_object'] = stmt_ref #Retrieve actor args['actor'] = Agent(initial=stmt_data['actor'], create=True).agent #Set voided to default false args['voided'] = False #Set result when present - result object can be string or JSON object if 'result' in stmt_data: # args['result'] = self._populateResult(stmt_data, raw_verb) args['result'] = self._populateResult(stmt_data, args['verb']) # Set context when present if 'context' in stmt_data: args['context'] = self._populateContext(stmt_data) # Set timestamp when present if 'timestamp' in stmt_data: args['timestamp'] = stmt_data['timestamp'] if 'authority' in stmt_data: args['authority'] = Agent(initial=stmt_data['authority'], create=True).agent else: if auth: authArgs = {} authArgs['name'] = auth.username authArgs['mbox'] = auth.email args['authority'] = Agent(initial=authArgs, create=True).agent #See if statement_id already exists, throw exception if it does if 'statement_id' in stmt_data: try: existingSTMT = models.statement.objects.get( statement_id=stmt_data['statement_id']) except models.statement.DoesNotExist: args['statement_id'] = stmt_data['statement_id'] else: raise exceptions.ParamConflict( "The Statement ID %s already exists in the system" % stmt_data['statement_id']) else: #Create uuid for ID args['statement_id'] = uuid.uuid4() # args['stored'] = datetime.datetime.utcnow().replace(tzinfo=utc).isoformat() #Save statement self.statement = self._saveStatementToDB(args, sub)
def setActivity(self, act_name, act_timestamp): """ Creates a new Activity and appends it to self._activities. """ activity = Activity(act_name, act_timestamp) self._activities.append(activity)
def __init__(self, activities=None, parent=None, account=None): QtGui.QWidget.__init__(self, parent) self.activities = activities #list of activity objects if self.activities == None: self.activities = [] self.account = account if len(self.activities) < 1: #create some defaults info instructions1 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist1 = InstructionList(instructions=instructions1) instructions2 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist2 = InstructionList(instructions=instructions2) instructions3 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist3 = InstructionList(instructions=instructions3) instructions4 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist4 = InstructionList(instructions=instructions4) instructions5 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist5 = InstructionList(instructions=instructions5) instructions6 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist6 = InstructionList(instructions=instructions6) instructions7 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist7 = InstructionList(instructions=instructions7) instructions8 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist8 = InstructionList(instructions=instructions8) instructions9 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist9 = InstructionList(instructions=instructions9) instructions10 = [ Instruction(title='Instruction1', date=None, time=None, location='Location1', description='Description1'), Instruction(title='Instruction2', date=None, time=None, location='Location2', description='Description2'), Instruction(title='Instruction3', date=None, time=None, location='Location3', description='Description3') ] instructionlist10 = InstructionList(instructions=instructions10) self.activities.append( Activity(title='Visit the Humane Society', index=0, instruction_list=instructionlist1)) self.activities.append( Activity(title='Do a new jigsaw puzzle', index=1, instruction_list=instructionlist2)) self.activities.append( Activity(title='Go to the zoo', index=2, instruction_list=instructionlist3)) self.activities.append( Activity(title='Visit the planetarium', index=3, instruction_list=instructionlist4)) self.activities.append( Activity(title='Play poker', index=4, instruction_list=instructionlist5)) self.activities.append( Activity(title='Organize your drawers', index=5, instruction_list=instructionlist6)) self.activities.append( Activity(title='Go to a baseball game', index=6, instruction_list=instructionlist7)) self.activities.append( Activity(title='Plant new flowers and garden', index=7, instruction_list=instructionlist8)) self.activities.append( Activity(title='Go to the science museum', index=8, instruction_list=instructionlist9)) self.activities.append( Activity(title='Go fishing on the lake', index=9, instruction_list=instructionlist10)) for activity in self.activities: activity.accepted.connect(self.ask_patient)
def create(self, arr): isNew = not self.isMember() # Is it a new account? # pre : The user's birth date is expressed as a "datetime" object. # now : The user's starting date is expressed as a "datetime" object. # If no account exists, Create a folder and a "profile.txt" file. # Also, 'pre', 'now' are defined as 'None' if isNew: pre = None now = None else: list = self.birth.split("-") pre = datetime(int(list[0]), int(list[1]), int(list[2])) list = self.currentDate.split("-") now = datetime(int(list[0]), int(list[1]), int(list[2])) # If you have a new account, arr must be [1, 2, 3, 4, 5, 6]. # In other words, all personal information of the user are entered. # If If you have an account, arr is [1], or [1, 2] , ... , [1, 2, 3, 4, 5, 6]. # In other words, the user's personal information is partially or all entered. for i in arr: i = int(i) if i == 1: while True: print("Enter name (20 Digits with Upper- and Lower-case alphabet and blank spaces)") name = input("-> ") if len(name) < 1 or len(name) > 20: print("Length of name must be 1 to 20.") input() os.system('cls') continue p = re.search(r'^[a-zA-Z ]{1,20}$', name) if not p: print("Only Upper- and Lower-case alphabet and blank spaces are allowed.") input() os.system('cls') continue if not isNew and self.name == name: print("You have entered the same value as before.") input() os.system('cls') continue os.system('cls') if not isNew: print("Your name has been modified.") input() self.name = name os.system('cls') break elif i == 2: while True: gender = input("Enter gender (1. Female 2. Male) : ") if len(gender) != 1: print("Length of gender must be 1.") input() os.system('cls') continue if gender < '1' or gender > '2': print("Only one Digit: 1 or 2 are legal.") input() os.system('cls') continue if gender == '1': self.gender = "Female" else: self.gender = "Male" os.system('cls') if not isNew and self.gender == gender: print("You have entered the same value as before.") input() os.system('cls') continue if not isNew: print("Your gender has been modified.") input() os.system('cls') break elif i == 3: while True: birth = input("Enter the date of birth (YYYY-MM-DD) : ") if len(birth) != 10: print("Length of string must be 10.") input() os.system('cls') continue if birth[4] != '-' or birth[7] != '-': print("Each year, month and date are must classified as '-' with followed form (YYYY-MM-DD)") input() os.system('cls') continue list = birth.split('-') if len(list[0]) != 4 or len(list[1]) != 2 or len(list[2]) != 2: print("Each year, month and date are must classified as '-' with followed form (YYYY-MM-DD)") input() os.system('cls') continue check = True for i in list: p = re.search(r'^[0-9]{1,4}$', i) if not p: check = False print("Character that is not a digit or '-' are illegal.") input() os.system('cls') break if(not check): continue p = re.search(r'^(19[7-9][0-9]|20[0-1][0-9])-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$', birth) if not p: print("Iligeal form of date (1970-01-01 ~ 2019-12-31)") input() os.system('cls') continue check = True while check: try: pre = datetime(int(list[0]), int(list[1]), int(list[2])) break except ValueError: print("Inexistent form of date followed by Gregorian Calendar") input() os.system('cls') check = False if not check: continue if not isNew and pre > now: print("Birth is later than date of current date.") input() os.system('cls') continue os.system('cls') if not isNew and self.birth == birth: print("You have entered the same value as before.") input() os.system('cls') continue if not isNew: print("Your birth has been modified.") input() self.birth = birth os.system('cls') break elif i == 4: while True: currentDate = input("Enter current date (YYYY-MM-DD) : ") if len(currentDate) != 10: print("Length of string must be 10.") input() os.system('cls') continue if currentDate[4] != '-' or currentDate[7] != '-': print("Each year, month and date are must classified as '-' with followed form (YYYY-MM-DD)") input() os.system('cls') continue list = currentDate.split('-') if len(list[0]) != 4 or len(list[1]) != 2 or len(list[2]) != 2: print("Each year, month and date are must classified as '-' with followed form (YYYY-MM-DD)") input() os.system('cls') continue check = True for i in list: p = re.search(r'^[0-9]{1,4}$', i) if not p: check = False print("Character that is not a digit or '-' are illegal.") input() os.system('cls') break if(not check): continue p = re.search(r'^((19[7-9][0-9]|20[0-2][0-9]|203[0-6])-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])|(2037-(0[1-9]|1[0-1])-(0[1-9]|[12][0-9]|3[01])))$', currentDate) if not p: print("Iligeal form of date. (1970-01-01 ~ 2037-11-30)") input() os.system('cls') continue check = True while check: try: now = datetime(int(list[0]), int(list[1]), int(list[2])) break except ValueError: print("Inexistent form of date followed by Gregorian Calendar") input() os.system('cls') check = False if not check: continue if pre > now: print("Current date is earlier than date of birth.") input() os.system('cls') continue if not isNew and self.currentDate == currentDate: print("You have entered the same value as before.") input() os.system('cls') continue if not isNew: print("Your current date has been modified.") input() self.currentDate = currentDate os.system('cls') break elif i == 5: while True: height = input("Enter your height (aaa.bb) : ") if len(height) != 6: print("Illegal form of height. Length of height is total 6 character.") input() os.system('cls') continue if height.find('.') == -1 or len(height.split('.')[0]) != 3 or len(height.split('.')[1]) != 2: print("Illegal form of height. Height is consisted with 3 integer and 2 decimal classified with '.'.") input() os.system('cls') continue if int(height.split('.')[0]) < 100: print("Integer part of weight must be 100 or more.") input() os.system('cls') continue if not isNew and self.height == height: print("You have entered the same value as before.") input() os.system('cls') continue if not isNew: print("Your height has been modified.") input() self.height = height os.system('cls') break elif i == 6: while True: weight = input("Enter your weight (aa.bb): ") if len(weight) != 5: print("Illegal form of weight. Length of weight is total 5.") input() os.system('cls') continue if weight.find('.') == -1 or len(weight.split('.')[0]) != 2 or len(weight.split('.')[1]) != 2: print("Illegal form of weight. Weight is consisted with 2 integer and 2 decimal classified with '.'.") input() os.system('cls') continue if int(weight.split('.')[0]) < 10: print("Integer part of weight must be 10 or more.") input() os.system('cls') continue if not isNew and self.weight == weight: print("You have entered the same value as before.") input() os.system('cls') continue if not isNew: print("Your weight has been modified.") input() self.weight = weight os.system('cls') break # If you have a new account, the personal information of the user entered above is recorded in "profile.txt". if isNew: os.mkdir("./user") filePath = "./user/profile.txt" f = open(filePath, "w") f.write(self.name + "\n") f.write(self.gender + "\n") f.write(self.birth + "\n") f.write(self.currentDate + "\n") f.write(self.height + "\n") f.write(self.weight + "\n") f.close() self.goal = Goal(self) self.workOut = WorkOut(self.gender) self.activity = Activity()
def main(): parser = argparse.ArgumentParser() parser.add_argument("--send", help="dispatches e-mails to service providers, if not set will just write a report out", action="store_true") parser.add_argument("--infolder", type=str, help="folder to load from, defaults to {}".format(INPUT_DIR)) parser.add_argument("--infilename", type=str, help="file to load from, defaults to {}".format(INPUT_FILE_NAME)) parser.add_argument("--outfolder", type=str, help="folder to write to, defaults to {}".format(OUTPUT_DIR)) parser.add_argument("--outfilename", type=str, help="file to write to, defaults to {}".format(OUTPUT_FILE_NAME)) args = parser.parse_args() if args.send: print "--send flag has been set so SENDING E-MAILS TO SERVICE PROVIDERS" # set up for output file if specified in_folder_name = "" if args.infolder: in_folder_name = args.infolder else: in_folder_name = INPUT_DIR in_file_name = "" if args.infilename: in_file_name = args.infilename else: in_file_name = INPUT_FILE_NAME infile = os.path.join(in_folder_name, in_file_name) print "using input data from file {}".format(infile) # set up for output file if specified out_folder_name = "" if args.outfolder: out_folder_name = args.outfolder else: out_folder_name = OUTPUT_DIR out_file_name = "" if args.outfilename: out_file_name = args.outfilename else: out_file_name = OUTPUT_FILE_NAME wb = open_workbook(infile) for s in wb.sheets(): print 'found worksheet:', s.name print # make service provider map provider_sheet = wb.sheet_by_name('Service providers') sp_ids = provider_sheet.col_values(0,1) sp_names = provider_sheet.col_values(1,1) sp_primary_emails = provider_sheet.col_values(4,1) providers = {} i=0 for sp_id in sp_ids: #print 'Service provider:', sp_id sp = ServiceProvider() sp.id = sp_id sp.name = sp_names[i] sp.primary_email = sp_primary_emails[i] i=i+1 providers[sp_id] = sp # for each activity in activities sheet, attach activity to appropriate provider activity_sheet = wb.sheet_by_name('Activities') act_ids = activity_sheet.col_values(0,1) act_provider_ids = activity_sheet.col_values(1,1) act_names = activity_sheet.col_values(3,1) act_intros = activity_sheet.col_values(5,1) act_start_dates = activity_sheet.col_values(7,1) act_last_dates = activity_sheet.col_values(8,1) act_start_times = activity_sheet.col_values(9,1) act_recurrences = activity_sheet.col_values(11,1) j=0 for activity_provider_id in act_provider_ids: provider = providers.get(activity_provider_id) if provider != None: ac = Activity() ac.id = act_ids[j] ac.name = act_names[j] ac.introduction = act_intros[j] ac.time = act_start_times[j] # work out what day the activity runs on from its start date try: start_date = datetime.strptime(act_start_dates[j], "%d/%m/%Y").date() except TypeError as e: exc_type, exc_value, exc_traceback = sys.exc_info() print "Error converting activity start date at row {}. {}".format(j, str(e)) print "Try converting the date column into text and trying again. Also check that the year has century numbers i.e.; it is 2015 rather than 15" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) ac.day = find_day_of_week(start_date) ends_on_date = datetime.strptime(act_last_dates[j], "%d/%m/%Y").date() branch = {0 : generate_one_off_occurence_list, 1 : generate_next_weekly_occurence_list, 2 : generate_next_fortnightly_occurence_list, 3 : generate_next_day_of_month_occurence_list, 4 : generate_next_date_of_month_occurence_list} next_dates = branch.get(act_recurrences[j], generate_default_occurence)(date.today(), start_date, ends_on_date) HOW_MANY = 2 ac.next_dates = resize_next_dates(next_dates, HOW_MANY) provider.addActivity(ac) else: print 'Activity id:', act_ids[j], ' has a provider_id of ', activity_provider_id, ' which does not match a service provider id' j += 1 # if e-mail switch is on then generate and send e-mails, but only if the provider has some activities if args.send: for k in providers.keys(): provider = providers.get(k) if len(provider.activities) > 0: generate_email_to_provider(provider) else: # set up output for report wb = Workbook() ws = wb.add_sheet('Kids Connect output', cell_overwrite_ok=True) # make header row ws.row(0).write(0,'provider id') ws.row(0).write(1,'provider name') ws.row(0).write(2,'e-mail') ws.row(0).write(3,'activity id') ws.row(0).write(4,'activity name') ws.row(0).write(5,'introduction') ws.row(0).write(6,'day') ws.row(0).write(7,'time') ws.row(0).write(8,'next event 1') ws.row(0).write(9,'next event 2') row_num = 1 for k in providers.keys(): provider = providers.get(k) print "processing provider {} {}".format(provider.id, provider.name) for activity in provider.activities: ws.row(row_num).write(0,provider.id) ws.row(row_num).write(1,provider.name) ws.row(row_num).write(2,provider.primary_email) ws.row(row_num).write(3,activity.id) ws.row(row_num).write(4,activity.name) ws.row(row_num).write(5,activity.introduction) ws.row(row_num).write(6,activity.day) ws.row(row_num).write(7,activity.time) if len(activity.next_dates) > 0: event_col = 8 for next_event_date in activity.next_dates: ws.row(row_num).write(event_col, next_event_date.strftime('%d-%m-%Y')) event_col += 1 row_num += 1 output_file = os.path.join(out_folder_name, out_file_name) wb.save(output_file) print "writing output data to file {}".format(output_file) print "finished!"
def read(path): # 打开文件 with open(os.path.join(os.getcwd(), path), "r") as data: # 第一行读取3个参数:全部作业数a,CNC机器数b,每个机器的同时进行操作容量c total_jobs, total_machines, max_operations = re.findall( '\S+', data.readline()) # 转为数字 number_total_jobs, number_total_machines, number_max_operations = int(total_jobs), int(total_machines), int(float( max_operations)) # 生成机器数ID 和 最大操作数 machines_list = [] # 机器表 machines_install_uninstall_time_cost_list = [] # 机器上下料时间表 # 第二行读取b个参数,RGV在对应顺序(b个)CNC机器一次上下料所需之单位时间 machines_install_uninstall_time_cost_list = re.findall( '\S+', data.readline()) # 第三行读取4个参数:RGV清洗作业时间,移动1个单位,2个单位,3个单位CNC机器间隔距离所需之时间 RGV_clean_time, RGV_movement_1_time, RGV_movement_2_time, RGV_movement_3_time = re.findall( '\S+', data.readline()) # 第四行读取2个参数: 故障率, 故障恢复时间(单位时间) CNC_break_down_rate, CNC_recovery_time_cost = re.findall( '\S+', data.readline()) # 字符串数字化 RGV_clean_time = int(RGV_clean_time) RGV_movement_1_time = int(RGV_movement_1_time) RGV_movement_2_time = int(RGV_movement_2_time) RGV_movement_3_time = int(RGV_movement_3_time) CNC_break_down_rate = float(CNC_break_down_rate) CNC_recovery_time_cost = int(CNC_recovery_time_cost) # 配置RGV车走动时间 RGV_config = RGVSystemConfig( RGV_movement_1_time, RGV_movement_2_time, RGV_movement_3_time, RGV_clean_time) for id_machine in range(1, number_total_machines + 1): machines_list.append( Machine( id_machine, number_max_operations, int( machines_install_uninstall_time_cost_list[id_machine-1]), CNC_break_down_rate, # 机器故障率 CNC_recovery_time_cost # 机器故障时间 ) ) # 初始工件ID id_job = 1 jobs_list = [] for key, line in enumerate(data): if key >= number_total_jobs: break # 按空格分隔字符串 parsed_line = re.findall('\S+', line) # 新建当前工件 job = Job(id_job) # 当前作业活动 id_activity = 1 # 当前读取行从 第一行开始 按行解析 i = 1 import random while i < len(parsed_line): # 总待加工工件即等于剩余行数k number_operations = int(parsed_line[i]) # 新建一道作业活动 activity = Activity(job, id_activity) for id_operation in range(1, number_operations + 1): # 插入操作到作业活动 machine_id_for_current_operation = int( parsed_line[i + 2 * id_operation - 1]) activity.add_operation( Operation( id_operation, # 顺序生成操作ID machine_id_for_current_operation, # 对应操作可选CNC机器ID int(parsed_line[i + 2 * id_operation]) # 初始化操作耗时 = 输入原耗时 ) ) # 随机插入故障占位 if random.random() < CNC_break_down_rate: # 随机指定故障CNC机器 activity.add_operation( Operation( -1, random.randint(1, number_total_machines), random.randint(10*60, 20*60) # 随机指定故障恢复时间 10-20分钟 ) ) job.add_activity(activity) i += 1 + 2 * number_operations id_activity += 1 jobs_list.append(job) id_job += 1 return jobs_list, machines_list, number_max_operations, RGV_config
def createActivity(label, weight, value, time): newactivity = Activity(label, weight, value, time) return newactivity
# init all for i in xrange(100): students.append(Student("student_" + str(i))) #Week = Week() for i in xrange(len(classes)): teachers.append(Teacher("teacher_" + str(i), [], [], classes[i])) #teachers.append(Teacher("teacher_1"+str(i),[],[],Lectures[i])) Week = [] #liczba dni tygodnia for i in xrange(Days_in_the_week): day = [] #liczba mozliwych zajec for j in xrange(Number_of_activities): schedules = [] for room in rooms: Day_activity = Activity(room) schedules.append(Day_activity) day.append(schedules) Week.append(day) def random_activity(type): match = False day = random.randint(0, Days_in_the_week - 1) termin = random.randint(0, Number_of_activities - 1) room = random.randint(0, len(rooms) - 1) activity = Week[day][termin][room] if activity.room.type == type: match = True return (match, activity)
def main(): # Create some activities for testing: actStart = Activity("Start", 0) actA = Activity("A", 4) actB = Activity("B", 5) actC = Activity("C", 3) actD = Activity("D", 4) actE = Activity("E", 3) actF = Activity("F", 6) actG = Activity("G", 4) actH = Activity("H", 4) actEnd = Activity("End", 0) tempActivity = Activity("temp", 5) # Just for testings # Create first graph: g = { actStart: [actA], actA: [actB, actC, actD], actB: [actF], actC: [actE], actD: [actE], actE: [actH], actF: [actG], actG: [actEnd], actH: [actEnd], actEnd: [] } # Create another graph for testing: withCircles = { actStart: [actA], actA: [actB, actC, actD], actB: [actF], actC: [actE], actD: [actE], actE: [actH], actF: [actG], actG: [actEnd, actH], actH: [actEnd, actF], actEnd: [] } ''' Check all the questions from the home work. ''' print( "============================== Question 1 ===================================" ) print("Initialize the project object - CPM_Network") newGraph = CPM_Network(g) print( "=============================================================================\n" ) print( "============================== Question 2 ===================================" ) print("Add activity to the project: %s, with the following activities %s" % (actH, [actEnd])) newGraph.addActivity(actH, [actEnd]) print( "=============================================================================\n" ) print( "============================== Question 3 ===================================" ) print("Add temporary activity i.e for testing:") print("Add activity %s to the project, with the following activities %s" % (tempActivity, [actEnd])) newGraph.addActivity(tempActivity, [actEnd]) print(str(newGraph)) print("Removing the %s activity from the project" % tempActivity) newGraph.removeActivity(tempActivity) print(str(newGraph)) print( "=============================================================================\n" ) print( "============================== Question 4 ===================================" ) print("Using another project for the test:") circles = CPM_Network(withCircles) circles.validateProject() print( "=============================================================================\n" ) print( "============================== Question 5 ===================================" ) isolatedActivities = newGraph.isolatedActivities() print("The isolated activities in the project: \n%s" % isolatedActivities) print( "=============================================================================\n" ) print( "============================== Question 6 ===================================" ) print(str(newGraph)) print( "=============================================================================\n" ) print( "============================== Question 7 ===================================" ) criticalPath, maximumDuration = newGraph.criticalPath() print("The duration of the critical path is: %r" % maximumDuration) print("The critical paths in the project: \n%s" % criticalPath) print( "=============================================================================\n" ) print( "============================== Question 8 ===================================" ) newGraph.showSlackTime() print( "=============================================================================\n" ) print( "============================== Question 9 ===================================" ) print("The project duration is: %r" % newGraph.duration) print( "=============================================================================\n" )
def test_add_activity(self): activity1 = Activity("999", "party", datetime(2020, 2, 2, 3, 20), datetime(2020, 2, 2, 4, 30), "case") self.assertTrue(self.db.add_activity(activity1, "393")) self.assertFalse(self.db.add_activity(activity1, "393"))