def GET(self,params_str):
     params=params_str.split('/')
     session = Activity.createSession('try')
     name = params[0]
     lead = params[1]
     attr =params[2]
     Activity.addTeamJson(session, name, lead, attr)
 def POST(self):
     session = Activity.createSession('try')
     if user_session.get('user')['access_level']==0:
         data  = json.loads(web.data())
         Activity.userIdAdmin(session, data["userid"], data["username"], data["mail"])
         return
     return "Permission Denied"
示例#3
0
 def authenticate(self, user_name, pswd):
     """
     Validates the user's credentials. If are valid, returns
     a user object (minus the password hash).
     """
     #login = login.strip()
     #password = password.strip()
     rslt = ldap_auth(user_name,pswd)
     if rslt:
         self.db_session = Activity.createSession('try')
         user = Activity.getUser(self.db_session,user_name)  
         if not user: 
             #user in LDAP but not in our DB
             return
         else:
             del user['password']
             return user
     else :
         #check in our own DB
         self.db_session = Activity.createSession('try')
         user = Activity.getUser(self.db_session,user_name)
         if not user:
             return
         if not self.checkPassword(pswd, user['password']):
             return
         del user['password']
         return user
 def GET(self):
     session = Activity.createSession('try')
     lead_teams = Activity.getLeadTeam(session, user_session.get('user')['name'])
     if lead_teams is None:
         return render.dashboard()
     else:
         return render.dashboard(teams=lead_teams, teamlead = True )
 def POST(self):
     params = json.loads(web.data())
     if params["workload"]=='':
         params["workload"]=1
     if params["weeks"]=='':
         params["weeks"]=0
     session = Activity.createSession('try')
     Activity.addAssignment(session, params["projectID"], params["name"], params["team"], params["personName"],params["start_date"],params["weeks"], params["desc"], workload=params["workload"],predecessor=params["predecessors"])
 def POST(self, param_str):
     params=param_str.split('/')
     session = Activity.createSession('try')
     if user_session.get('user')['access_level'] == 0:
         Activity.deletePersonByAdmin(session, params[0])
         #(session, objectId)   
         return
     else:
         return "Permisson Denied"   
def GetSupportTasksByTeam(session, teamname):
    result =  '{"supports": [\n'
    supports = list(session.query(Activity.Assignment).filter(Activity.Assignment.team==teamname).filter(Activity.Assignment.task_phase>=100))
    for i in range(len(supports)-1):
        result+= supports[i].json()[:-1]+',"display_name":"'+Activity.getDisplaynameByUsername(session, supports[i].person)+ '"},\n'
    if len(supports)>0:
        result+= supports[-1].json()[:-1]+',"display_name":"'+Activity.getDisplaynameByUsername(session, supports[-1].person)+ '"}\n'
    result+=']}'
    return result
 def GET(self, activityId):
     session = Activity.createSession('try')
     activityType = Activity.getActivityTypeById(session, activityId)
     if activityType == 'Project':
         return web.seeother('/project/'+activityId)
     elif activityType == 'Feature':
         return web.seeother('/feature/'+activityId)
     else:
         return web.seeother('/release/'+activityId)
def getCostBreakdownJson(parent_id):
    session = Activity.createSession('try')
    costs = Activity.getChildCosts(session, parent_id)
    result = '{"costs": [\n'
    for i in range(len(costs)-1):
        result += '{"name": "' + str(costs[i][0]) + '", "cost": ' + str(costs[i][1]) +', "objectId": '+str(costs[i][2])+ '},\n'
    if len(costs)>0:
        result += '{"name": "' + str(costs[-1][0]) + '", "cost": ' + str(costs[-1][1]) +', "objectId": '+str(costs[-1][2])+ '}'
    result +=']}'
    return result
    def GET(self, taskId):

        user = Activity.getAssignmentPersonName(session, taskId)
        #activId = Activity.getAssignmentParent(session, task_id[0])
        #if (user==user_session.get('user')['name'] or Activity.check_recursive_lead(session, activId, user_session.get('user')['name'])=="true" or user_session.get('user')['access_level']<=2 or 
            #Activity.getLeadTeam(session, user_session.get('user')['name']) is not None ):
        if (user==user_session.get('user')['name'] or user=='' or user=="Unstaffed" or user_session.get('user')['access_level']<=2):  
            Activity.start_task(session, taskId);
        else:
            return "Permission Denied"
 def GET(self):
     session = Activity.createSession('try')
     efjira_render = web.template.render("templates/", globals={}).jiramultiselector("efjira")
     jira_render = web.template.render("templates/", globals={}).jiramultiselector("jira")
     render._add_global(efjira_render, "efjira")
     render._add_global(jira_render, "jira")
     if Activity.getLeadTeam(session, user_session.get('user')['name']) is not None or user_session.get('user')['access_level']<=2 :
         return render.features(feature_editable=True)
     else:
         return render.features(feature_editable=False)
 def GET(self, feature):
     session = Activity.createSession('try')
     user = user_session.get('user')
     efjira_render = web.template.render("templates/", globals={}).jiramultiselector("efjira")
     epjira_render = web.template.render("templates/", globals={}).jiramultiselector("epjira")
     jira_render = web.template.render("templates/", globals={}).jiramultiselector("jira")
     render._add_global(efjira_render, "efjira")
     render._add_global(epjira_render, "epjira")
     render._add_global(jira_render, "jira")
     editable = Activity.check_recursive_lead(session, feature, user['name'])=="true" or Activity.getLeadTeam(session, user['name']) is not None or user['access_level']<=2
     return render.feature(feature, editable)
 def POST(self, param_str):
     session = Activity.createSession('try')
     params = param_str.split('/')
     user = Activity.getAssignmentPersonName(session, params[0])
     #activId = Activity.getAssignmentParent(session, params[0])
     #if(user==user_session.get('user')['name'] or Activity.check_recursive_lead(session, activId, user_session.get('user')['name'])=="true" or user_session.get('user')['access_level']<=2 or 
         #Activity.getLeadTeam(session, user_session.get('user')['name']) is not None ):
     if (user==user_session.get('user')['name'] or user=='' or user=="Unstaffed" or user_session.get('user')['access_level']<=2):
         Activity.updateAssignmentStatus(session, params[0], params[1])
     else:
         return "Permission Denied!"      
 def POST(self, task_id):
     session = Activity.createSession('try')
     user = Activity.getAssignmentPersonName(session, task_id)
     #activId = Activity.getAssignmentParent(session, task_id)
     #if (Activity.check_can_exe_assignment(session, task_id, user_session.get('user')['name']) or
         #user_session.get('user')['name']==user or Activity.check_recursive_lead(session, activId, user_session.get('user')['name'] )=="true" or user_session.get('user')['access_level']<=2 or 
         #Activity.getLeadTeam(session, user_session.get('user')['name']) is not None ):
     if (user==user_session.get('user')['name'] or user=='' or user=="Unstaffed" or user_session.get('user')['access_level']<=2):
         params = json.loads(web.data())
         Activity.forecast_task(session,task_id,forecast_start_date = params["start_date"], forecast_end_date = params["end_date"])
     else :
         return "Permission Denied"
 def POST(self,taskid):
     #check permission
     session = Activity.createSession('try')
     user = Activity.getAssignmentPersonName(session, taskid)
     #activId = Activity.getAssignmentParent(session, taskid)
     #if(user==user_session.get('user')['name'] or Activity.check_recursive_lead(session, activId, user_session.get('user')['name'])=="true" or user_session.get('user')['access_level']<=2 or 
        #Activity.getLeadTeam(session, user_session.get('user')['name']) is not None ):
     if (user==user_session.get('user')['name'] or user=='' or user=="Unstaffed" or user_session.get('user')['access_level']<=2):
         desc = json.loads(web.data())
         Activity.updateAssignmentNote(session, taskid, desc["newContent"])
     else:
         raise PermissionDeny()
 def GET(self,project):
     session = Activity.createSession('try')
     user = user_session.get('user')
     editable = False
     if Activity.check_recursive_lead(session, project, user['name'])=='true' or user['access_level']<=2:
         editable = True
     epjira_render = web.template.render("templates/", globals={}).jiramultiselector("epjira")
     render._add_global(epjira_render, "epjira")
     taskTable_render = web.template.render("templates/", globals={'session':user_session}).taskTable(popLink = "/assignments/" + project)
     render._add_global(taskTable_render,"taskTable")
     gantt_render = web.template.render("templates/", globals={'session':user_session}).ganttChart(popLink = "/assignments/" + project, canEdit = editable, showProj = True)
     render._add_global(gantt_render,"ganttChart")
     return render.project(project, editable)
