Пример #1
0
    def start_animation(self,
                        animation_time,
                        target_index=None,
                        direction="left"):
        if target_index is None:
            if self.active_index >= self.slider_numuber - 1:
                return False
                target_index = 0
            else:
                target_index = self.active_index + 1
        else:
            if target_index < self.active_index:
                direction = "right"

        if not self.in_animation:
            self.in_animation = True
            self.target_index = target_index

            self.timeline = Timeline(animation_time, CURVE_SINE)
            self.timeline.connect(
                "update", lambda source, status: self.update_animation(
                    source, status, direction))
            self.timeline.connect(
                "completed",
                lambda source: self.completed_animation(source, target_index))
            self.timeline.run()
        return True
Пример #2
0
class Switch():
    def __init__(self, switchRadix, reconfig_penalty, timeline_params):

        self.switchRadix = switchRadix
        self.reconfig_penalty = reconfig_penalty
        self.switch_scheduler = Scheduler(switchRadix, reconfig_penalty)
        self.demand = Timeline(timeline_params)
        self.reconfig_delay = reconfig_penalty
        self.currConfig = None

    def update(self, clock):

        if self.switch_scheduler.readyToSchedule(self.demand, clock):
            demandMatrix = self.demand.getDemand()
            self.switch_scheduler.scheduleDemand(demandMatrix)

        if self.reconfig_delay > 0:
            self.reconfig_delay = self.reconfig_delay - 1
            return

        if self.currConfig == None:
            self.currConfig = self.switch_scheduler.getNextConfig()

        if self.currConfig != None and self.currConfig.timeDuration > 0:
            self.demand.serveDemand(self.currConfig)
            self.currConfig.service()

            if self.currConfig.timeDuration == 0:

                self.currConfig = None
                self.reconfig_delay = self.reconfig_penalty
Пример #3
0
class World:
    """
    The Underworlds world data structure
    """
    def __init__(self, name, meshes):
        self.__scene = Scene()
        self.__timeline = Timeline()
        self.__meshes = meshes
        self.__name = name

    def apply_changes(self, header, changes):
        invalidations = Invalidations()

        invalidations.node_ids_deleted = self.__scene.remove(
            changes.nodes_to_delete)
        invalidations.node_ids_updated = self.__scene.update(
            changes.nodes_to_update)

        invalidations.situation_ids_deleted = self.__timeline.remove(
            changes.situations_to_delete)
        invalidations.situation_ids_updated = self.__timeline.update(
            changes.situations_to_update)

        for mesh_id in changes.meshes_to_delete:
            del self.__meshes[mesh_id]
            invalidations.mesh_ids_deleted.append(mesh_id)
        for mesh in changes.meshes_to_update:
            self.__meshes[mesh.id] = mesh
            invalidations.mesh_ids_updated.append(mesh.id)
        return invalidations

    def reset(self):
        self.__scene.reset(self.__scene.root_id())
        self.__timeline.reset(self.__timeline.origin().data)
        self.__meshes.reset()
Пример #4
0
    def label_timeline(self, label):
        """Get timeline for a given label

        Parameters
        ----------
        label :

        Returns
        -------
        timeline : :class:`Timeline`
            Timeline made of all segments annotated with `label`

        """
        if label not in self.labels():
            return Timeline(uri=self.uri)

        if self._labelNeedsUpdate[label]:
            self._updateLabels()

            for l, hasChanged in self._labelNeedsUpdate.iteritems():
                if hasChanged:
                    self._labels[l] = Timeline(uri=self.uri)

            for segment, track, l in self.itertracks(label=True):
                if self._labelNeedsUpdate[l]:
                    self._labels[l].add(segment)

            self._labelNeedsUpdate = {l: False for l in self._labels}

        return self._labels[label].copy()
def timeline_json():
    headline = "Timeline Photo Headline"
    text = "this is the text"
    start_date = '2012,4,12'

    # find settings
    settings = Setting.query.order_by(desc(Setting.id)).all()
    if len(settings) > 0:
        setting = settings[0]
        headline = setting.headline
        text = setting.setting_text
        start_date = setting.start_date.replace("-", ",")

    # convert timeline's start date to datetime obj
    album_start_date = datetime.datetime.strptime(start_date, "%Y,%m,%d")

    # collect all photos
    tl = Timeline(headline, text, start_date)
    photos = Photo.query.filter(Photo.visibility == True).all()
    for photo in photos:
        dt = photo.start_date.replace("-", ",")

        # convert photo's start date to datetime obj
        photo_start_date = datetime.datetime.strptime(dt, "%Y,%m,%d")
        days_in_album = (photo_start_date - album_start_date).days + 1
        # get No.D after timeline's start date
        asset_caption = _("Day %(value)d", value=days_in_album)

        text = photo.photo_text + "<BR/><BR/><A href='%s'><i class='icon-zoom-in'></i>%s</A>" % (url_for("photos.show_html", filename=photo.filename), photo.filename)

        tl.add_date(startDate=dt, headline=photo.headline, asset_media=url_for("photos.show_thumb", filename=photo.filename), text=text, asset_caption=asset_caption)
    return tl.get_json()
Пример #6
0
    def __init__(self, switchRadix, reconfig_penalty, timeline_params):

        self.switchRadix = switchRadix
        self.reconfig_penalty = reconfig_penalty
        self.switch_scheduler = Scheduler(switchRadix, reconfig_penalty)
        self.demand = Timeline(timeline_params)
        self.reconfig_delay = reconfig_penalty
        self.currConfig = None
