Example #1
0
    def __init__(self, screen, items):
        Activity.__init__(self, screen)
        self.screen = screen
        
        # Position of the categories menu
        self.cat_pos = (675, 60)
        
        # Position of the activities menu
        self.act_pos = (270, 105)

        # items holds the categories
        self.menu = Menu(self.cat_pos)

        # submenus holds the different activities separated by category
        self.submenus = {}

        # Wich category is active
        self.active = None

        if items:
            for item in items:
                if not self.submenus.has_key(item.category):
                    submenu = MenuActivity(self.act_pos)
                    self.submenus[item.category] = submenu
                self.submenus[item.category].add(item)

            for item in self.submenus.keys():
                self.menu.add(ItemCategory(item, self.cat_pos))

        introduction = (u"Este contenido educativo", 
                        u"está diseñado con actividades ", 
                        u"lúdicas para la adquisición de ",
                        u"conceptos y hábitos que contribuyen ",
                        u"a formar niñas y niños saludables.",
                        u" ",
                        u"Esperamos que pases momentos ",
                        u"agradables y divertidos ",
                        u"mientras aprendes.")

        font_default = pygame.font.SysFont(constants.font_default[0],
                                           constants.font_default[1])

        isize = font_default.size(introduction[0])[1]

        introduction_pos = (constants.screen_mode[0] / 2.0 + 3, 100)
        
        introduction_ = []
        for i in introduction:
            line = font_default.render(i, True, (102, 102, 102))
            introduction_.append(line)
        self.text = ((introduction_, introduction_pos),)

        self.finger = Finger()
        self.sprites = pygame.sprite.Group()
        self.icons = pygame.sprite.Group()
        self.icons.add([Icons('stop')])
        self.sprites.add((self.finger, self.icons))
        
        self.pos = None
        return
    def test_when_update_time(self) -> None:
        not_working_activity = Activity('wm_class1',
                                        'window_name1',
                                        datetime(2020, 7, 21, 21, 30, 0, 3),
                                        is_work_time=False).set_end_time(
                                            datetime(2020, 7, 21, 22, 30, 0,
                                                     3))
        working_activity = Activity('wm_class1',
                                    'window_name1',
                                    datetime(2020, 7, 21, 22, 30, 0, 4),
                                    is_work_time=True).set_end_time(
                                        datetime(2020, 7, 21, 22, 35, 0, 5))

        sub_tests_data = {
            'Update off time stat when it was empty':
            (self.activity, not_working_activity, timedelta(0, 3600, 1),
             timedelta(0, 3600)),
            'Update work time stat when it was empty':
            (not_working_activity, working_activity, timedelta(0, 300, 1),
             timedelta(0, 3600)),
            'Update work time stat when it was not empty':
            (self.activity, working_activity, timedelta(0, 3900,
                                                        2), timedelta(0)),
        }

        for sub_test, (activity, same_activity_with_diff_time, work_time,
                       off_time) in sub_tests_data.items():
            with self.subTest(name=sub_test):
                activity_stat = ActivityStat.from_activity(activity)
                activity_stat.update(same_activity_with_diff_time)

                self.assertEqual(activity_stat.work_time, work_time)
                self.assertEqual(activity_stat.off_time, off_time)
Example #3
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.CloseButton = pygame.sprite.RenderUpdates(([Icons('stop')]))
     self.finger = Finger()
     self.Cursor = pygame.sprite.RenderUpdates((self.finger))
     self.pos = None
     self.messages_filename = constants.poetry
Example #4
0
    def test_entity_activity_init_params(self):
        uuid = "ActivityUUID-321"
        start_datetime = datetime.datetime(year=2018,
                                           month=1,
                                           day=2,
                                           hour=1,
                                           minute=0,
                                           second=0)
        end_datetime = datetime.datetime(year=2018,
                                         month=1,
                                         day=2,
                                         hour=1,
                                         minute=0,
                                         second=2)
        obj = Activity(uuid=uuid,
                       start_datetime=start_datetime,
                       end_datetime=end_datetime)

        e_flag = False
        try:
            str_rep = obj.__str__()
            self.assertFalse(
                obj.in_daytime(),
                msg='activity not properly assigned to day or night time')
            self.assertEqual(
                obj.seconds,
                2,
                msg='seconds between start and end datetime calculated wrongly'
            )
        except Exception as e:
            print(e)
            e_flag = True
        self.assertFalse(e_flag, 'exception thrown')
Example #5
0
 def updateTimer(self, event):
     self.processTimeActive += self.timerDelay / 1000
     windowName = win32gui.GetWindowText(win32gui.GetForegroundWindow())
     if self.processName == "ERROR-FINDING-PROCESS":
         try:
             self.pid = win32process.GetWindowThreadProcessId(
                 win32gui.GetForegroundWindow())[-1]
             self.processName = psutil.Process(self.pid).name()
         except:
             self.processName = "ERROR-FINDING-PROCESS"
     if self.lastWindowName != windowName:
         #OutputActivity(startTime, time.time(), lastWindowName, processName)
         activity = Activity(self.startTime, time.time(),
                             self.lastWindowName, self.processName,
                             self.filePath)
         activity.SaveToFile()
         self.startTime = time.time()
         try:
             self.pid = win32process.GetWindowThreadProcessId(
                 win32gui.GetForegroundWindow())[-1]
             self.processName = psutil.Process(self.pid).name()
         except:
             self.processName = "ERROR-FINDING-PROCESS"
         self.lastWindowName = windowName
         del activity
         self.processTimeActive = 0
     self.updateGUI()
Example #6
0
    def __init__(self, screen, pos):
        Activity.__init__(self, screen)

 
        self.couple = set()
        self.couples = []

        self.sprites0 = pygame.sprite.OrderedUpdates()
        self.sprites1 = pygame.sprite.OrderedUpdates()
        self.pointer_ = pygame.sprite.OrderedUpdates()
        self.items = pygame.sprite.Group()
        self.icons = pygame.sprite.Group()

        self.icons.add([Icons('stop')])

        self.sprites0.add(self.icons)

        for i in pos.keys():
            item = Item(i, pos[i])
            self.sprites0.add(item)
            self.items.add(item)

        self.pointer = Pointer()
        self.pointer_.add(self.pointer)

        self.arrows = []
        self.arrow = None