示例#17
0
 def login(self, user):
     """
     Set the user as logged in.
     """
     record_time = str(datetime.utcnow())
     self.db_session = Activity.createSession('try')
     user = Activity.updateUser(self.db_session,user['objectId'], record_time)
     try:
         del user['password']
     except KeyError:
         pass
     self.session.user = user
     return
 def GET(self, release):
     session=Activity.createSession('try')
     feature_editable = False 
     render_jira = web.template.render("templates/", globals={}).jiramultiselector("jira")
     render_efjira = web.template.render("templates/", globals={}).jiramultiselector("efjira")
     render_allocation = web.template.render("templates/", globals={}).allocationtool(release_id=release)
     render._add_global(render_allocation,"allocation_tool")
     render._add_global(render_efjira, "efjira")
     render._add_global(render_jira, "jira")
     if Activity.getLeadTeam(session, user_session.get('user')['name']) is not None or user_session.get('user')['access_level']<=2:
         feature_editable = True
     if user_session.get('user')['access_level']<=2 or Activity.check_recursive_lead(session, release, user_session.get('user')['name'])=='true':
         return render.release(release, True, True)
     else:
         return render.release(release, False, feature_editable)
示例#19
0
    def import_fit_data(self):
        """
        Will look at the file location for our google fit files and loop though imported them by category. It will
        ignore any walking activity to remove clutter. Then call a function to move any read files to the ./imported
        folder
        """
        categories = ['Running', 'Yoga', 'Weights', 'Wal']
        for category in categories:
            file_names = self.get_tcx_files(category)
            for file in file_names:
                if category is not 'Wal':
                    tcx = tcxparser.TCXParser(self._activitiesLocation + '\\' +
                                              file)
                    date_str, duration, pace = self.convert_data(tcx)
                    name = category + " - " + date_str
                    notes = tcx.activity_notes
                    calories = tcx.calories
                    heart_rate = self.get_heart_rate(tcx)
                    distance = tcx.distance

                    fit_activity = Activity.Activity(category, name, date_str,
                                                     notes)
                    fit_activity.add_fit_entry(calories, heart_rate, pace,
                                               duration, distance)
                self.move_read_files(file)
def convert_user_input_to_object():
    # date, type and duration are mandatory
    date_to_save = input_date.get()
    type_to_save = input_type.get()
    duration_to_save = float(input_duration.get())
    # check if average speed is empty and set null if it is empty, if it is not empty convert to float
    if input_average_speed.get() == "":
        average_speed_to_save = None
    else:
        average_speed_to_save = float(input_average_speed.get())
    # info is optional and anything can be entered, but check if empty to set null
    if input_info.get() == "":
        info_to_save = None
    else:
        info_to_save = input_info.get()
    # check if distance is empty and set null, otherwise convert to float
    if input_distance.get() == "":
        distance_to_save = None
    else:
        distance_to_save = float(input_distance.get())
    # create activity_to_save object with user input values
    activity_to_save = Activity(date_to_save, type_to_save, distance_to_save,
                                duration_to_save,average_speed_to_save, info_to_save)
    # check if date, type and duration are not empty because they are mandatory, raise ValueError if empty
    if date_to_save == "" or type_to_save == "" or duration_to_save == "":
        raise ValueError
    else:
        return activity_to_save
示例#21
0
def get_active_window_x():
    full_detail = a.get_active_window_raw()
    if full_detail != None:
        try:
            detail_list = full_detail.split(" - ")
            new_window_name = detail_list[-1]
            return new_window_name
        except SystemError:
            print("You have closed or opened a file!")