Пример #7
0
    def test_daily(self):
        n_days = 10
        data = get_timed_data(n_days)

        timeline = Timeline(data)
        daily = timeline.split_daily()

        self.assertEqual(len(daily), n_days, msg='Testing with {} days should yield dictionary with {} items'.format(daily, daily))
Пример #8
0
 def graphicsView_reset(self):
     self.projects_list = db.get_projects()
     timeline = Timeline(self.projects_list)
     self.dates = timeline.generate_timeline()
     self.timeline_scene = self.create_scene()
     self.graphicsView.setScene(self.timeline_scene)
     self.projects = create_project_items(self.projects_list)
     self.show_projects()
     self.timeline_scene.itemClicked.connect(self.project_clicked)
Пример #9
0
def singlebeat(beat, *args, **kwargs):
    beat_timeline = Timeline()
    time = 0.0
    beat_timeline.add(time+0.0, beat)

    print "Rendering beat audio..."
    beat_data = beat_timeline.render()

    return beat_data
Пример #10
0
    def test_get_merged_timeline__single_timeline(self):
        """Verify merged timeline of exactly one partial timeline.
        """
        partial_timeline = ['one', 'two', 'three', 'four']
        timeline = Timeline(partial_timelines=[partial_timeline])

        # Verify get_merged_timelines return value
        merged_timelines = timeline.get_merged_timelines()
        self.assertEqual([partial_timeline], merged_timelines)
Пример #11
0
 def test_get_all_subsequent_events__simple(self):
     """Verify behavior of _get_all_subsequent_events.
     """
     timeline = Timeline()
     timeline._subsequent_events = {'one': set(['two']),
                                   'two': set(['three']),
                                   'three': set(['four']),
                                   'four': set()}
     subsequent_events = timeline._get_all_subsequent_events('one')
     self.assertEqual(set(['two', 'three', 'four']), subsequent_events)
 def clear(self):
     self.global_settings = {}
     PlateDesign.clear()
     #
     # TODO:
     #
     self.timeline = Timeline('TEST_STOCK')
     for matchstring, callbacks in self.subscribers.items():
         for callback in callbacks:
             callback(None)