Example #7
0
    def add_follower(cls, leader, follower):
        # TODO: expand to handle more than 5000 followers, using extra entities
        follower_id = follower.key().id()  # TickUser.get_by_user_id(follower.user_id(),keys_only=True).id()
        leader_id = leader.key().id()
        check = cls.all(keys_only=True).ancestor(leader).filter("followers_ids =", follower_id).get()
        if not check:
            entity = cls.all().ancestor(leader).filter("leader_id =", leader_id).get()
            if entity:
                entity.follower_ids.append(follower_id)
                index = entity.get_follow_index()
                index.add_followers(follower.all_user_ids)
                index.put()
                entity.put()
            else:
                new_entity = cls(parent=leader, leader_id=leader_id, follower_ids=[follower_id])
                new_entity.put()
                new_index = FollowIndex(parent=new_entity)
                new_index.add_leaders(leader.all_user_ids)
                new_index.add_followers(follower.all_user_ids)
                new_index.put()
            from activity import Activity

            Activity.create(
                "<actor>|began following|<target>", actor=follower, target=leader, extra_recipients=[leader]
            )
            return True
        else:
            return False
Example #8
0
def _load_peaks(source: List[int], attributes: Dict[int, str],
                activity: Activity):
    """
    Load a set of peak data from the nominated source data.
    
    The source data we're given is either the time-series collection of power figures,
    or the time-series collection of HR figures.

    The attributes we're provided tells us what time periods we need to average that
    over. For example: given power data, and an attribute of (5, "peak_5sec_power")
    means that we need to take a moving 5 second average of the source data, find the
    maximum of those 5 second averages, and store that in the "peak_5sec_power" property
    of the Peaks object.

    Args:
        source:     The source data to load from.
        attributes: The attributes we load.
        activity:   The activity object we're populating.
    """

    for window, attr_name in attributes.items():
        if (moving_average := get_moving_average(source=source,
                                                 window=window)):
            activity.__dict__[attr_name] = int(max(moving_average))
        else:
            activity.__dict__[attr_name] = None
def getActivityInfo():
    activity_id = int(request.form.get("activity_id"))
    manager = DataManager(DataType.activity)
    activity_info = manager.getInfo(activity_id)
    if len(activity_info) == 0:
        return json.dumps({'status': 'Not Found'})

    activity = Activity(at_id=activity_id,
                        at_name=activity_info[0][1],
                        at_description=activity_info[0][2],
                        at_club_id=activity_info[0][3],
                        at_place=activity_info[0][4],
                        at_start_time=activity_info[0][5],
                        at_end_time=activity_info[0][6],
                        at_lottery_time=activity_info[0][7],
                        at_lottery_method=activity_info[0][8],
                        at_max_number=activity_info[0][9],
                        at_fee=activity_info[0][10],
                        at_sign_up_ddl=activity_info[0][11],
                        at_sponsor=activity_info[0][12],
                        at_undertaker=activity_info[0][13])

    res = activity.Jsonfy()

    return res
Example #10
0
 def add_follower(cls, leader, follower):
     # TODO: expand to handle more than 5000 followers, using extra entities
     follower_id = follower.key().id(
     )  #TickUser.get_by_user_id(follower.user_id(),keys_only=True).id()
     leader_id = leader.key().id()
     check = cls.all(keys_only=True).ancestor(leader).filter(
         'followers_ids =', follower_id).get()
     if not check:
         entity = cls.all().ancestor(leader).filter('leader_id =',
                                                    leader_id).get()
         if entity:
             entity.follower_ids.append(follower_id)
             index = entity.get_follow_index()
             index.add_followers(follower.all_user_ids)
             index.put()
             entity.put()
         else:
             new_entity = cls(parent=leader,
                              leader_id=leader_id,
                              follower_ids=[follower_id])
             new_entity.put()
             new_index = FollowIndex(parent=new_entity)
             new_index.add_leaders(leader.all_user_ids)
             new_index.add_followers(follower.all_user_ids)
             new_index.put()
         from activity import Activity
         Activity.create('<actor>|began following|<target>',
                         actor=follower,
                         target=leader,
                         extra_recipients=[leader])
         return True
     else:
         return False
Example #11
0
    def validation_data(self, contrast=1., small_batch_size = 1000,large_batch_size = 50000):

        parameters = self.network.parameters        
        parameters.batch_size = small_batch_size
        orig_time_data = parameters.time_data
        orig_keep_spikes = parameters.keep_spikes
        #parameters.time_data = True
        #parameters.static_data_control = True
        parameters.keep_spikes = True
        if orig_keep_spikes == False:
            self.network.spike_train = ()
            nout = parameters.M
            for ii in np.arange(self.network.n_layers):
                out_dim = nout[ii]
                self.network.spike_train += (nw.make_shared((parameters.batch_size,
                                                  out_dim,
                                                  parameters.num_iterations)),)
                                                  
        small_bs = self.network.parameters.batch_size        
        batch_size = large_batch_size
        
        if parameters.time_data and not parameters.static_data_control:
            data = Time_Data(os.path.join(os.environ['DATA_PATH'],'vanhateren/whitened_images.h5'),
            1000,
            parameters.batch_size,
            parameters.N,
            parameters.num_frames,
            start=35)     
        else:
            data = Static_Data(os.path.join(os.environ['DATA_PATH'],'vanhateren/whitened_images.h5'),
            1000,
            parameters.batch_size,
            parameters.N,
            start=35)    
            
        self.network.to_gpu()
        activity = Activity(self.network)
        self.big_X = np.zeros((batch_size, parameters.N), dtype='float32')
        self.big_Y = ()
        
        for layer in range(self.network.n_layers):
            self.big_Y += (np.zeros((batch_size, parameters.M[layer]), dtype='float32'),)

        for ii in range(batch_size/small_bs):
            data.make_X(self.network) 
            if contrast != 1.:
                self.network.X.set_value(self.network.X.get_value() *
                                         np.array(contrast, dtype='float32'))
            activity.get_acts()
            
            self.big_X[ii*small_bs:(ii+1)*small_bs,:] = self.network.X.get_value()
            for layer in range(self.network.n_layers):
                self.big_Y[layer][ii*small_bs:(ii+1)*small_bs,:] = self.network.Y[layer].get_value()
        
        self.network.to_cpu()
        self.network.Y = self.big_Y
        self.network.X = self.big_X
        self.network.parameters.time_data = orig_time_data
        self.network.parameters.keep_spikes = orig_keep_spikes
 def choose_item(self):
     contents.activityChosen = self.activityList.get(
         self.activityList.curselection())
     user_interface_handler.load_sections_time(self)
     self.activityAnnounce.config(text=contents.activityNom +
                                  contents.activityChosen)
     Activity.cancel_edit(self, self.noteTxt)
     Activity.update_description(self, self.noteTxt)