def EditSupportTask(session, id, st):
    task = list(session.query(Activity.Assignment).filter(Activity.Assignment.objectId == id))[0]
    task.person = st["person"]
    task.task_phase = st["type"]
    task.planned_start_date = st["start_date"]
    task.planned_num_weeks = st["duration"]
    task.forecast_end_date = Activity.getEndDate(st['start_date'], float(st["duration"]))
    task.activity_id = st["activity_id"]
    task.work_load = st["workload"]
    session.commit()
 def POST(self):
     session = Activity.createSession('try')
     web_input = web.input(new_picture={})
     person_profile = {'objectId': web_input['objectId']}
     teams = Activity.getLeadTeam(session, user_session.get('user')['name'])
     rtn_url =  web_input['rtn_url']
     del web_input['rtn_url']
     if web_input.new_picture.filename!='':  #update the profile image
         origin_full_filename="images/profile/origin_"  +web_input.new_picture.filename
         file_ext = web_input.new_picture.filename.split('.')[-1]
         fout = open( origin_full_filename,'wb+') 
         fout.write(web_input.new_picture.file.read())
         fout.close()
         im = Image.open(origin_full_filename)
         thumbnail_file_name= md5(open(origin_full_filename, 'rb').read()).hexdigest() + '.' + file_ext
         im.thumbnail((140,140), Image.ANTIALIAS)
         im.save("images/profile/" + thumbnail_file_name)
         web_input.picture = thumbnail_file_name
         remove(origin_full_filename)
     if user_session.get('user')['access_level'] <=2:   #manager             
         person_profile.update(web_input)
         del person_profile['new_picture']
     elif teams is not None:   #TEAMLEAD
         for team in teams:
             if Activity.check_person_on_team(session, web_input['objectId'], team.objectId) :
                 person_profile['display_name'] = web_input['display_name']
                 person_profile['team'] = web_input['team']
                 person_profile['location'] = web_input['location']
                 person_profile['user_type'] = web_input['user_type']
                 person_profile['email'] = web_input['email']
                 person_profile['name'] = web_input['email'].split('@')[0]
                 break
     if user_session.get('user')['display_name'] == web_input['display_name']:  #person himself
         person_profile['email'] = web_input['email']
         person_profile['name'] = web_input['email'].split('@')[0]
         if 'picture' in web_input.keys():
             person_profile['picture'] = web_input['picture']
         person_profile['mobile_num'] = web_input['mobile_num']
     Activity.editPersonProfile(session, person_profile)
     user_session.user.update(person_profile)
     raise web.seeother(rtn_url)         
def defineOperation(request):
    # leio o objeto request que está em json e transformo em um objeto chave-valor
    message = json.loads(request)
    if message["op"] == "list":  # aí consigo acessar assim os dados do json
        return json.dumps(
            [activity.__dict__ for activity in controller.getActivities()])
    elif message["op"] == "add":
        newActivity = activity.Activity(message["title"],
                                        message["description"],
                                        message["closingDate"])
        controller.addActivity(newActivity)
    elif message["op"] == "up":
        newActivity = activity.Activity(message["title"],
                                        message["description"],
                                        message["closingDate"])
        controller.updateActivity(int(message["id"]), newActivity)
    elif message["op"] == "end":
        controller.finishActivity(int(message["id"]))
    # transformo meus objetos em json novamente com esse método dumps
    return json.dumps(
        [activity.__dict__ for activity in controller.getActivities()])
 def GET(self, team):
     session=Activity.createSession('try')
     team_editable = False 
     allocation_render = web.template.render("templates/", globals={}).allocationtool(team_id = team, unstaffed = True)
     render._add_global(allocation_render, "allocation_tool")
     teamTable_render = web.template.render("templates/", globals={'session':user_session}).taskTable(popLink = "/filledassignmentsbyteam/" + team,showAddBtn=False,
                                                                                                      fields=["index", "name", "activity", "person", "start_time", "end_time" ,"status", "description", "operation"],
                                                                                                      reorder=False)
     render._add_global(teamTable_render,"teamTable") 
     if Activity.getLeadTeam(session, user_session.get('user')['name']) is not None:
         tleads = Activity.getTeamLead(session, team)
         for params in tleads:
             if params ==  user_session.get('user')['name']:
                 team_editable = True
     if user_session.get('user')['access_level']<=1 :
         support_render = web.template.render("templates/", globals={}).support(team, True)
         render._add_global(support_render, "support")
         return render.team(team, True)
     else: 
         support_render = web.template.render("templates/", globals={}).support(team, False)
         render._add_global(support_render, "support")
         return render.team(team,team_editable)
示例#26
0
 def ingest_data(self):
     with open(self._file_path) as csv_file:
         csv_reader = csv.reader(csv_file, delimiter=',')
         line_count = 0
         for row in csv_reader:
             if line_count == 0:
                 line_count += 1
             else:
                 date = self.convert_date(row[0])
                 activities = row[5].split("|")
                 note = row[6]
                 for activity in activities:
                     activity = self.normalize_activity(activity)
                     Activity.Activity(activity, activity + " - " + date, date, note).add_entry()
                 line_count += 1
示例#27
0
    def send_next_intervention(self):
        """
        Send next intervention in line.
            """
        if self.lined_up_intervention is not None:
            if self.lined_up_intervention.created_at < self.current_time:
                self.lined_up_intervention = None

        if self.lined_up_intervention is not None:
            if self.lined_up_intervention.created_at == self.current_time:
                self.received_intervention_current_hour = 1
                schedule_profile = str(self.agent_profile[0])
                activity_id = self.lined_up_intervention.activity_id
                activity_params = self.agent_profiles_params[
                    "activity_profiles"][schedule_profile][activity_id]
                activity = Activity(
                    label=activity_id,
                    duration_mean=round(
                        randint(
                            activity_params["duration_hour_range"][0] *
                            self.NUMBER_SECONDS_HOUR,
                            activity_params["duration_hour_range"][1] *
                            self.NUMBER_SECONDS_HOUR) / self.time_granularity),
                    duration_sd=round(
                        activity_params["standard_deviation_seconds"][0] /
                        self.time_granularity),
                    start_time_activity=self.current_time,
                    end_time_activity=None,
                    intervention=True,
                    fatigue=self.fatigue)

                intervention_accepted = self.suggest_intervention(
                    self.lined_up_intervention, activity)

                if intervention_accepted:
                    self.schedule_intervention_activity(
                        self.lined_up_intervention, activity)
                    self.reward.append(
                        self.get_reward_value("suggestion_accepted", activity))
                else:
                    self.lined_up_intervention = None
                    self.reward.append(
                        self.get_reward_value("suggestion_rejected", None))
            else:
                self.reward.append(0)
        else:
            self.reward.append(0)