Пример #13
0
    def test_get_merged_timelines__full_merge__interleaved(self):
        """Verify that unambiguous interleaved timelines merge correctly.
        """
        partial_timelines = [['two', 'three', 'seven'],
                             ['three', 'four', 'five', 'seven']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        self.assertEqual([['two', 'three', 'four', 'five', 'seven']],
                         merged_timelines)
Пример #14
0
    def test_get_merged_timelines__full_merge__start_and_end_overlap(self):
        """Verify that unambiguous overlapping timelines merge correctly.
        """
        partial_timelines = [['two', 'three', 'six'],
                             ['six', 'seven'],
                             ['one', 'two']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        self.assertEqual([['one', 'two', 'three', 'six', 'seven']],
                         merged_timelines)
Пример #15
0
    def test_get_merged_timelines__full_merge__shooting_example(self):
        """Verify that full merge is possible for shooting example.
        """
        partial_timelines = [
            ['shouting', 'fight', 'fleeing'],
            ['fight', 'gunshot', 'panic', 'fleeing'],
            ['anger', 'shouting']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        self.assertEqual([['anger', 'shouting', 'fight', 'gunshot', 'panic', 'fleeing']],
                         merged_timelines)
Пример #16
0
    def test_eq(self):
        t1 = Timeline(elements=[ScoreSpaceElement(0), ScoreSpaceElement(1)])
        t2 = Timeline(elements=[ScoreSpaceElement(0)])
        t3 = Timeline()
        t4 = Timeline(elements=[ScoreSpaceElement(0), ScoreSpaceElement(1)])
        t5 = Timeline(elements=[ScoreSpaceElement(1), ScoreSpaceElement(1)])

        self.assertEqual(t1, t4)
        self.assertNotEqual(t1, t2)
        self.assertNotEqual(t1, t3)
        self.assertNotEqual(t2, t3)
        self.assertNotEqual(t4, t5)
Пример #17
0
def singlenote(note_number, *args, **kwargs):
    singlenote_timeline = Timeline()
    time = 0.0 # Keep track of currect note placement time in seconds

    # Strum out root chord to finish
    chord = kwargs['progression'][0]
    singlenote_timeline.add(time + 0.0, Hit(chord.notes[note_number], 3.0))

    print "Rendering singlenote audio..."
    singlenote_data = singlenote_timeline.render()

    return singlenote_data
Пример #18
0
    def test_daily(self):
        n_days = 10
        data = get_timed_data(n_days)

        timeline = Timeline(data)
        daily = timeline.split_daily()

        self.assertEqual(
            len(daily),
            n_days,
            msg='Testing with {} days should yield dictionary with {} items'.
            format(daily, daily))
Пример #19
0
def settings(user_token):
    try:
        user = User.objects.get(user_token=user_token)
    except User.DoesNotExist:
        return render_template('registration_wait.html')

    # Wait until geocode completes
    if not user.location_geoname:
        return render_template('registration_wait.html')

    if not user.timeline_token:
        return render_template('no_timeline.html')

    if request.method == "POST":
        old_config = dict(user.config)
        user.config["method"] = request.form["method"]
        user.config["asr"] = request.form["asr"]
        user.config["prayer_names"] = request.form["prayer_names"]
        user.save()
        if old_config != user.config:
            Timeline.push_pins_for_user(user)
        return render_template('settings_confirmed.html')

    # Allow calculation method to override geocoded name, where applicable
    location = user.location
    if hasattr(location, "keys"):
        location = location['coordinates']
    location = location[::-1]  # From the database, it's lon/lat
    location_geoname = TimetableResolver.ResolveLocationGeoname(
        user.config["method"], user.config, location)
    if location_geoname is None:
        location_geoname = user.location_geoname

    asr_options = ["Standard", "Hanafi"]

    method_options = sorted(list(TimetableResolver.Methods()))
    asr_setting_availability = json.dumps(
        {x: TimetableResolver.AsrSettingAvailable(x)
         for x in method_options})
    prayer_name_options = {
        k:
        ", ".join([v[p] for p in ["fajr", "dhuhr", "asr", "maghrib", "isha"]])
        for k, v in sorted(list(Timeline.PRAYER_NAMES.items()),
                           key=lambda i: i[0] == "standard")
    }
    return render_template('settings.html',
                           user=user,
                           location_geoname=location_geoname,
                           asr_options=asr_options,
                           method_options=method_options,
                           asr_setting_availability=asr_setting_availability,
                           prayer_name_options=prayer_name_options)
Пример #20
0
    def test_add_partial_timeline__simple(self):
        """Verify side-effects of single call to add_partial_timeline.
        """
        partial_timeline = ['one', 'two', 'three', 'four']
        timeline = Timeline()
        timeline.add_partial_timeline(partial_timeline)

        # Verify internal timeline data
        expected_subsequent_events = {'one': set(['two']),
                                      'two': set(['three']),
                                      'three': set(['four']),
                                      'four': set()}
        self.assertEqual(expected_subsequent_events, timeline._subsequent_events)
Пример #21
0
 def test_add_partial_timeline__contradiction(self):
     """Verify that order contradiction is detected and avoided.
     """
     partial_timelines = [
         ['one', 'two', 'three'],
         ['three', 'two']]
     timeline = Timeline()
     timeline.add_partial_timeline(partial_timelines[0])
     self.assertRaisesRegexp(
         ValueError,
         "Contradiction detected: event 'three' comes before and after event 'two'",
         timeline.add_partial_timeline,
         partial_timelines[1])
Пример #22
0
 def test_get_all_subsequent_events__branching(self):
     """Verify behavior of _get_all_subsequent_events when events overlap.
     """
     timeline = Timeline()
     timeline._subsequent_events = {'one': set(['two']),
                                    'two': set(['three']),
                                    'three': set(['six', 'four']),
                                    'four': set(['five']),
                                    'five': set(['six']),
                                    'six': set(['seven']),
                                    'seven': set()}
     subsequent_events = timeline._get_all_subsequent_events('one')
     self.assertEqual(set(['two', 'three', 'four', 'five', 'six', 'seven']), subsequent_events)
Пример #23
0
    def test_get_merged_timelines__no_merge__scandal_example(self):
        """Verify that no merge is possible for scandal example.
        """
        partial_timelines = [
            ['argument', 'coverup', 'pointing'],
            ['press brief', 'scandal', 'pointing'],
            ['argument', 'bribe']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        expected_timelines = partial_timelines
        self.assertEqual(len(expected_timelines), len(merged_timelines))
        for merged_timeline in merged_timelines:
            self.assertTrue(merged_timeline in expected_timelines)
Пример #24
0
    def test_place(self):
        a1 = Animation(np.ndarray((2, 1)))

        scores = [
            [ScoreSpaceElement(0, 0, anim=a1), ScoreSpaceElement(3, 1, anim=a1), ScoreSpaceElement(5, 2, anim=a1), ScoreSpaceElement(6, 3, anim=a1)],
            [ScoreSpaceElement(1, 0, anim=a1), ScoreSpaceElement(2, 1, anim=a1), ScoreSpaceElement(4, 2, anim=a1), ScoreSpaceElement(5, 3, anim=a1)],
            [ScoreSpaceElement(4, 2, anim=a1), ScoreSpaceElement(6, 1, anim=a1), ScoreSpaceElement(10, 0, anim=a1)]
        ]

        timeline = Timeline(10)
        TimelinePlacer.layout_score_space_on_timeline(scores, timeline)
        desired_timeline = Timeline(length=10, elements=[ScoreSpaceElement(0, 0, anim=a1), ScoreSpaceElement(4, 2, anim=a1)])

        self.assertEqual(desired_timeline, timeline)
Пример #25
0
    def test_get_merged_timelines__partial_merge(self):
        """Verify that ambiguous partial timelines are merged as far as possible.
        """
        partial_timelines = [['two', 'three', 'four', 'seven', 'eight'],
                             ['one', 'two', 'five', 'six', 'seven']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        expected_timelines = [
            ['one', 'two', 'three', 'four', 'seven', 'eight'],
            ['one', 'two', 'five', 'six', 'seven', 'eight']]
        self.assertEqual(len(expected_timelines), len(merged_timelines))
        for merged_timeline in merged_timelines:
            self.assertTrue(merged_timeline in expected_timelines)
Пример #26
0
    def handle_button_press(self, cr, rect, event_x, event_y):
        if self.is_expandable:
            if not self.in_animation:
                if self.has_expand:
                    text_width, text_height = self.shrink_button_width, self.shrink_button_height
                else:
                    text_width, text_height = self.expand_button_width, self.expand_button_height
                if is_in_rect((event_x, event_y),
                              (rect.width - (rect.width - self.label_wrap_width) / 2 - text_width,
                               rect.height - text_height,
                               text_width,
                               text_height)):

                    if self.has_expand:
                        start_position = self.expand_height
                        animation_distance = self.init_height - self.expand_height
                    else:
                        start_position = self.init_height
                        animation_distance = self.expand_height - self.init_height

                    self.in_animation = True

                    timeline = Timeline(self.animation_time, CURVE_SINE)
                    timeline.connect('update', lambda source, status:
                                     self.update(source,
                                                 status,
                                                 start_position,
                                                 animation_distance))
                    timeline.connect("completed", self.completed)
                    timeline.run()
        else:
            print "no expand button"
Пример #27
0
    def test_get_merged_timelines__partial_merge__foiled_mugging_example(self):
        """Verify that partial merge is possible for foiled_mugging example.
        """
        partial_timelines = [
            ['shadowy figure', 'demands', 'scream', 'siren'],
            ['shadowy figure', 'pointed gun', 'scream']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        expected_timelines = [
            ['shadowy figure', 'demands', 'scream', 'siren'],
            ['shadowy figure', 'pointed gun', 'scream', 'siren']]
        self.assertEqual(len(expected_timelines), len(merged_timelines))
        for merged_timeline in merged_timelines:
            self.assertTrue(merged_timeline in expected_timelines)
Пример #28
0
    def test_get_merged_timelines__partial_merge__arson_example(self):
        """Verify that partial merge is possible for arson example.
        """
        partial_timelines = [
            ['pouring gas', 'laughing', 'lighting match', 'fire'],
            ['buying gas', 'pouring gas', 'crying', 'fire', 'smoke']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        expected_timelines = [
            ['buying gas', 'pouring gas', 'crying', 'fire', 'smoke'],
            ['buying gas', 'pouring gas', 'laughing', 'lighting match', 'fire', 'smoke']]
        self.assertEqual(len(expected_timelines), len(merged_timelines))
        for merged_timeline in merged_timelines:
            self.assertTrue(merged_timeline in expected_timelines)
Пример #29
0
    def follow(self, target):
        current_time = time()

        user_following_tl = Timeline(self.client, following_key(self.user))
        user_following_tl.add(target, current_time)

        target_follower_tl = Timeline(self.client, follower_key(target))
        target_follower_tl.add(self.user, current_time)
Пример #30
0
    def test_free_frames_set(self):
        t = Timeline()
        self.assertEqual(set(), t.free_frames_set())

        t = Timeline(length=5)
        self.assertEqual(set(range(5)), t.free_frames_set())

        anim1 = Animation(np.ndarray((2, 1)))  # Anim with 2 frames
        se1 = ScoreSpaceElement(0, anim=anim1, window_start_frame=0)

        t.add_element(se1)  # Must reserve frames 0 and 1
        self.assertEqual(set(range(2, 5)), t.free_frames_set())
Пример #31
0
    def OnInit(self):
        try:
            if self.options.record:
                # Connect to ROS master
                if not self.connect_to_ros():
                    raise Exception('recording requires connection to master')

                # Get filename to record to
                record_filename = time.strftime('%Y-%m-%d-%H-%M-%S.bag', time.localtime(time.time()))
                if self.options.name:
                    record_filename = self.options.name
                    if not record_filename.endswith('.bag'):
                        record_filename += '.bag'
                elif self.options.prefix:
                    prefix = self.options.prefix
                    if prefix.endswith('.bag'):
                        prefix = prefix[:-len('.bag')]
                    if prefix:
                        record_filename = '%s_%s' % (prefix, record_filename)

                rospy.loginfo('Recording to %s.' % record_filename)

            # Create main timeline frame
            self.frame = BaseFrame(None, 'rxbag', 'Timeline')
            self.frame.BackgroundColour = wx.WHITE
            self.frame.Bind(wx.EVT_CLOSE, lambda e: wx.Exit())

            scroll = wx.ScrolledWindow(self.frame, -1)
            scroll.BackgroundColour = wx.WHITE
            
            timeline = Timeline(scroll, -1)
            timeline.Size = (100, 100)
            
            self.frame.Show()
            self.SetTopWindow(self.frame)

            timeline.SetFocus()

            if self.options.record:
                timeline.record_bag(record_filename, all=self.options.all, topics=self.args, regex=self.options.regex, limit=self.options.limit)
            else:
                RxBagInitThread(self, timeline)

        except Exception, ex:
            print >> sys.stderr, 'Error initializing application:', ex
            #import traceback
            #traceback.print_exc()
            return False
Пример #32
0
def object_hook(d):
    """
    Usage
    -----
    >>> import simplejson as json
    >>> with open('file.json', 'r') as f:
    ...   json.load(f, object_hook=object_hook)
    """

    from segment import Segment
    from timeline import Timeline
    from annotation import Annotation
    from transcription import Transcription

    if PYANNOTE_JSON_SEGMENT in d:
        return Segment.from_json(d)

    if PYANNOTE_JSON_TIMELINE in d:
        return Timeline.from_json(d)

    if PYANNOTE_JSON_ANNOTATION in d:
        return Annotation.from_json(d)

    if PYANNOTE_JSON_TRANSCRIPTION in d:
        return Transcription.from_json(d)

    return d
Пример #33
0
def object_hook(d):
    """
    Usage
    -----
    >>> import simplejson as json
    >>> with open('file.json', 'r') as f:
    ...   json.load(f, object_hook=object_hook)
    """

    from segment import Segment
    from timeline import Timeline
    from annotation import Annotation
    from transcription import Transcription

    if PYANNOTE_JSON_SEGMENT in d:
        return Segment.from_json(d)

    if PYANNOTE_JSON_TIMELINE in d:
        return Timeline.from_json(d)

    if PYANNOTE_JSON_ANNOTATION in d:
        return Annotation.from_json(d)

    if PYANNOTE_JSON_TRANSCRIPTION in d:
        return Transcription.from_json(d)

    return d
Пример #34
0
    def setUp(self):
        self.client = Redis(decode_responses=True)
        self.client.flushdb()

        self.tl = Timeline(self.client, "blog::timeline")

        self.blogs = [
            {"id": "blog::100", "time": 1000},
            {"id": "blog::101", "time": 1500},
            {"id": "blog::102", "time": 1550},
            {"id": "blog::103", "time": 1700},
            {"id": "blog::104", "time": 1750},
            {"id": "blog::105", "time": 2500}
        ]

        self.reversed_blogs = list(reversed(self.blogs))
Пример #35
0
    def to_page(self, w, direction):
        '''
        Slide to given page.
        
        @param w: gtk.Widget to slide.
        @param direction: The direction of slide animation, can use below value:
         - \"right\"    slide from right to left
         - \"left\"     slide from left to right
         - None         no animation effect, slide directly
        '''
        if self.in_sliding:
            return

        if w != self.active_widget:
            w.set_size_request(self.page_width, self.page_height)
            if w.parent != self.fixed:
                self.fixed.put(w, self.page_width, 0)
            self.active_widget = w

            self.timeline = Timeline(self.slide_time, CURVE_SINE)
            if direction == "right":
                self.timeline.connect('update', lambda source, status: self._to_right(status))
            elif direction == "left":
                self.timeline.connect('update', lambda source, status: self._to_left(status))
            else:
                self._no_effect()

            self.timeline.connect("start", lambda source: self._start())
            self.timeline.connect("completed", lambda source: self._completed())
            self.timeline.run()
            self.in_sliding = True

            self.show_all()
Пример #36
0
def subscribe():
    data = request.get_json()
    user_token = data["user_token"]
    user = User.objects(user_token=user_token) \
      .modify(upsert=True, new=True, set_on_insert__created_at=datetime.utcnow())
    if "timeline_token" in data:
        user.timeline_token = data["timeline_token"]
    user.location = [float(data["location_lon"]), float(data["location_lat"])]
    user.tz_offset = int(data["tz_offset"])
    user.subscribed_at = datetime.utcnow()
    user.geocode()
    user.save()
    Timeline.push_pins_for_user(user)

    result = {"location_geoname": user.location_geoname}
    return jsonify(result)
Пример #37
0
    def __init__(self, file=None, verbose=False):
        # Create an empty workplace
        self.agents = []
        self.completed_tasks = []
        self.current_task = None
        self.tasks_todo = []
        self.time = 0
        self.timeline = Timeline()  # list of TimePoints
        self.coordination_times = {}
        self.Tperf = {}

        self.verbose = verbose

        if file:
            print("Reading from input file " + file + "...\n")
            self.parse_json(file, verbose)
Пример #38
0
 def set_value(self, value):
     if (not self.in_animation) and value != self.value:
         self.start_value = self.value
         self.range = value - self.value
         times = int(abs(self.range)) * 10
         from timeline import Timeline, CURVE_SINE
         timeline = Timeline(times * 10, CURVE_SINE)
         timeline.connect("start", self.start_animation)
         timeline.connect("stop", self.stop_animation)
         timeline.connect("update", self.update_animation)
         timeline.run()
         
     return False    
Пример #39
0
def strum(*args, **kwargs):
    strum_timeline = Timeline()
    time = 0.0 # Keep track of currect note placement time in seconds

    # Strum out root chord to finish
    chord = kwargs['progression'][0]
    strum_timeline.add(time + 0.0, Hit(chord.notes[0], 4.0))
    strum_timeline.add(time + 0.1, Hit(chord.notes[1], 4.0))
    strum_timeline.add(time + 0.2, Hit(chord.notes[2], 4.0))
    strum_timeline.add(time + 0.3, Hit(chord.notes[1].transpose(12), 4.0))
    strum_timeline.add(time + 0.4, Hit(chord.notes[2].transpose(12), 4.0))
    strum_timeline.add(time + 0.5, Hit(chord.notes[0].transpose(12), 4.0))

    print "Rendering strum audio..."
    strum_data = strum_timeline.render()

    return strum_data
Пример #40
0
def get_request_timeline(request):
    """Get a `Timeline` for request.

    This should ideally return the request.annotations['timeline'], creating it
    if necessary. However due to bug 623199 it instead using the adapter
    context for 'requests'. Once bug 623199 is fixed it will instead use the
    request annotations.

    :param request: A zope/launchpad request object.
    :return: A timeline.timeline.Timeline object for the request.
    """
    try:
        return webapp.adapter._local.request_timeline
    except AttributeError:
        return set_request_timeline(request, Timeline())
    # Disabled code path: bug 623199, ideally we would use this code path.
    return request.annotations.setdefault('timeline', Timeline())
Пример #41
0
    def set_value(self, value):
        if (not self.in_animation) and value != self.value:
            self.start_value = self.value
            self.range = value - self.value
            times = int(abs(self.range)) * 10
            if times != 0:
                from timeline import Timeline, CURVE_SINE
                timeline = Timeline(times * 10, CURVE_SINE)
                timeline.connect("start", self.start_animation)
                timeline.connect("stop", self.stop_animation)
                timeline.connect("update", self.update_animation)
                timeline.run()
            else:
                self.value = value
                self.queue_draw()

        return False
Пример #42
0
 def handle_button_press(self, cr, rect, event_x, event_y):
     if self.is_expandable:
         if not self.in_animation:
             if self.has_expand:
                 text_width, text_height = self.shrink_button_width, self.shrink_button_height
             else:
                 text_width, text_height = self.expand_button_width, self.expand_button_height
             if is_in_rect((event_x, event_y), 
                           (rect.width - (rect.width - self.label_wrap_width) / 2 - text_width,
                            rect.height - text_height,
                            text_width,
                            text_height)):
                 
                 if self.has_expand:
                     start_position = self.expand_height
                     animation_distance = self.init_height - self.expand_height
                 else:
                     start_position = self.init_height
                     animation_distance = self.expand_height - self.init_height
                 
                 self.in_animation = True    
                     
                 timeline = Timeline(self.animation_time, CURVE_SINE)
                 timeline.connect('update', lambda source, status: 
                                  self.update(source,
                                              status, 
                                              start_position,
                                              animation_distance))
                 timeline.connect("completed", self.completed)
                 timeline.run()
     else:
         print "no expand button"
Пример #43
0
def arpeggio(*args, **kwargs):

    arpeggio_timeline = Timeline()
    time = 0.0 # Keep track of currect note placement time in seconds

    # Add progression to timeline by arpeggiating chords from the progression
    for index in [0, 1]:
      chord = kwargs['progression'][index]
      root, third, fifth = chord.notes
      arpeggio = [root, third, fifth, third, root, third, fifth, third]
      for i, interval in enumerate(arpeggio):
        ts = float(i * 2) / len(arpeggio)
        arpeggio_timeline.add(time + ts, Hit(interval, 1.0))
      time += 2.0

    print "Rendering arpeggio audio..."
    arpeggio_data = arpeggio_timeline.render()

    return arpeggio_data
Пример #44
0
Файл: tyrs.py Проект: Nic0/tyrs
def init_timelines():
    buffers = ('home', 'mentions', 'direct', 'search', 'user', 'favorite',
               'thread', 'user_retweet', 'list')
    timelines = {}
    for buff in buffers:
        timelines[buff] = Timeline(buff)
    container.add('timelines', timelines)
    container.add('buffers', buffers)
    completion = Completion()
    container.add('completion', completion)
 def clear(self):
     self.global_settings = {}
     PlateDesign.clear()
     #
     # TODO:
     #
     self.timeline = Timeline('TEST_STOCK')
     for matchstring, callbacks in self.subscribers.items():
         for callback in callbacks:
             callback(None)
Пример #46
0
    def test_construct(self):
        with self.assertRaises(ValueError):
            Timeline(length=-1)

        t = Timeline()
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 0)

        t = Timeline(length=5)
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 5)

        t = Timeline(elements=[])
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 0)

        els = [ScoreSpaceElement(0), ScoreSpaceElement(1)]
        t = Timeline(elements=els)
        self.assertListEqual(els, t.elements)
Пример #47
0
    def slide_to(self, widget):

        self.active_widget = widget

        def update(source, status):
            pos = end_position - start_position
            adjustment.set_value(start_position + int(round(status * pos)))

        adjustment = self.get_hadjustment()
        start_position = adjustment.get_value()
        end_position = widget.get_allocation().x

        if start_position != end_position:
            timeline = Timeline(500, CURVE_SINE)
            timeline.connect('update', update)
            timeline.run()
            
        if self.slide_callback:    
            self.slide_callback(self.layout.get_children().index(widget), widget)
Пример #48
0
def main():
    parser = CommandParser()
    try:
        command_list = parser.parse()
    except CommandParser.ParserException as e:
        sys.exit(e)

    router = Router(command_list)
    runner_class = router.get_runner()
    timeline = Timeline()
    runner_class(timeline).run(command_list)
Пример #49
0
    def test_get_merged_timelines__multiple_partial_merge(self):
        """Verify that ambiguous partial timelines are merged in multiple places.

        Note that generating four timelines may not be the desired behavior. Rather, we 
        would like two timelines with merged fronts, middles, and ends, one timeline with 
        the divergent sections of the first partial timeline and the other with the
        divergent sections of the second partial timeline.
        """
        partial_timelines = [['two', 'three', 'four', 'six', 'seven', 'eight', 'nine', 'eleven'],
                             ['one', 'two', 'five', 'six', 'seven', 'ten', 'eleven', 'twelve']]
        timeline = Timeline(partial_timelines=partial_timelines)

        merged_timelines = timeline.get_merged_timelines()
        expected_timelines = [
            ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine', 'eleven', 'twelve'],
            ['one', 'two', 'three', 'four', 'six', 'seven', 'ten', 'eleven', 'twelve'],
            ['one', 'two', 'five', 'six', 'seven', 'eight', 'nine', 'eleven', 'twelve'],
            ['one', 'two', 'five', 'six', 'seven', 'ten', 'eleven', 'twelve']]
        self.assertEqual(len(expected_timelines), len(merged_timelines))
        for merged_timeline in merged_timelines:
            self.assertTrue(merged_timeline in expected_timelines)
Пример #50
0
    def test_process_and_get_timeline(self):
        p = AnimationRecognitionProcessor()
        p.process(self.data)
        timeline = p.get_timeline_with_placed_animations()

        desired_timeline = Timeline(
            length=5,
            elements=[
                ScoreSpaceElement(0, 0, self.lib_anim1),
                ScoreSpaceElement(4, 2, self.lib_anim2)
            ])

        self.assertEqual(desired_timeline, timeline)
Пример #51
0
 def __init__(self, width, height, player=None):
     self.width = width
     self.height = height
     self.grid = Grid(width, height)
     self.player = Player
     #self.camera = Camera(51, 19, self)
     self.camera = Camera(51, 19, self)
     self.output_buffer = OutputBuffer(self.camera.lensHeight)
     self.timeline = Timeline(100)
     self.portalList = []
     self.triggerTileList = []
     self.name = None
     #not used
     self.viewDistance = 3
Пример #52
0
class Window(QtGui.QMainWindow):


    def __init__(self):
        super(Window, self).__init__()
        self.ctr = 0
        self.timeline = Timeline()
        self.signals_slots = signals_slots.Signal_Slots()

        #timer for animation
        #self.timer = QtCore.QTimer(self)
        #self.connect(self.timer,
        #             QtCore.SIGNAL("timeout()"),
        #             self.update)
        #self.timer.start(DELAY)
    
    def setup_connections( self, ui ) :
        ui.actionExit.triggered.connect(QtCore.QCoreApplication.instance().quit )
        ui.actionOpen.triggered.connect(lambda: self.signals_slots.open_file(self, ui))
        ui.playButton.clicked.connect(lambda: self.signals_slots.start_playback(self, ui))
        ui.stopButton.clicked.connect(lambda: self.signals_slots.stop_playback(self, ui))
        ui.seekSlider.setMediaObject(ui.videoPlayer.mediaObject())
        ui.volumeSlider.setAudioOutput(ui.videoPlayer.audioOutput())

        #ticker
        ui.videoPlayer.mediaObject().tick.connect(self.tick)



    def paintEvent(self, e):
        print "paintEvent called"
        
        start = {"x" : 170, "y" : 410 }
        end = {"x" : 430, "y" : 500}
        lines = { "short" : 5, "long" : 12 }

        qp = QtGui.QPainter()
        qp.begin(self)
        self.timeline.drawRectangles(qp, start, end, lines)
        self.timeline.drawLines(qp, start, end, lines)

        self.timeline.drawTicker(qp, start, end, lines, self.ctr)

        qp.end()    


    #def update( self) :
    #    print "something"
    #    self.ctr = self.ctr + 1
    #    print self.ctr
    #    self.repaint()

    def tick(self, time):
        displayTime = QtCore.QTime(0, (time / 60000) % 60, (time / 1000) % 60).second()
        print displayTime * 10
        self.ctr = displayTime * 10
        self.repaint()
Пример #53
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.ctr = 0
        self.timeline = Timeline()
        self.signals_slots = signals_slots.Signal_Slots()

        #timer for animation
        #self.timer = QtCore.QTimer(self)
        #self.connect(self.timer,
        #             QtCore.SIGNAL("timeout()"),
        #             self.update)
        #self.timer.start(DELAY)

    def setup_connections(self, ui):
        ui.actionExit.triggered.connect(
            QtCore.QCoreApplication.instance().quit)
        ui.actionOpen.triggered.connect(
            lambda: self.signals_slots.open_file(self, ui))
        ui.playButton.clicked.connect(
            lambda: self.signals_slots.start_playback(self, ui))
        ui.stopButton.clicked.connect(
            lambda: self.signals_slots.stop_playback(self, ui))
        ui.seekSlider.setMediaObject(ui.videoPlayer.mediaObject())
        ui.volumeSlider.setAudioOutput(ui.videoPlayer.audioOutput())

        #ticker
        ui.videoPlayer.mediaObject().tick.connect(self.tick)

    def paintEvent(self, e):
        print "paintEvent called"

        start = {"x": 170, "y": 410}
        end = {"x": 430, "y": 500}
        lines = {"short": 5, "long": 12}

        qp = QtGui.QPainter()
        qp.begin(self)
        self.timeline.drawRectangles(qp, start, end, lines)
        self.timeline.drawLines(qp, start, end, lines)

        self.timeline.drawTicker(qp, start, end, lines, self.ctr)

        qp.end()

    #def update( self) :
    #    print "something"
    #    self.ctr = self.ctr + 1
    #    print self.ctr
    #    self.repaint()

    def tick(self, time):
        displayTime = QtCore.QTime(0, (time / 60000) % 60,
                                   (time / 1000) % 60).second()
        print displayTime * 10
        self.ctr = displayTime * 10
        self.repaint()
    def layout_score_space_on_timeline(score_space: List[
        List[ScoreSpaceElement]], timeline: Timeline) -> Timeline:
        # TODO Replace List[List[ScoreSpaceElement]] with LinearScoreSpace or smth. everywhere
        """
        Grab elements from the score space and drop them onto the timeline using some algorithm,
        that may (and will) change. So consider it to be sort of a callback or mixin or...

        
        So, the algorithm is:
        1. Find the highest score through all the ScoreSpaceElements
        
        2. If each of its frames is not reserved on the timeline
           2.1. Add it to the timeline
           2.2. Add the frames occupied by the animation to the reserved frames list
           
        3. Drop it from the list
        
        4. Repeat step 1 till the timeline is full or till the score list is empty.
        - 
        """

        # This is a temporary trick while I don't use the ScoreSpace everywhere in the code
        # instead of list of lists
        from score_space_simple_2d import ScoreSpaceSimple2D
        score_space = ScoreSpaceSimple2D(score_space)

        while not score_space.empty():
            score_element = score_space.get_best_score_element(remove=True)

            try:
                timeline.add_element(score_element)
                print(f"Added {score_element} to timeline")
            except FramesAlreadyReservedError:
                # Just drop the elements which can't be placed to the Timeline and move on
                pass

        return timeline
Пример #55
0
 def start_animation(self, index, tab_start_x):
     if not self.in_animiation:
         self.in_animiation = True
         
         source_tab_x = tab_start_x + self.tab_index * self.tab_width
         target_tab_x = tab_start_x + index * self.tab_width
         
         timeline = Timeline(self.tab_animation_time, CURVE_SINE)
         timeline.connect('update', lambda source, status: self.update_animation(source, status, source_tab_x, (target_tab_x - source_tab_x)))
         timeline.connect("completed", lambda source: self.completed_animation(source, index))
         timeline.run()
         
         self.emit("tab-switch-start", index)
Пример #56
0
    def to_page(self, w, direction):
        '''
        Slide to given page.

        @param w: gtk.Widget to slide.
        @param direction: The direction of slide animation, can use below value:
         - \"right\"    slide from right to left
         - \"left\"     slide from left to right
         - None         no animation effect, slide directly
        '''
        if self.in_sliding:
            return

        if w != self.active_widget:
            w.set_size_request(self.page_width, self.page_height)
            if w.parent != self.fixed:
                self.fixed.put(w, self.page_width, 0)
            self.active_widget = w

            self.timeline = Timeline(self.slide_time, CURVE_SINE)
            if direction == "right":
                self.timeline.connect(
                    'update', lambda source, status: self._to_right(status))
            elif direction == "left":
                self.timeline.connect(
                    'update', lambda source, status: self._to_left(status))
            else:
                self._no_effect()

            self.timeline.connect("start", lambda source: self._start())
            self.timeline.connect("completed",
                                  lambda source: self._completed())
            self.timeline.run()
            self.in_sliding = True

            self.show_all()
Пример #57
0
    def __init__(self, multitrack=True, video=None, modality=None):

        super(Annotation, self).__init__()

        # whether a segment can contain multiple track (True) or not (False)
        self.__multitrack = multitrack

        # name of annotated modality
        self.__modality = modality

        # path to (or any identifier of) segmented video
        self.__video = video

        # this timeline is meant to store annotated segments.
        # it only contains segments with at least one labelled track.
        # a segment that is no longer annotated must be removed from it.
        self.__timeline = Timeline(video=self.video)

        # this is where tracks and labels are actually stored.
        # it is a dictionary indexed by segments.
        # .__data[segment] is a dictionary indexed by tracks.
        # .__data[segment][track] contains the actual label.
        self.__data = {}

        # this is a dictionary indexed by labels.
        # .__label_timeline[label] is a timeline made of segments for which
        # there exists at least one track labelled by label.
        # when a label no longer exists, its entry must be removed.
        self.__label_timeline = {}

        # this is a dictionary indexed by labels
        # .__label_count[label] is a dictionary indexed by segments containing
        # at least one track labelled by label.
        # .__label_count[label][segment] contains the number of tracks labelled
        # as label in this segment. when zero, segment entry must be removed.
        self.__label_count = {}
Пример #58
0
    def __init__(self, app=None, token=None, refresh_token=None, tokens=None):

        if tokens:
            token = tokens["access_token"]
            refresh_token = tokens["refresh_token"]

        self.app = app
        self.token = token
        self.refresh_token = refresh_token
        
        self.session = self.app.oauth.get_session(token=self.token)
        self.session.headers.update({'Content-Type': 'application/json'})

        self.timeline = Timeline(self)
        self.contacts = Contacts(self)
Пример #59
0
    def start_animation(self, animation_time, index=None):
        # Update ticker with active index if option index is None.
        if index == None:
            if self.active_index >= self.image_number - 1:
                index = 0
            else:
                index = self.active_index + 1

        if not self.in_animiation:
            self.in_animiation = True
            self.target_index = index

            timeline = Timeline(animation_time, CURVE_SINE)
            timeline.connect("update", self.update_animation)
            timeline.connect("completed", lambda source: self.completed_animation(source, index))
            timeline.run()

        return True