def readFile (filename, partition) :
    """
    Read files filename and partition and return the correponding work sheet
    """
    Activity.readPartition (partition)
    w = WorkSheet()
    w.read(filename)
    return w
Example #14
0
    def __init__(self, db, models):
        """

        :type db: flask_sqlalchemy.SQLAlchemy
        :type models: models
        """
        self.db = db
        self.models = models
        self.activity = Activity(db=db, models=models, logger=logging)
Example #15
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.CloseButton = pygame.sprite.RenderUpdates(([Icons('stop')]))
     self.finger = Finger()
     self.cursor = pygame.sprite.RenderUpdates((self.finger))
     self.change = pygame.sprite.Group([Navigation()]) #load next and prev buttons
     self.pos = None
     self.sprites = pygame.sprite.OrderedUpdates()
     self.sprites.add([self.CloseButton, self.change, self.cursor])
     self.text()
    def set_if_matched(self, activity: Activity) -> None:
        """Set ApplicationInfo to Activity if matched"""

        application_info = self.__try_find_app_info_in(
            self.distracting_app_infos,
            activity) or self.__try_find_app_info_in(self.detailed_app_infos,
                                                     activity)

        if application_info is None:
            return

        activity.set_application_info(application_info)
Example #17
0
    def __init__(self, screen):
        Activity.__init__(self, screen)
        self.wrong_pos = [
                Rect(490, 272, 21, 29),
                Rect(439, 315, 47, 21),
                Rect(435, 355, 34, 29),
                Rect(458, 376, 45, 47),
                Rect(517, 372, 63, 36),
                Rect(614, 370, 37, 41),
                Rect(525, 421, 33, 30),
                Rect(567, 454, 25, 20),
                Rect(510, 473, 34, 33),
                Rect(467, 505, 36, 23),
                Rect(541, 516, 33, 28),
                Rect(639, 432, 53, 45),
                Rect(738, 329, 41, 23),
                Rect(722, 206, 29, 21),
                Rect(713, 176, 33, 20),
                Rect(653, 196, 30, 26),
                Rect(519, 271, 61, 52),
                Rect(583, 290, 24, 22),
                Rect(591, 318, 29, 38),
                Rect(401, 536, 105, 61),
                Rect(720, 248, 74, 33),
                ]

        self.found = 0

        self.screen = screen
        path = os.path.join(constants.data_folder, "backgrounds", 'illustration_020_021.png')
        self.background, rect = common.load_image(path)

        self.title = ("¡Orden en mi habitación!",)
        self.instructions = ("Observa estas dos habitaciones. Una está ordenada",
                "y la otra desordenada: descubre las 21 diferencias y",
                "márcalas con una X en la habitación desordenada")

        self.icons = pygame.sprite.Group()
        self.icons.add([Icons('stop')])

        self.pointer_ = Xs()
        self.pointer = sprite.RenderUpdates([self.pointer_, self.icons])
        self.xs = sprite.RenderUpdates()

        self.xs.draw(self.screen)
        self.pointer.draw(self.screen)

        self.check = sprite.RenderUpdates()
        
        self.room = Rect(403, 129, 393, 467)
        pygame.display.update()
Example #18
0
def calculate_transient_values(activity: Activity):
    """
    Calculate the transient values for a specific activity.

    Lots of this logic comes from https://medium.com/critical-powers/formulas-from-training-and-racing-with-a-power-meter-2a295c661b46.

    Args:
        activity: The activity to calculate the transient values for.
    """
    # Simple stuff
    activity.variability_index = round(
        ((activity.normalised_power - activity.avg_power) /
         activity.normalised_power) * 100, 0)
    activity.ftp = get_ftp(activity.start_time)
    activity.intensity_factor = activity.normalised_power / activity.ftp if activity.ftp else 0

    activity.duration_in_seconds = (activity.end_time -
                                    activity.start_time).seconds
    activity.tss = int(
        (activity.duration_in_seconds * activity.normalised_power *
         activity.intensity_factor) /
        (activity.ftp * 36)) if activity.ftp else 0

    distance_in_meters = activity.distance
    speed_in_ms = distance_in_meters / activity.duration_in_seconds
    activity.speed_in_kmhr = speed_in_ms * 3600 / 1000

    # Now calculate aerobic decoupling
    # See https://www.trainingpeaks.com/blog/aerobic-endurance-and-decoupling.
    if distance_in_meters >= 10000:
        activity.aerobic_decoupling = calculate_aerobic_decoupling(activity)
        activity.aerobic_efficiency = activity.normalised_power / activity.avg_hr
Example #19
0
    def build(self) -> Activity:
        if self.start_time is None:
            raise RuntimeError('start_time should be set!')

        if self.end_time is None:
            raise RuntimeError('end_time should be set!')

        activity = Activity(self.origin_activity.wm_class,
                            self.origin_activity.window_name, self.start_time,
                            self.origin_activity.is_work_time)

        activity.set_end_time(self.end_time)

        return activity
    def test_when_end_time_is_greater_than_start_time(self):
        start_time = datetime(2020, 7, 12, 20, 30, 0)
        end_time = datetime(2020, 7, 12, 21, 30, 0)
        expected_activity_time = timedelta(hours=1)

        self.assertGreater(end_time, start_time)

        activity = Activity('wm_class', 'window_name', start_time, is_work_time=True)

        activity.set_end_time(end_time)

        self.assertTrue(activity.has_finished())
        self.assertEqual(end_time, activity.end_time)
        self.assertEqual(expected_activity_time, activity.activity_time)