def AddSupportTask(session, st):
    if st["duration"]=='':
        durationCount = 0
        expectedEnd = ''
    else: 
        durationCount = st["duration"]
        expectedEnd = Activity.getEndDate(st['start_date'], float(st["duration"]))
    if st["type"]=="300":
        setname = st["person"]+" On Vacation"
    elif st["type"] == "301":
        setname = "Other"
    else:
        setname = st["team"] +":"+st["person"] + " Support Task"
    task = Activity.Assignment(name = setname, team = st["team"], activity_id = st["activity_id"],person = st["person"], task_phase = st["type"],\
                               planned_start_date = st["start_date"],planned_num_weeks = durationCount, work_load=st["workload"], forecast_start_date='',\
                               forecast_end_date = expectedEnd,actual_start_date='', actual_end_date='', status = 0, predecessor="[]", successor="[]",description='')
    session.add(task)
    session.commit()
def getActivityProgressInfo(activity):
    info = {"warning":False, "delaytime":0, "msg":"", "children":0, "delayed":0}
    session = Activity.createSession("try")
    if activity.activity_type == "Release" or activity.activity_type == "Feature":
        query_table = Activity.Activity
        filter_col = Activity.Activity.parent_id
        recursive_func = getActivityProgressInfo
    else:
        query_table = Activity.Assignment
        filter_col = Activity.Assignment.activity_id
        recursive_func = getTaskProgressInfo
    children = session.query(query_table).filter(filter_col == activity.objectId)
    for child in children:
        info["children"] += 1
        if json.loads(recursive_func(child))["warning"]: info["delayed"] += 1
    if info["delayed"] > 0: info["warning"] = True
    session.close()
    return json.dumps(info)
示例#30
0
    def get_planned_activity(self):
        """
        Check if there is any planned activity arriving at a certain moment in time.
        Return the activity object if an activity occurs.
        """
        time_of_day = (self.current_time % 86400) / self.time_granularity
        activity = None

        for key in self.activities:
            if self.activities[key]['start_time'] == time_of_day:
                activity = Activity(
                    self.activities[key]['label'],
                    self.activities[key]['duration'] / self.time_granularity,
                    self.activities[key]['standard_deviation'] /
                    self.time_granularity, self.current_time, 0)
                if activity.label == "sleep":
                    self.register_occurrence_sleep_activities_current_day()
                return activity
        return activity
    def create_activities(self, index):
        activities = []
        activity_count = 0
        for activity in self.matching_activity[self.user_preferences[index]]:
            if activity_count < self.MAX_ACTIVITY_PER_PAGE:
                activity_count += 1
                print(activity)
                print()
                activities.append(
                    Activity(category=self.user_preferences[index],
                             country=self.city,
                             location=activity["location_string"],
                             activity_name=activity["name"],
                             address=activity["address"],
                             description=activity["description"],
                             web_url=activity["web_url"],
                             image_link=activity["photo_url"]))

        return activities
 def POST(self, team_name):
     session = Activity.createSession('try')
     if user_session.get('user')['access_level']<=1:
         data  = json.loads(web.data())
         if data["accesslevel"] == '':
             al = 4
         else:
             al = data["accesslevel"]
         Activity.newPerson(session, team=team_name, display_name=data["name"], email=data["email"], position=data["position"], 
                            location=data["location"], user_type=data["user_type"],access_level=al,mobile_num=data["mobile"])
         return
     #check if modified by the team lead
     leadteams = Activity.getLeadTeam(session, user_session.get('user')['name'])
     if leadteams is not None:
         for team in leadteams:
             if team_name==team.name:
                 data  = json.loads(web.data())
                 Activity.newPerson(session, team=team_name, display_name=data["name"], email=data["email"], position=data["position"], 
                                    location=data["location"], user_type=data["user_type"],mobile_num=data["mobile"])
                 return
     return "Permission Denied"
示例#33
0
def makeOptions(act: Activity, frame: tk.Frame):
    # 2dim
    def update2dim(*args, **kw):
        try:
            x = act.getValue('arg_value_2dim_x')
            y = act.getValue('arg_value_2dim_y')

            act.extras['arg_value'][2][0] = x
            act.extras['arg_value'][2][1] = y
            if act.extras['upDefault'] != None:
                act.extras['upDefault'](act.extras['layer_select'])
        except Exception as e:
            print(e)

    def updatefloat(*args, **kw):
        try:
            floatvalue = act.getValue('arg_value_float')
            act.extras['arg_value'][2] = floatvalue
            if act.extras['upDefault'] != None:
                act.extras['upDefault'](act.extras['layer_select'])
        except Exception:
            return

    def updateint(*args, **kw):
        try:
            intvalue = act.getValue('arg_value_int')
            act.extras['arg_value'][2] = intvalue
            if act.extras['upDefault'] != None:
                act.extras['upDefault'](act.extras['layer_select'])
        except Exception:
            return

    f2dim = act.Frame(frame, width=frame.w, height=frame.py(50))
    act.label('arg_name',
              'null',
              frame=frame,
              x=frame.px(25),
              width=frame.px(50),
              y=frame.py(25) - 30)
    act.entry('arg_value_2dim_x',
              1,
              int,
              frame=f2dim,
              y=30,
              x=f2dim.px(25),
              width=f2dim.px(50),
              justify=tk.CENTER).bind('<KeyRelease>', update2dim)
    act.entry('arg_value_2dim_y',
              1,
              int,
              frame=f2dim,
              y=60,
              x=f2dim.px(25),
              width=f2dim.px(50),
              justify=tk.CENTER).bind('<KeyRelease>', update2dim)

    ffloat = act.Frame(frame, width=frame.w, height=frame.py(50))
    act.entry('arg_value_float',
              1,
              float,
              frame=ffloat,
              y=30,
              x=ffloat.px(25),
              width=ffloat.px(50),
              justify=tk.CENTER).bind('<KeyRelease>', updatefloat)
    fint = act.Frame(frame, width=frame.w, height=frame.py(50))
    act.entry('arg_value_int',
              1,
              int,
              frame=fint,
              y=30,
              x=fint.px(25),
              width=fint.px(50),
              justify=tk.CENTER).bind('<KeyRelease>', updateint)

    foptions = act.Frame(frame, width=frame.w, height=frame.py(50))

    lista = act.Listbox(x=foptions.px(25),
                        width=foptions.px(50),
                        height=foptions.w,
                        frame=foptions)
    act.ScroolbarY(lista,
                   x=foptions.px(25) - 20,
                   width=20,
                   height=foptions.w,
                   frame=foptions)

    def putArgs(arg):
        if act.extras['last_arg_frame'] != None:
            act.extras['last_arg_frame'].place_forget()
        act.setVar('arg_name', arg[0])
        act.extras['arg_value'] = arg
        if arg[1] == 'float':
            act.setVar('arg_value_float', arg[2])
            ffloat.actplace(y=frame.py(25))
            act.extras['last_arg_frame'] = ffloat
        elif arg[1] == 'int':
            act.setVar('arg_value_int', arg[2])
            fint.actplace(y=frame.py(25))
            act.extras['last_arg_frame'] = fint
        elif arg[1] == '2dim':
            act.setVar('arg_value_2dim_x', arg[2][0])
            act.setVar('arg_value_2dim_y', arg[2][1])
            f2dim.actplace(y=frame.py(25))
            act.extras['last_arg_frame'] = f2dim
        elif arg[1] == 'options':
            lista.delete(0, tk.END)
            for op in arg[3]:
                lista.insert(tk.END, op)
            lista.selection_set(arg[2])
            foptions.actplace(y=frame.py(25))
            act.extras['last_arg_frame'] = foptions

    def listaChange(*args, **kw):
        if lista.size() <= 0:
            return
        if lista.size() == 0:
            selc = 0
        else:
            selc = lista.curselection()
            if len(selc) >= 1:
                selc = selc[0]
            else:
                return
        act.extras['arg_value'][2] = act.extras['arg_value'][4][selc]

    lista.bind('<<ListboxSelect>>', listaChange)

    return putArgs