Example #21
0
class Manager:
    def __init__(self, db, models):
        """

        :type db: flask_sqlalchemy.SQLAlchemy
        :type models: models
        """
        self.db = db
        self.models = models
        self.activity = Activity(db=db, models=models, logger=logging)

    def start(self):
        thread = threading.Thread(target=self.run)
        thread.start()

    def run(self):
        print("### run")

        try:
            self.clear_running()
        except Exception as exc:
            print("Exception during clear_running():")
            print(exc)
        while True:
            self.loop()
            print("run sleep(600)")
            sleep(600)

    def loop(self):
        now = time_in_week(datetime.datetime.now())
        tts = self.models.TimeTable.query.filter(
            self.models.TimeTable.start <= now,
            self.models.TimeTable.end > now,
            # self.models.TimeTable.end < self.models.TimeTable.start,
        ).all()
        ids = list(map(lambda tt: tt.account_id, tts))
        print("ids: %s" % ids)
        for id in ids:
            try:
                self.activity.start_bot(id)
            except Exception as exc:
                print("Exception during loop():")
                print(exc)
                self.db.session.rollback()
                print("Session.rollback() Done")

    def clear_running(self):
        delete = self.db.session.query(self.models.Running).delete(synchronize_session='fetch')
        self.db.session.commit()
        print("### clear Entries: %r" % str(delete))
Example #22
0
    def setUpClass(cls):
        cls.activities = ActivitiesStorage()
        cls.a = Activity('title', datetime.now() - timedelta(hours=1, minutes=15), datetime.now())
        cls.a2 = Activity('title2', datetime.now() - timedelta(minutes=4, seconds=23), datetime.now())

        cls.activities2 = ActivitiesStorage()
        cls.activities2.storage = [
            {
                'active_tab': 'title3',
                'active_sessions': [{'hours': 2, 'minutes': 20, 'seconds': 0}],
                'last_active_session': {'hours': 2, 'minutes': 20, 'seconds': 0},
                'total_time': timedelta(seconds=8400, microseconds=11)
            }
        ]
        cls.a3 = Activity('title3', datetime.now() - timedelta(minutes=12, seconds=45), datetime.now())
    def test_when_tree_day_activity(self, mock_is_dir_res, mock_open_res) -> None:
        files_provider = FilesProvider(Path('/root_dir/'))
        self.assertEqual(4, mock_is_dir_res.call_count)

        writer = ActivityWriter(files_provider)

        handle_new_day_event = Mock()

        writer.event.on(ActivityWriter.NEW_DAY_EVENT, handle_new_day_event)

        three_days_activity = Activity('wm_class2',
                                       'window_name2',
                                       datetime(2020, 7, 31, 12, 5),
                                       is_work_time=True).set_end_time(datetime(2020, 8, 2, 11, 30))

        writer.write(three_days_activity)

        mock_open_res.assert_has_calls([
            call('/root_dir/dest/2020-07-31_speaking_eye_raw_data.tsv', 'a'),
            call().write('2020-07-31 12:05:00\t2020-07-31 23:59:59.999999\t'
                         '11:54:59.999999\twm_class2\twindow_name2\tTrue\n'),
            call().flush(),
            call().close(),
            call('/root_dir/dest/2020-08-01_speaking_eye_raw_data.tsv', 'a'),
            call().write('2020-08-01 00:00:00\t2020-08-01 23:59:59.999999\t'
                         '23:59:59.999999\twm_class2\twindow_name2\tTrue\n'),
            call().flush(),
            call().close(),
            call('/root_dir/dest/2020-08-02_speaking_eye_raw_data.tsv', 'a'),
            call().write('2020-08-02 00:00:00\t2020-08-02 11:30:00\t'
                         '11:30:00\twm_class2\twindow_name2\tTrue\n'),
            call().flush()
        ])

        self.assertEqual(2, handle_new_day_event.call_count)
Example #24
0
 def get_activity(self, key):
     with dbapi2.connect(self.app.config['dsn']) as connection:
         cursor = connection.cursor()
         query = "SELECT TITLE, ACTIVITY_TYPE, FOUNDERID, PARTICIPANT_COUNT,  TIME, PLACE, ACTIVITY_INFO FROM ACTIVITY WHERE (ID = %s)"
         cursor.execute(query, (key,))
         title, activity_type, founder, participant_count, time, place, activity_info = cursor.fetchone()
     return Activity(title, activity_type, founder, participant_count, time, place, activity_info)
    def test_when_activity_has_not_finished(self, mock_is_dir_res, mock_open_res) -> None:
        files_provider = FilesProvider(Path('/root_dir/'))
        self.assertEqual(4, mock_is_dir_res.call_count)

        writer = ActivityWriter(files_provider)

        not_finished_activity = Activity('wm_class1',
                                         'window_name1',
                                         datetime(2020, 7, 21, 20, 30, 0),
                                         is_work_time=True)

        handle_new_day_event = Mock()

        writer.event.on(ActivityWriter.NEW_DAY_EVENT, handle_new_day_event)

        with self.assertRaisesRegex(
                ValueError,
                expected_regex='Activity \\[2020-07-21 20:30:00\tNone\tNone\twm_class1\twindow_name1\tTrue\n\\] '
                               'should be finished!'):
            writer.write(not_finished_activity)

        mock_open_res.assert_not_called()

        mock_file = mock_open_res.return_value

        mock_file.write.assert_not_called()
        mock_file.flush.assert_not_called()
        mock_file.close.assert_not_called()
        handle_new_day_event.assert_not_called()
    def test_when_end_time_is_not_greater_than_start_time(self):
        start_time = datetime(2020, 7, 12, 20, 30, 0)
        end_time = datetime(2020, 7, 12, 19, 30, 0)

        self.assertLess(end_time, start_time)

        activity = Activity('wm_class', 'window_name', start_time, is_work_time=True)

        with self.assertRaisesRegex(ValueError,
                                    expected_regex=r'end_time \[2020-07-12 19:30:00\] should be greater '
                                                   r'than start_time \[2020-07-12 20:30:00\]!'):
            activity.set_end_time(end_time)

        self.assertFalse(activity.has_finished())
        self.assertIsNone(activity.end_time)
        self.assertIsNone(activity.activity_time)
Example #27
0
    def set_work_time_state(self, value: bool) -> None:
        if value == self.is_work_time:
            self.logger.debug(
                'Trying to change is_work_time to the same value')
            return

        self.is_work_time = value

        current_activity = Value.get_or_raise(self.current_activity,
                                              'current_activity')
        now = datetime.now()
        new_activity = Activity(current_activity.wm_class,
                                current_activity.window_name, now,
                                self.is_work_time)

        self.__on_activity_changed(current_activity, new_activity)

        self.is_work_time_update_time = now

        self.logger.debug(f'Set Work Time to [{self.is_work_time}]')

        icon = self.active_icon if self.is_work_time else self.disabled_icon
        self.tray_icon.set_icon_if_exist(icon)

        if self.is_work_time:
            self.last_lock_screen_time = now
            self.last_break_notification = None
            self.last_overtime_notification = None
Example #28
0
def add_activity_to_bucketlist():
    ''' Add activity to named bucketlist '''
    user = None
    username = session['user']['username']

    if username in users.keys():
        user = users[username]

    current_bucketlist = request.args.get('name')

    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']

        activity = Activity(title, description)

        if current_bucketlist in user.bucketlists.keys():
            user.bucketlists[current_bucketlist].add_activity(activity)

        activities = user.bucketlists[current_bucketlist].activities

        return render_template('bucketlist.html',
                               name=current_bucketlist,
                               activities=activities)
    else:
        return render_template(
            'bucketlist.html',
            name=current_bucketlist,
            activities=user.bucketlists[current_bucketlist].activities)
    def _add_activity(self, activity_name, time_entry):
        """
        Add the activity with its time entry to the activity list.

        If activity was already present in the list, only update the duration
        and add the time entry. If activity was not present, add it.

        Parameters
        ----------
        activity_name: string
            The name of the activity to add
        time_entry: TimeEntry
            The time entry of the activity to add

        Returns
        -------
        bool: True
        """
        for activity in self.activities:
            if activity_name == activity.name:
                activity.duration += time_entry.delta
                activity.entries.append(time_entry)
                return True

        activity = Activity(name=activity_name,
                            duration=time_entry.delta,
                            entries=[time_entry])

        self.activities.append(activity)
        return True
Example #30
0
    def store(self, *, activity: Activity):
        """
        Persist an activity in the SQLite database.
        
        Args:
            activity: The activity to persist.
        """

        # Setup parameters for insert.
        params = {}

        for key, value in activity.__dict__.items():
            if key in ["raw_power", "raw_hr"]:
                params[key] = ",".join(str(x) for x in value)
            else:
                params[key] = value

        # Insert the record.
        self.conn.execute(INSERT_SQL, params)
        self.conn.commit()

        # Fetch the row ID
        cursor = self.conn.cursor()
        try:
            cursor.execute('select last_insert_rowid() as "last_row_id"')
            records = cursor.fetchall()
            assert len(records) == 1
            activity.rowid = int(records[0][0])
        finally:
            cursor.close()
Example #31
0
    def activity_stream_item(self, activity_type, revision, user_id):
        import ckan.model
        import ckan.lib.dictization
        import ckan.logic
        assert activity_type in ("new", "changed"), (str(activity_type))

        # Handle 'deleted' objects.
        # When the user marks a package as deleted this comes through here as
        # a 'changed' package activity. We detect this and change it to a
        # 'deleted' activity.
        if activity_type == 'changed' and self.state == u'deleted':
            if ckan.model.Session.query(ckan.model.Activity).filter_by(
                    object_id=self.id, activity_type='deleted').all():
                # A 'deleted' activity for this object has already been emitted
                # FIXME: What if the object was deleted and then activated
                # again?
                return None
            else:
                # Emit a 'deleted' activity for this object.
                activity_type = 'deleted'

        try:
            d = {
                'package':
                ckan.lib.dictization.table_dictize(
                    self, context={'model': ckan.model})
            }
            return Activity(user_id, self.id, revision.id,
                            "%s package" % activity_type, d)
        except ckan.logic.NotFound:
            # This happens if this package is being purged and therefore has no
            # current revision.
            # TODO: Purge all related activity stream items when a model object
            # is purged.
            return None
Example #32
0
    def Transform(self, client, activity, callback):
        from activity import Activity
        from asset_id import AssetIdUniquifier
        from device import Device

        def _OnUpdate(new_activity):
            """Delete the old activity."""
            if Version._mutate_items:
                activity.Delete(client, partial(callback, new_activity))
            else:
                callback(new_activity)

        timestamp, device_id, uniquifier = Activity.DeconstructActivityId(
            activity.activity_id)

        if device_id == Device.SYSTEM:
            if activity.activity_id in DisambiguateActivityIds2._unique_activity_ids:
                # Already saw this activity id, so append viewpoint id to it.
                assert uniquifier.server_id is None, (activity, uniquifier)
                new_uniquifier = AssetIdUniquifier(uniquifier.client_id,
                                                   activity.viewpoint_id)
                new_activity_id = Activity.ConstructActivityId(
                    timestamp, device_id, new_uniquifier)

                new_activity_dict = activity._asdict()
                new_activity_dict['activity_id'] = new_activity_id

                new_activity = Activity.CreateFromKeywords(**new_activity_dict)

                logging.info('%s\n%s (%s/%s/%s) => %s (%s/%s/%s/%s)' %
                             (activity, activity.activity_id, timestamp,
                              device_id, uniquifier.client_id, new_activity_id,
                              timestamp, device_id, new_uniquifier.client_id,
                              new_uniquifier.server_id))

                if Version._mutate_items:
                    new_activity.Update(client,
                                        partial(_OnUpdate, new_activity))
                else:
                    _OnUpdate(new_activity)
            else:
                DisambiguateActivityIds2._unique_activity_ids.add(
                    activity.activity_id)
                callback(activity)
        else:
            assert activity.activity_id not in DisambiguateActivityIds2._unique_activity_ids, activity
            callback(activity)