示例#34
0
def ui(act: Activity):
    act.text('Entrada', x=act.px(1), y=act.py(0.3), height=act.py(5))
    act.entry('x',
              1,
              int,
              x=act.px(5),
              width=act.px(5),
              height=act.py(5),
              justify=tk.CENTER)
    act.entry('y',
              1,
              int,
              x=act.px(10),
              width=act.px(5),
              height=act.py(5),
              justify=tk.CENTER)
    act.entry('z',
              1,
              int,
              x=act.px(15),
              width=act.px(5),
              height=act.py(5),
              justify=tk.CENTER)
    fArch = act.Frame(act.frame, width=act.px(30), height=act.py(84))
    fEdit = act.Frame(act.frame, width=act.px(68), height=act.py(90))
    fSet = act.Frame(fEdit, width=fEdit.px(50), height=act.py(90))
    fAdd = act.Frame(act.frame, width=fEdit.w, height=act.py(89))

    lista = act.Listbox(x=20,
                        frame=fArch,
                        width=fArch.w - 20,
                        height=fArch.h,
                        font=Font.Font(size=14))
    act.ScroolbarY(lista, frame=fArch, width=20, height=fArch.h)

    params = act.Listbox(frame=fEdit,
                         x=21,
                         y=act.py(6),
                         width=fEdit.px(50),
                         height=fEdit.py(94),
                         font=Font.Font(size=16))
    act.ScroolbarY(params,
                   frame=fEdit,
                   y=act.py(6),
                   width=20,
                   height=fEdit.py(94))

    possibleLayers = act.Listbox(frame=fAdd,
                                 x=21,
                                 y=act.py(6),
                                 width=fAdd.px(50),
                                 height=fAdd.py(94),
                                 font=Font.Font(size=16))
    act.ScroolbarY(possibleLayers,
                   frame=fAdd,
                   y=act.py(6),
                   width=20,
                   height=fAdd.py(94))

    act.label('nomeCamada',
              "NULL",
              frame=fEdit,
              x=fEdit.px(1),
              y=act.py(0.3),
              height=act.py(5))

    def load(*args, **kw):
        fileName = act.askLoad()
        if fileName == '': return
        err, msg = act.extras['arch'].load(fileName)
        if err < 0:
            messagebox.showerror(title="Falha ao carregar Arquitetura",
                                 message=msg)
        else:
            act.setVar('x', act.extras['arch'].entrada[0], True)
            act.setVar('y', act.extras['arch'].entrada[1], True)
            act.setVar('z', act.extras['arch'].entrada[2], True)
            updateArq()

    def compile(*args, **kw):
        fileName = act.askSaveAs()
        if fileName == '': return
        with open(fileName, 'w') as file:
            act.extras['arch'].compile(file)

    menubar = tk.Menu(act.frame)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Open", command=load)
    filemenu.add_command(label="Save", command=compile)
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=act.finishprogram)
    menubar.add_cascade(label="File", menu=filemenu)
    act.root.config(menu=menubar)
    act.button('make',
               'Compilar',
               frame=fAdd,
               x=fAdd.px(25),
               y=act.py(0.3),
               width=fAdd.px(23),
               height=act.py(5),
               command=compile)

    act.extras['arch'] = Arquitetura()

    def updateArq(*args, **kw):
        try:
            entrada = [act.getValue('x'), act.getValue('y'), act.getValue('z')]
        except Exception:
            return
        act.extras['arch'].update(entrada)
        lista.delete(0, tk.END)
        for camada in act.extras['arch'].camadas:
            lista.insert(tk.END, camada['name'])
            if not camada['ok']:
                lista.itemconfig(tk.END, {'fg': '#f00'})

    act.getEntry('x').bind('<KeyRelease>', updateArq)
    act.getEntry('y').bind('<KeyRelease>', updateArq)
    act.getEntry('z').bind('<KeyRelease>', updateArq)
    for layer in LAYERS:
        possibleLayers.insert(tk.END, layer['name'])
    possibleLayers.selection_set(0)
    fArch.actplace(y=act.py(6))

    def putParam(*args, **kw):
        if params.size() <= 0:
            return
        if params.size() == 0:
            selc = 0
        else:
            selc = params.curselection()
            if len(selc) >= 1:
                selc = selc[0]
            else:
                return
        putArgs(act.extras['layer_select']['args'][selc])

    def addLayer(*args, **kw):
        if possibleLayers.size() <= 0:
            return
        if possibleLayers.size() == 0:
            select = 0
        else:
            select = possibleLayers.curselection()
            if len(select) >= 1:
                select = select[0]
            else:
                return
        act.extras['arch'].add(LAYERS[select])

        def updefault(layer):
            LAYERS[select] = copy.deepcopy(layer)

        act.extras['upDefault'] = updefault
        # fAdd.place_forget()
        updateArq()
        # editLayer(act.extras['arch'].camadas[-1], -1)

    def editLayer(layer, index):
        act.setVar('nomeCamada', layer['name'] + f' {layer["saida"]}')
        act.extras['layer_select'] = layer
        params.bind('<<ListboxSelect>>', None)
        params.delete(0, tk.END)
        for arg in layer['args']:
            params.insert(tk.END, arg[0])
        fEdit.actplace(x=act.px(32))
        params.selection_set(0, 0)
        params.bind('<<ListboxSelect>>', putParam)
        act.extras['lastplace_set_or_edit'] = fEdit
        act.extras['index_edit_layer'] = index
        putParam()

    act.button('addLayer',
               'Nova camada',
               frame=fAdd,
               x=fAdd.px(1),
               y=act.py(0.3),
               width=fAdd.px(23),
               height=act.py(5),
               command=addLayer)

    def confirm(*args, **kw):
        if act.extras['last_arg_frame'] != None:
            act.extras['last_arg_frame'].place_forget()
            act.extras['last_arg_frame'] = None
        updateArq()
        fEdit.place_forget()
        act.extras['lastplace_set_or_edit'] = fAdd
        fAdd.actplace(x=act.px(32))

    def RemoveLayer(*a, **kw):
        if act.extras['last_arg_frame'] != None:
            act.extras['last_arg_frame'].place_forget()
            act.extras['last_arg_frame'] = None
        act.extras['arch'].remove(act.extras['index_edit_layer'])
        updateArq()
        fEdit.place_forget()
        fAdd.actplace(x=act.px(32))
        act.extras['lastplace_set_or_edit'] = fAdd

    act.extras['last_arg_frame'] = None
    act.button('oklayer',
               'confirm',
               frame=fEdit,
               x=fEdit.px(85),
               y=act.py(0.3),
               width=fEdit.px(9),
               height=act.py(5),
               command=confirm)
    act.button('removeLayer',
               'Remove',
               frame=fEdit,
               x=fEdit.px(75),
               y=act.py(0.3),
               width=fEdit.px(9),
               height=act.py(5),
               command=RemoveLayer)
    # fEdit.actplace(x=act.px(32))
    fSet.actplace(x=fEdit.px(50) + 20)
    #### continuar
    putArgs = makeOptions(act, fSet)
    fAdd.actplace(x=act.px(32))

    def listaChange(*args, **kw):
        if lista.size() <= 0:
            return
        if lista.size() == 0:
            selc = 0
        else:
            selc = lista.curselection()
            if len(selc) >= 1:
                selc = selc[0]
            else:
                return
        fAdd.place_forget()
        act.extras['upDefault'] = None
        editLayer(act.extras['arch'].camadas[selc], selc)

    lista.bind('<<ListboxSelect>>', listaChange)
示例#35
0
from flask import Flask, request, Response, abort, jsonify
from flask_cors import CORS
from Authentication import *
from Activity import *
from firebase import firebase
import datetime

app = Flask(__name__)
CORS(app)

auth = Authentication()
act = Activity()

#firebase header
url = 'https://accenture-hackathon-2019-11a52.firebaseio.com/'  #firebase db url
messager = firebase.FirebaseApplication(url)


####Authentication####
#register
@app.route("/register", methods=["POST"])
def register():
    data = request.form.to_dict()
    result = auth.register(data)
    if result is None:
        resp = Response("Success", status=200, mimetype='application/json')
    else:
        # js = json.dumps(result)
        resp = Response(result, status=404, mimetype='application/json')
    return resp
示例#36
0
from sys import stderr
import os.path

import Activity

"""
Script pour injecter dans la base de données des activités de demo
"""

DB_NAME = 'database.db'

activity1 = Activity.Activity("0",
                     "name1",
                     "name1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
                     1,
                     20,
                     0,
                     50,
                     str(0),
                     [str(0), str(1), str(2)])

activity2 = Activity.Activity("1",
                              "name2",
                              "name2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
                              1,
                              20,
                              50,
                              100,
                              str(2),
                              [str(3), str(4), str(5)])
 def award_new_activity(self):
     global currentActivity
     tempActivity = Activity(sm.actNameInput.text,
                             int(sm.actPointsInput.text))
     currentActivity = tempActivity
 def POST(self):
     params = json.loads(web.data())
     session = Activity.createSession("try")
     return Activity.getFeatureLoad(session, params["numofweeks"], params["startdate"], params["releasetuple"], params["teams"])