Example #33
0
 def get_activities(self):
     with dbapi2.connect(self.app.config['dsn']) as connection:
         cursor = connection.cursor()
         query = "SELECT * FROM ACTIVITY ORDER BY ID"
         cursor.execute(query)
         activities = [(key, Activity(title, activity_type, founder, participant_count, time, place, activity_info))
                   for key, title, activity_type, founder, participant_count, time, place, activity_info in cursor]
     return activities
def parse(path):
    with open(os.path.join(os.getcwd(), path), "r") as data:
        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))
        jobs_list = []
        # Current job's id
        id_job = 1

        for key, line in enumerate(data):
            if key >= number_total_jobs:
                break
            # Split data with multiple spaces as separator
            parsed_line = re.findall('\S+', line)
            # Current job
            job = Job(id_job)
            # Current activity's id
            id_activity = 1
            # Current item of the parsed line
            i = 1

            while i < len(parsed_line):
                # Total number of operations for the activity
                number_operations = int(parsed_line[i])
                # Current activity
                activity = Activity(job, id_activity)
                for id_operation in range(1, number_operations + 1):
                    activity.add_operation(
                        Operation(id_operation,
                                  int(parsed_line[i + 2 * id_operation - 1]),
                                  int(parsed_line[i + 2 * id_operation])))

                job.add_activity(activity)
                i += 1 + 2 * number_operations
                id_activity += 1

            jobs_list.append(job)
            id_job += 1

    # Machines
    machines_list = []
    for id_machine in range(1, number_total_machines + 1):
        machines_list.append(Machine(id_machine, number_max_operations))

    return jobs_list, machines_list, number_max_operations
Example #35
0
    def test_entity_activity_init_from_sensor_logs(self):
        uuid1 = "uuid-01"
        node_id1 = 1
        event1 = 0
        ts1 = datetime.datetime(year=2018,
                                month=1,
                                day=2,
                                hour=1,
                                minute=0,
                                second=0)
        obj1 = Sensor_Log(uuid=uuid1,
                          node_id=node_id1,
                          event=event1,
                          recieved_timestamp=ts1)

        uuid2 = "uuid-02"
        node_id2 = 2
        event2 = 225
        ts2 = datetime.datetime(year=2018,
                                month=1,
                                day=2,
                                hour=1,
                                minute=0,
                                second=2)
        obj2 = Sensor_Log(uuid=uuid2,
                          node_id=node_id2,
                          event=event2,
                          recieved_timestamp=ts2)

        obja = Activity(start_log=obj1, end_log=obj2)

        e_flag = False
        try:
            str_rep = obja.__str__()
            self.assertFalse(
                obja.in_daytime(),
                msg='activity not properly assigned to day or night time')
            self.assertEqual(
                obja.seconds,
                2,
                msg='seconds between start and end datetime calculated wrongly'
            )
        except:
            e_flag = True
        self.assertFalse(e_flag, 'exception thrown')
Example #36
0
def like():
    try:
        id = flask.request.args['id']
        n = flask.request.args['n']
        act = Activity.load_from_db(id)
        act.like(int(n))
        return json.dumps({'status': 'ok'})
    except Exception as e:
        return json.dumps({'status': 'error', 'message': str(e)})
Example #37
0
 def search_activity(self, key):
     with dbapi2.connect(self.app.config['dsn']) as connection:
         cursor = connection.cursor()
         query = "SELECT * FROM ACTIVITY WHERE (TITLE ILIKE %s OR ACTIVITY_TYPE ILIKE %s OR PLACE ILIKE %s OR ACTIVITY_INFO ILIKE %s)"
         key = '%'+key+'%'
         cursor.execute(query, (key, key, key, key))
         activities = [(key, Activity( title, activity_type, founder, participant_count, time, place, activity_info))
                   for key,  title, activity_type, founder, participant_count, time, place, activity_info in cursor]
     return activities
Example #38
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.close_button = pygame.sprite.RenderUpdates(([Icons('stop')]))
     self.finger = Finger()
     self.cursor = pygame.sprite.RenderUpdates((self.finger))
     self.pos = None
     self.line_start = (0, 0)
     self.draw_color = (0, 0, 0)
     self.line_width = 3
     self.line_end = None
     self.text()
     self.transparent = pygame.Rect(297, 96, 400, 408)
     # Color palette
     self.palette = {}
     self.mk_palette(constants.rgb_colors)
     # Thickness
     self.thickness = {}
     self.mk_thickness()
Example #39
0
    def __init__(self, window, app, antfile):
        Gtk.ListBoxRow.__init__(self)
        Activity.__init__(self, app, antfile)

        self.window = window

        grid = Gtk.Grid(margin=6)
        grid.set_column_spacing(10)
        self.add(grid)

        self.image = Gtk.Image(icon_name='preferences-system-time-symbolic',
                               icon_size=self.ICON_SIZE)

        self.label = Gtk.Label()
        self.label.set_ellipsize(Pango.EllipsizeMode.END)
        self.label.set_valign(Gtk.Align.CENTER)
        self.label.set_halign(Gtk.Align.START)

        self.spinner = Gtk.Spinner()
        self.spinner.set_valign(Gtk.Align.CENTER)
        self.spinner.set_halign(Gtk.Align.END)
        self.spinner.set_hexpand(True)
        self.spinner.set_no_show_all(True)

        self.selector_button = Gtk.CheckButton()
        self.selector_button.set_valign(Gtk.Align.CENTER)
        self.selector_button.set_halign(Gtk.Align.END)
        self.selector_button.set_hexpand(True)
        self.selector_button.set_no_show_all(True)

        grid.attach(self.image, 0, 0, 1, 1)
        grid.attach(self.label, 1, 0, 1, 1)
        grid.attach(self.spinner, 2, 0, 1, 1)
        # don't show spinner yet
        grid.attach(self.selector_button, 3, 0, 1, 1)
        # don't show selector button yet

        if not self.downloaded:
            self.label.set_sensitive(False)
            self.image.set_from_icon_name('dialog-question-symbolic',
                                          self.ICON_SIZE)

        self.connect('status-changed', self.status_changed_cb)
        self.status_changed_cb(self, self.status)
Example #40
0
    def __init__(self, screen):
        Activity.__init__(self, screen)
        self.background = common.load_image(constants.illustration_019)[0]
        words = {
                'saludable': (114, 236),
                'risa': (41, 264),
                'alimentos': (143, 283),
                'agua': (41, 307),
                'descanso': (101, 346),
                'amor': (89, 375),
                'limpieza': (26, 407),
                'deporte': (149, 445),
                'sol': (59, 463),
                'aire': (109, 490),
                'aseo': (55, 514),
                'banarse': (193, 542),
                }

        self.title = ("¡Palabras largas, palabras cortas!",)
        self.instructions = ("Estas palabras están relacionadas con la salud.",
                        "  ",
                        "Arrastra hacia la bolsa roja",
                        "las palabras que tienen",
                        "menos de 5 letras y hacia la",
                        "bolsa azul las que tienen",
                        "más de 5 letras.")
        self.informative_text(self.title, self.instructions)
        self.hand = Hand()
        self.icons = pygame.sprite.Group()
        self.icons.add([Icons('stop')])
        self.words = pygame.sprite.Group()
        self.sprites = pygame.sprite.OrderedUpdates()
        for word, pos in words.items():
            word_ = Word(word, pos)
            self.sprites.add(word_)
            self.words.add(word_)
        self.sprites.add([self.icons, self.hand])
        self.sprites.draw(self.screen)
        self.selected = None
        self.bags = (Bag('cortas', (430, 150, 170, 150), (475, 175, 100, 120)), 
                     Bag('largas', (430, 375, 170, 160), (480, 395, 105, 130)))
                
        return
Example #41
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.count = 0
     self.id = ""
     # Change the mouse pointer by a hand
     self.button_down = 0
     self.selection = 0
     self.hand = Hand()
     self.sprites    = pygame.sprite.OrderedUpdates()
     self.pictures   = pygame.sprite.Group() # Picture that can be move
     self.transparent= pygame.sprite.Group() # Picture that cann't be move
     self.icons      = pygame.sprite.Group()
     self.icons.add([Icons('stop')])
     self.transparent.add([ \
       ImagePuzzle(302, 100, 1, "5"), \
       ImagePuzzle(500, 100, 2, "5"), \
       ImagePuzzle(302, 250, 3, "5"), \
       ImagePuzzle(500, 250, 4, "5")]
     )
Example #42
0
    def __init__(self, window, app, antfile):
        Gtk.ListBoxRow.__init__(self)
        Activity.__init__(self, app, antfile)

        self.window = window

        grid = Gtk.Grid(margin=6)
        grid.set_column_spacing(10)
        self.add(grid)

        self.image = Gtk.Image(icon_name='preferences-system-time-symbolic',
            icon_size=self.ICON_SIZE)

        self.label = Gtk.Label()
        self.label.set_ellipsize(Pango.EllipsizeMode.END)
        self.label.set_valign(Gtk.Align.CENTER)
        self.label.set_halign(Gtk.Align.START)

        self.spinner = Gtk.Spinner()
        self.spinner.set_valign(Gtk.Align.CENTER)
        self.spinner.set_halign(Gtk.Align.END)
        self.spinner.set_hexpand(True)
        self.spinner.set_no_show_all(True)

        self.selector_button = Gtk.CheckButton()
        self.selector_button.set_valign(Gtk.Align.CENTER)
        self.selector_button.set_halign(Gtk.Align.END)
        self.selector_button.set_hexpand(True)
        self.selector_button.set_no_show_all(True)

        grid.attach(self.image, 0, 0, 1, 1)
        grid.attach(self.label, 1, 0, 1, 1)
        grid.attach(self.spinner, 2, 0, 1, 1)
        # don't show spinner yet
        grid.attach(self.selector_button, 3, 0, 1, 1)
        # don't show selector button yet

        if not self.downloaded:
            self.label.set_sensitive(False)
            self.image.set_from_icon_name('dialog-question-symbolic', self.ICON_SIZE)

        self.connect('status-changed', self.status_changed_cb)
        self.status_changed_cb(self, self.status)
    def _new_activity(self, activity_id, tp, room):
        try:
            objid = self._get_next_object_id()
            activity = Activity(self._session_bus, objid, self, tp, room,
                                id=activity_id)
        except Exception:
            # FIXME: catching bare Exception considered harmful
            _logger.debug("Invalid activity:", exc_info=1)
            try:
                del self._activities_by_handle[tp][room]
            except KeyError:
                pass
            return None

        activity.connect("validity-changed",
                         self._activity_validity_changed_cb)
        activity.connect("disappeared", self._activity_disappeared_cb)
        self._activities_by_id[activity_id] = activity
        self._activities_by_handle[tp][room] = activity
        return activity