def main():

    lacOperon = LacOperon(1, 0, 0)
    X = lacOperon.GetGraph()
    activity = list()
    f = lacOperon.GetFunctionList()
    for node in X.nodes():
        iMap = lacOperon.GetIMap()
        A = Activity.Activity(X, f, node, iMap)
        A.ComputeActivity()
        activity.append(A.GetActivity())
    print "activity:", activity
    sys.exit(0)

    vpc = VPC(3, 0)
    g = vpc.GetGraph()

    activity = list()
    f = vpc.GetFunctionList()
    for node in g.nodes():
        iMap = vpc.GetIMap()
        A = Activity.Activity(g, f, node, iMap)
        A.ComputeActivity()
        activity.append(A.GetActivity())
    print "activity:", activity
    sys.exit(0)
    '''
    f = vpc.GetFunctionList()
    n = nx.number_of_nodes(g)
    m = nx.number_of_edges(g)

    F = vpc.F
    F.SetParallel()
    #F.SetBlockSequence([ [0,1,2,3,4,6,8,9,10,11,12,13], [5,7] ])

    p = phase_space.PhaseSpace(F)

    periodicPoints = p.GetPeriodicPoints()

    cNum = 0
    for cycle in periodicPoints :
        print "Cycle <%i>:" % cNum
        for xIndex in cycle :
            print "\t", F.tupleConverter.IndexToTuple( xIndex )
        cNum += 1

    sys.exit(0)
    '''

    M = MendozaAlvarezBuylla()
    X = M.GetGraph()
    activity = list()

    for node in X.nodes():
        f = M.GetFunctionList()
        A = Activity.Activity(X, f, node)
        A.ComputeActivity()
        activity.append(A.GetActivity())
    print "Average activity for network %s:" % M.GetName()
    print activity

    M = I5GroupTTSS()
    X = M.GetGraph()
    activity = list()

    for node in X.nodes():
        f = M.GetFunctionList()
        A = Activity.Activity(X, f, node)
        A.ComputeActivity()
        activity.append(A.GetActivity())
    print "Average activity for network %s:" % M.GetName()
    print activity

    M = MammalianCellCyclePBN()
    X = M.GetGraph()
    activity = list()

    for node in X.nodes():
        f = M.GetFunctionList()
        A = Activity.Activity(X, f, node)
        A.ComputeActivity()
        activity.append(A.GetActivity())
    print "Average activity for network %s:" % M.GetName()
    print activity
 def POST(self):
     params=json.loads(web.data())
     session = Activity.createSession('try')
     return Activity.getWorkloadFilter(session,params["numofweeks"],params["startdate"],params["releasetuple"],params["teams"])
 def GET(self):
     session = Activity.createSession('try')
     return Activity.getProgramLeads(session)
 def GET(self):
     session = Activity.createSession('try')
     return Activity.getAllLeadsJson(session)
 def GET(self,team):
     session = Activity.createSession('try')
     return Activity.getTeamLeadsJson(session,team)   
    def build(self):
        global sm
        sm = Screens()

        Window.size = (300, 570)
        Window.clearcolor = (1, 1, 1, .2)

        ball = Activity("ball", 10)
        soccer = Activity("soccer", 20)
        choir = Activity("choir", 5)
        lead_prayer = Activity("lead prayer", 100)
        help_prepare = Activity("help with assembly", 50)
        singing_o_canada = Activity("singing o canada", 200)
        ram_of_the_month = Activity("ram of the month", 1000)
        assisting_others = Activity("helping a student", 70)
        helpful_student = Activity("giving a student a pencil", 90)
        character_award = Activity("character award", 80)
        activities = [
            ball, soccer, choir, lead_prayer, help_prepare, singing_o_canada,
            ram_of_the_month, assisting_others, helpful_student,
            character_award
        ]

        student1 = Student("Timofey", "Hartanovich", 1, 12)
        student2 = Student("Jorge", "Sumi", 2, 12)
        student3 = Student("Jermaine", "Cole", 3, 12)
        student4 = Student("Marshal", "Matthers", 4, 12)
        student5 = Student("Killy", "", 5, 12)
        student6 = Student("Post", "Malone", 6, 12)
        student7 = Student("Trey", "Songz", 7, 12)
        student8 = Student("Kanye", "West", 8, 12)
        students = [
            student1, student2, student3, student4, student5, student6,
            student7, student8
        ]

        currentActivity = ball
        currentStudent = student1

        def refreshCallBack(text1):
            global currentActivity
            global currentStudent
            global lastScreen
            sm.activityName.clear_widgets()
            sm.box2.clear_widgets()
            sm.transition.direction = 'left'
            sm.current = 'Screen2'
            text = text1
            for i in students:
                currentStudent = i
                currentStudent.select(False)
            for i in activities:
                if i.get_activity() == text:
                    text2 = str(i.get_points()) + " points"
                    currentActivity = i
                    break

            label = Label(text=text,
                          font_name='images/FFF_Tusj.ttf',
                          font_size=sm.width / 20,
                          size_hint=(0.7, 1))
            label2 = Label(text=text2,
                           font_name='images/FFF_Tusj.ttf',
                           font_size=sm.width / 30,
                           size_hint=(0.2, 1))
            add_points_button = Button(text="+",
                                       font_name='images/FFF_Tusj.ttf',
                                       font_size=sm.width / 30,
                                       size_hint=(0.05, 1))
            add_points_button.bind(on_press=on_click)
            back_button = Button(text="<-",
                                 font_name='images/FFF_Tusj.ttf',
                                 font_size=sm.width / 25,
                                 size_hint=(0.05, 1))
            add_points_button.bind(on_press=on_click)
            back_button.bind(on_press=backButtonCallBack)
            sm.activityName.add_widget(back_button)
            sm.activityName.add_widget(label)
            sm.activityName.add_widget(label2)
            sm.activityName.add_widget(add_points_button)

            for i in students:
                currentStudent = i
                text = 'Points: ' + str(i.get_points())
                label = Label(text=text,
                              font_name='images/FFF_Tusj.ttf',
                              font_size=sm.width / 30,
                              size_hint=(0.2, 1),
                              color=(0, 0, 0, 1))
                checkbox = CheckBox(size_hint=(0.1, 1))
                checkbox.text = i.get_name()
                checkbox.bind(active=on_checkbox_active)
                student_button = Button()
                student_button.text = i.get_name()
                student_button.background_normal = ''
                student_button.background_color = .15, .7, .2, .7
                student_button.size_hint = 0.7, 1
                student_button.bind(on_press=callback2)
                sm.box2.add_widget(student_button)
                sm.box2.add_widget(label)
                sm.box2.add_widget(checkbox)

        def callback(instance):
            refreshCallBack(instance.text)

        def backButtonCallBack(instance):
            sm.activityName.clear_widgets()
            sm.transition.direction = 'right'
            sm.current = 'menu'

        def newActivityCallBack(instance):
            sm.transition.direction = 'left'
            sm.current = 'activityCreate'

        def backStudentButtonCallBack(instance):
            global currentActivity
            text = currentActivity.get_activity()
            sm.activityName.clear_widgets()
            refreshCallBack(text)
            sm.transition.direction = 'right'
            sm.current = 'Screen2'

        def on_checkbox_active(checkbox, value):
            global currentStudent
            select = False
            for i in students:
                if i.get_name() == checkbox.text:
                    currentStudent = i
            if value:
                select = True
            currentStudent.select(select)

        def on_click(instance):
            global currentStudent
            global currentActivity
            for i in students:
                if i.isSelected():
                    currentStudent = i
                    currentStudent.set_points(i.get_points() +
                                              currentActivity.get_points())
                    currentStudent.log_event(currentActivity.get_activity())
            refreshCallBack(currentActivity.get_activity())

        def callback2(instance):
            global currentActivity
            global currentStudent
            global lastScreen
            sm.current = 'StudentInfo'
            sm.studentInformation.clear_widgets()
            for i in students:
                if i.get_name() == instance.text:
                    currentStudent = i
                    break
            nameLabel = Label(text="Name: " + currentStudent.get_name())
            idLabel = Label(text="Student ID: " + str(currentStudent.get_id()))
            gradeLabel = Label(text="Grade: " +
                               str(currentStudent.get_grade()))
            pointsLabel = Label(text="Points: " +
                                str(currentStudent.get_points()))
            activitiesLabel = ScrollableLabel(
                text="    Activities:\n" + str(currentStudent.get_history()))
            button = Button(text="Back")
            button.bind(on_press=backStudentButtonCallBack)
            sm.studentInformation.add_widget(button)
            sm.studentInformation.add_widget(nameLabel)
            sm.studentInformation.add_widget(idLabel)
            sm.studentInformation.add_widget(gradeLabel)
            sm.studentInformation.add_widget(pointsLabel)
            sm.studentInformation.add_widget(activitiesLabel)

        newActivityButton = Button()
        newActivityButton.text = "Custom Activity"
        newActivityButton.bind(on_press=newActivityCallBack)
        sm.createActivity.add_widget(newActivityButton)
        for i in activities:
            text = i.get_activity()
            text1 = str(i.get_points())
            button = Button()
            button.text = text
            label = Label()
            label.text = "Points: " + text1
            label.color = 0, 0, 0, 1
            label.size_hint = 0.3, 1
            button.background_normal = ''
            button.background_color = .15, .7, .2, .7
            button.size_hint = 0.7, 1
            button.bind(on_press=callback)
            sm.box.add_widget(button)
            sm.box.add_widget(label)

        return sm
示例#45
0
import tkinter as tk

from Activity import *

from treinoui import ui

root = tk.Tk()
root.geometry('%dx%d'%(root.winfo_screenwidth(), root.winfo_screenheight()))
Activity(root, 'Inicializar Valores', ui, width=root.winfo_screenwidth(), height = root.winfo_screenheight()).start()
root.mainloop()
示例#46
0
def extractPerson(main=False,
                  onto=None,
                  functType=None,
                  name=None,
                  time="present"):

    if onto is None:
        raise Exception("Parameters found None")

    if main and functType is None:
        usernametext = "Alright! Tell me about yourself. What is your name?: "
        healthparamsaux = healthparams
    elif functType == "liveswith":
        usernametext = texts[main]["liveswithintroduce"].format(name=name)
        healthparamsaux = healthliveswith
        main = False
    elif functType == "companions":
        usernametext = texts[main]["companionsintroduce"]
        healthparamsaux = healthcompanions
        main = False
    else:
        pass  #debug

    username = input(usernametext)
    person = AGPerson(username, onto)
    if username in ag.globalAgent().people:
        name = renameUser(username, ag.globalAgent().people.keys())
        if name is None:
            return ag.globalAgent().people[name]
        person.name = name
    ag.globalAgent().addPerson(person)

    if main:
        userparamstext = "What else could be of interest about you? This data will help me give you a better analysis."
    else:
        userparamstext = "What else could be of interest about " + username + "? This data will help me give you a better analysis."

    while (True):
        clear()
        print(userparamstext)

        uindex = userMenu(
            list(x[0] for x in healthparamsaux) + ["That's enough data."])
        if uindex == len(healthparamsaux):
            break
        else:
            clear()
            healthparamsaux[uindex][1](main, person)
            if uindex == len(healthparamsaux) - 1:
                healthparamsaux = healthparamsaux[:uindex]
            elif uindex == 0:
                healthparamsaux = healthparamsaux[uindex + 1:]
            else:
                healthparamsaux = healthparamsaux[:uindex] + healthparamsaux[
                    uindex + 1:]

    if functType != "liveswith":
        liveswith = extractLivingwith(main=main, person=person, onto=onto)
        person.toOnto()
        if liveswith is not None:
            person.linkLivesWith(liveswith)
        gears = extractProtectionGear(main=main,
                                      onto=onto,
                                      personname=person.name,
                                      placename=name)
        if gears is not None:
            person.gears = gears
        person.updateGears()

    clear()
    while (True):
        resp = input(texts[main]["pastactivityyesno"].format(name=person.name))
        if resp.lower() == "no":
            break
        elif resp.lower() == "yes":
            clear()
            pastActivities = AC.extractActivity(
                main=main,
                entranceText=texts[main]["pastactivitytell"].format(
                    name=person.name),
                onto=onto,
                locations=[
                    "Bookshop", "Boutique", "Cafe", "Library", "Restaurant",
                    "Shop", "Stadium"
                ],
                time="past",
                agent=person)
            clear()
        else:
            clear()
            print("Please introduce yes or no.")

    person.toOnto()
    return person
示例#47
0
文件: actor.py 项目: ojaohe-3/RTB
 def setDestination(self, point):
     self.activity = Activity(point,"moving", "unschedual", time.time+random.randrange(10,100))
 def POST(self):
     params=json.loads(web.data())
     session = Activity.createSession('try')
     return Activity.getAvailable(session,params["startdate"],params["numofweeks"],params["teams"],params["teamname"])