Example #44
0
    def append_extra(self, trs):
        """
        Append extra tiers in trs: Activity and PhnTokAlign.

        """
        tokenalign = trs.Find("TokensAlign")
        if tokenalign is None:
            self.print_message("No time-aligned tokens found. No extra tier can be generated.", indent=2, status=WARNING_ID)
            return trs

        # PhnTokAlign tier
        if self._options['phntok'] is True:
            try:
                phonalign = trs.Find("PhonAlign")
                tier = self.phntokalign_tier(phonalign,tokenalign)
                trs.Append(tier)
                trs.GetHierarchy().addLink("TimeAssociation", tokenalign, tier)
            except Exception as e:
                self.print_message("PhnTokAlign generation: %s"%str(e), indent=2, status=WARNING_ID)

        # Activity tier
        if self._options['activity'] is True or self._options['activityduration']:
            try:
                activity = Activity( trs )
                tier = activity.get_tier()
                if self._options['activity'] is True:
                    trs.Append(tier)
                    trs.GetHierarchy().addLink("TimeAlignment", tokenalign, tier)

                if self._options['activityduration'] is True:
                    dtier = tier.Copy()
                    dtier.SetName( "ActivityDuration" )
                    trs.Append(dtier)
                    for a in dtier:
                        d = a.GetLocation().GetDuration().GetValue()
                        a.GetLabel().SetValue( '%.3f' % d )

            except Exception as e:
                self.print_message("Activities generation: %s"%str(e), indent=2, status=WARNING_ID)

        return trs
Example #45
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     """change the mouse pointer by a hand"""
     self.button_down = 0
     self.rectList = [ 
             pygame.Rect(311, 91, 158, 51),
             pygame.Rect(546, 414, 67, 121),
             pygame.Rect(157, 358, 72, 109),
             ]
     self.sprites = pygame.sprite.OrderedUpdates()
     self.icons = pygame.sprite.Group()
     self.icons.add([Icons('stop')])
     image_check = image_normal = os.path.join(constants.icons_folder,\
             "check.png")
     self.checkImage, self.checkRect = common.load_image\
       (image_check)
     self.hand = Hand()
     self.tex_info = {
         'title': ["Una boca bien sana", None],
         'instructions' : [["Selecciona aquellos objetos", \
                         "que son necesarios para mantener tu boca sana"], None]
     }
Example #46
0
    def remove_follower(leader, follower):
        follower_id = follower.key().id()
        existing = (
            Follow.all()
            .ancestor(leader)
            .filter("leader_id =", leader.key().id())
            .filter("follower_ids =", follower_id)
            .get()
        )
        if not existing:
            return False
        existing.follower_ids.remove(follower_id)
        existing.put()
        # do dependent index
        index = existing.get_follow_index()
        for user_id in follower.all_user_ids:
            index.remove_follower(user_id)
        index.put()
        from activity import Activity

        Activity.create("<actor>|stopped following|<target>", actor=follower, target=leader, extra_recipients=[leader])
        return True
Example #47
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.correct = set()
     self.rectangleListEnter = [
             pygame.Rect(345, 90, 10, 15),
             pygame.Rect(340, 480, 10, 15),
             pygame.Rect(300, 390, 10, 15),
             pygame.Rect(493, 325, 10, 15),
             pygame.Rect(362, 299, 10, 15)
             ]
     self.pointList = [
             (350, 123),
             (400, 460),
             (277, 279),
             (451, 365)
             ]
     self.checkList = [
             (390, 80),
             (360, 520),
             (260, 340),
             (494, 358),
             (407, 304),
             ]
     self.ball = Ball(self.screen, (200,80))
     self.text_info = {
         'title': {
             'text': u"El laberinto de la salud",
             'offset': None
             },
         'instructions': {
             'text': [u"   Ayuda a Nina a realizar",
                     u"las tareas diarias a través",
                     u"del laberinto. Utiliza las",
                     u"teclas de desplazamiento."],
             'offset': 490
             }
     }
 def read(self, filename) :
     """
     Read a work sheet in a file
     """
     
     with open(filename, 'rb') as f :
         reader = csv.reader(f, dialect = CsvDialectSemiColon())
         ln = 0
         for row in reader :
             ln += 1
             try:
                 a = Activity.fromList(row)
                 self.add(a)
             except Exception as exc:
                 raise IOError("error at line %d: %s"%(ln,str(exc)))
Example #49
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.background = common.load_image(constants.illustration_024)[0]
     self.instruction_text()
Example #50
0
 def __init__(self):
     Activity.__init__(self, None)
Example #51
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.informative_text()
Example #52
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
            if properties:
                raise ValueError('Unsupported properties given: <%s>'
                                 % ', '.join(properties.iterkeys()))
        except ValueError, e:
            async_err_cb(e)
            return

        objid = self._get_next_object_id()
        # XXX: is the preferred Telepathy plugin always the right way to
        # share the activity?
        # We set private=True here - when the activity becomes shared
        # via join(), we'll set private to the correct value.
        activity = Activity(self._session_bus, objid, self,
                            self._get_preferred_plugin(), 0,
                            id=actid, type=atype,
                            name=name, color=self._owner.props.color,
                            local=True, private=True, tags=tags)

        activity.connect("validity-changed",
                         self._activity_validity_changed_cb)
        activity.connect("disappeared", self._activity_disappeared_cb)
        self._activities_by_id[actid] = activity

        def activity_shared():
            tp, room = activity.room_details
            self._activities_by_handle[tp][room] = activity
            async_cb(activity.object_path())

        activity.join(activity_shared, async_err_cb, sharing=True,
                      private=private, sender=sender)
Example #54
0
 def __init__(self, icarus):
    Activity.__init__(self, icarus)
Example #55
0
 def __init__(self, fsm, core, mon_data):
    Activity.__init__(self)
    self.fsm = fsm
    self.core = core
    self.mon_data = mon_data
    self.canceled = False
Example #56
0
    def do_activity(self, _args):
        """
Interact with exported activities on the device
        """
        subconsole = Activity(self.session)
        subconsole.cmdloop()
Example #57
0
 def test_decompose(self):
     self.assertRaises(UserWarning, Activity.decompose, [])
     self.assertRaises(UserWarning, Activity.decompose, 4.3)
     self.assertRaises(UserWarning, Activity.decompose, 'nop')
     self.assertRaises(UserWarning, Activity.decompose, sum([x.value for x in Activity.flags()])+1)
Example #58
0
 def __init__(self, icarus):
    Activity.__init__(self, icarus)
    self.canceled = False
Example #59
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.back1 = common.load_image(constants.illustration_005)[0]
     self.back2 = common.load_image(constants.illustration_006)[0]
     self.background = self.back1
Example #60
0
 def __init__(self, screen):
     Activity.__init__(self, screen)
     self.correct = set()