Search Results

Search found 1354 results on 55 pages for 'duration'.

Page 9/55 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Whether to use UNION or OR in SQL Server Queries

    - by Dinesh Asanka
    Recently I came across with an article on DB2 about using Union instead of OR. So I thought of carrying out a research on SQL Server on what scenarios UNION is optimal in and which scenarios OR would be best. I will analyze this with a few scenarios using samples taken  from the AdventureWorks database Sales.SalesOrderDetail table. Scenario 1: Selecting all columns So we are going to select all columns and you have a non-clustered index on the ProductID column. --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR ProductID =709 OR ProductID =998 OR ProductID =875 OR ProductID =976 OR ProductID =874 --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 709 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 998 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 875 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 976 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 874 So query 1 is using OR and the later is using UNION. Let us analyze the execution plans for these queries. Query 1 Query 2 As expected Query 1 will use Clustered Index Scan but Query 2, uses all sorts of things. In this case, since it is using multiple CPUs you might have CX_PACKET waits as well. Let’s look at the profiler results for these two queries: CPU Reads Duration Row Counts OR 78 1252 389 3854 UNION 250 7495 660 3854 You can see from the above table the UNION query is not performing well as the  OR query though both are retuning same no of rows (3854).These results indicate that, for the above scenario UNION should be used. Scenario 2: Non-Clustered and Clustered Index Columns only --Query 1 : OR SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR ProductID =709 OR ProductID =998 OR ProductID =875 OR ProductID =976 OR ProductID =874 GO --Query 2 : UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 709 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 998 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 875 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 976 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 874 GO So this time, we will be selecting only index columns, which means these queries will avoid a data page lookup. As in the previous case we will analyze the execution plans: Query 1 Query 2 Again, Query 2 is more complex than Query 1. Let us look at the profile analysis: CPU Reads Duration Row Counts OR 0 24 208 3854 UNION 0 38 193 3854 In this analyzis, there is only slight difference between OR and UNION. Scenario 3: Selecting all columns for different fields Up to now, we were using only one column (ProductID) in the where clause.  What if we have two columns for where clauses and let us assume both are covered by non-clustered indexes? --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR CarrierTrackingNumber LIKE 'D0B8%' --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE CarrierTrackingNumber  LIKE 'D0B8%' Query 1 Query 2: As we can see, the query plan for the second query has improved. Let us see the profiler results. CPU Reads Duration Row Counts OR 47 1278 443 1228 UNION 31 1334 400 1228 So in this case too, there is little difference between OR and UNION. Scenario 4: Selecting Clustered index columns for different fields Now let us go only with clustered indexes: --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR CarrierTrackingNumber LIKE 'D0B8%' --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE CarrierTrackingNumber  LIKE 'D0B8%' Query 1 Query 2 Now both execution plans are almost identical except is an additional Stream Aggregate is used in the first query. This means UNION has advantage over OR in this scenario. Let us see profiler results for these queries again. CPU Reads Duration Row Counts OR 0 319 366 1228 UNION 0 50 193 1228 Now see the differences, in this scenario UNION has somewhat of an advantage over OR. Conclusion Using UNION or OR depends on the scenario you are faced with. So you need to do your analyzing before selecting the appropriate method. Also, above the four scenarios are not all an exhaustive list of scenarios, I selected those for the broad description purposes only.

    Read the article

  • FFmpeg extract clip - stream frame rate differs from container frame rate (x264, aac)

    - by fideli
    Summary H.264 video seems to have a really high frame rate that requires a scaling factor to the applied to the duration of video that I'm trying to extract (900x lower). Body I'm trying to extract a clip from a movie that I have in MP4 format (created using Handbrake). After trying mencoder and VLC, I decided to give FFmpeg a shot since it was the least troublesome when it came to copying the codecs. That is, compared to mencoder and VLC, the resulting file was still playable in QuickTime (I know about Perian, etc, I'm just trying to learn how all this works). Anyway, my command was as follows: ffmpeg -ss 01:15:51 -t 00:05:59 -i outofsight.mp4 \ -acodec copy -vcodec copy clip.mp4 During the copy, The following comes up: Seems stream 0 codec frame rate differs from container frame rate: 45000.00 (45000/1) -> 25.00 (25/1) Input #0, mov,mp4,m4a,3gp,3g2,mj2, from outofsight.mp4': Duration: 01:57:42.10, start: 0.000000, bitrate: 830 kb/s Stream #0.0(und): Video: h264, yuv420p, 720x384, 25 tbr, 22500 tbn, 45k tbc Stream #0.1(eng): Audio: aac, 48000 Hz, stereo, s16 Output #0, mp4, to 'out.mp4': Stream #0.0(und): Video: libx264, yuv420p, 720x384, q=2-31, 90k tbn, 22500 tbc Stream #0.1(eng): Audio: libfaac, 48000 Hz, stereo, s16 Stream mapping: Stream #0.0 -> #0.0 Stream #0.1 -> #0.1 Press [q] to stop encoding frame= 2591 fps=2349 q=-1.0 size= 8144kB time=101.60 bitrate= 656.7kbits/s … Instead of a 5:59 duration clip, I get the entire rest of the movie. So, to test this, I ran the ffmpeg command with -t 00:00:01. What I got was exactly a 15:00 minute clip. So I did some black box engineering and decided to scale my -t option by calculating what value to enter given that 1 second was interpreted as 900 s. For my desired 359 s clip, I calculated 0.399 s and so my ffmpeg command became: ffmpeg -ss 01:15.51 -t 00:00:00.399 -i outofsight.mp4 \ -acodec copy -vcodec copy clip.mp4 This works, but I have no idea why the duration is scaled by 900. Investigating further, each ffmpeg run has the line: Seems stream 0 codec frame rate differs from container frame rate: 45000.00 (45000/1) -> 25.00 (25/1) 45000/25 = 1800. Must be a relation somewhere. Somehow, the obscenely high frame rate is causing issues with the timing. How is that frame rate so high? The best part about this is that the resulting clip.mp4 has the exact same feature (due to the copied video codec), and taking further clips from this needs the same scaling for the -t duration option. Therefore, I've made it available for anyone willing to check this out. Appendix The preamble for ffmpeg on my system (built using MacPorts ffmpeg port): FFmpeg version 0.5, Copyright (c) 2000-2009 Fabrice Bellard, et al. configuration: --prefix=/opt/local --disable-vhook --enable-gpl --enable-postproc --enable-swscale --enable-avfilter --enable-avfilter-lavf --enable-libmp3lame --enable-libvorbis --enable-libtheora --enable-libdirac --enable-libschroedinger --enable-libfaac --enable-libfaad --enable-libxvid --enable-libx264 --mandir=/opt/local/share/man --enable-shared --enable-pthreads --cc=/usr/bin/gcc-4.2 --arch=x86_64 libavutil 49.15. 0 / 49.15. 0 libavcodec 52.20. 0 / 52.20. 0 libavformat 52.31. 0 / 52.31. 0 libavdevice 52. 1. 0 / 52. 1. 0 libavfilter 1. 4. 0 / 1. 4. 0 libswscale 1. 7. 1 / 1. 7. 1 libpostproc 51. 2. 0 / 51. 2. 0 built on Jan 4 2010 21:51:51, gcc: 4.2.1 (Apple Inc. build 5646) (dot 1)

    Read the article

  • FFmpeg extract clip - stream frame rate differs from container frame rate (x264, aac)

    - by fideli
    Summary H.264 video seems to have a really high frame rate that requires a scaling factor to the applied to the duration of video that I'm trying to extract (900x lower). Body I'm trying to extract a clip from a movie that I have in MP4 format (created using Handbrake). After trying mencoder and VLC, I decided to give FFmpeg a shot since it was the least troublesome when it came to copying the codecs. That is, compared to mencoder and VLC, the resulting file was still playable in QuickTime (I know about Perian, etc, I'm just trying to learn how all this works). Anyway, my command was as follows: ffmpeg -ss 01:15:51 -t 00:05:59 -i outofsight.mp4 \ -acodec copy -vcodec copy clip.mp4 During the copy, The following comes up: Seems stream 0 codec frame rate differs from container frame rate: 45000.00 (45000/1) -> 25.00 (25/1) Input #0, mov,mp4,m4a,3gp,3g2,mj2, from outofsight.mp4': Duration: 01:57:42.10, start: 0.000000, bitrate: 830 kb/s Stream #0.0(und): Video: h264, yuv420p, 720x384, 25 tbr, 22500 tbn, 45k tbc Stream #0.1(eng): Audio: aac, 48000 Hz, stereo, s16 Output #0, mp4, to 'out.mp4': Stream #0.0(und): Video: libx264, yuv420p, 720x384, q=2-31, 90k tbn, 22500 tbc Stream #0.1(eng): Audio: libfaac, 48000 Hz, stereo, s16 Stream mapping: Stream #0.0 -> #0.0 Stream #0.1 -> #0.1 Press [q] to stop encoding frame= 2591 fps=2349 q=-1.0 size= 8144kB time=101.60 bitrate= 656.7kbits/s … Instead of a 5:59 duration clip, I get the entire rest of the movie. So, to test this, I ran the ffmpeg command with -t 00:00:01. What I got was exactly a 15:00 minute clip. So I did some black box engineering and decided to scale my -t option by calculating what value to enter given that 1 second was interpreted as 900 s. For my desired 359 s clip, I calculated 0.399 s and so my ffmpeg command became: ffmpeg -ss 01:15.51 -t 00:00:00.399 -i outofsight.mp4 \ -acodec copy -vcodec copy clip.mp4 This works, but I have no idea why the duration is scaled by 900. Investigating further, each ffmpeg run has the line: Seems stream 0 codec frame rate differs from container frame rate: 45000.00 (45000/1) -> 25.00 (25/1) 45000/25 = 1800. Must be a relation somewhere. Somehow, the obscenely high frame rate is causing issues with the timing. How is that frame rate so high? The best part about this is that the resulting clip.mp4 has the exact same feature (due to the copied video codec), and taking further clips from this needs the same scaling for the -t duration option. Therefore, I've made it available for anyone willing to check this out. Appendix The preamble for ffmpeg on my system (built using MacPorts ffmpeg port): FFmpeg version 0.5, Copyright (c) 2000-2009 Fabrice Bellard, et al. configuration: --prefix=/opt/local --disable-vhook --enable-gpl --enable-postproc --enable-swscale --enable-avfilter --enable-avfilter-lavf --enable-libmp3lame --enable-libvorbis --enable-libtheora --enable-libdirac --enable-libschroedinger --enable-libfaac --enable-libfaad --enable-libxvid --enable-libx264 --mandir=/opt/local/share/man --enable-shared --enable-pthreads --cc=/usr/bin/gcc-4.2 --arch=x86_64 libavutil 49.15. 0 / 49.15. 0 libavcodec 52.20. 0 / 52.20. 0 libavformat 52.31. 0 / 52.31. 0 libavdevice 52. 1. 0 / 52. 1. 0 libavfilter 1. 4. 0 / 1. 4. 0 libswscale 1. 7. 1 / 1. 7. 1 libpostproc 51. 2. 0 / 51. 2. 0 built on Jan 4 2010 21:51:51, gcc: 4.2.1 (Apple Inc. build 5646) (dot 1) EDIT Not sure whether it was a bug or not, but it seems to be fixed now in my current version of ffmpeg, at least for this video (version 0.6.1 from MacPorts).

    Read the article

  • iphone cannot rotate views in TabBar controller

    - by Luc
    Hello, I am working on an application that consists of a TabBar controller. Within on of its tab, I have a subclass of UITableViewController, within this list I have a Core-plot graph in the first cell and some other data in the 4 following cells. When I return YES in the shouldAutorotateToInterfaceOrientation method, I would expect the autoresizing of the list view to happen, but... nothing. When I add some log in the willRotateToInterfaceOrientation method, they are not displayed. Is there something I missed ? Thanks a lot, Luc // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations //return (interfaceOrientation == UIInterfaceOrientationPortrait); NSLog(@"Orientation"); return YES; } - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; NSLog(@"Rotating"); if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { NSLog(@"view land:%@", self.view); } if (toInterfaceOrientation == UIInterfaceOrientationPortrait) { NSLog(@"view portrait:%@", self.view); } }

    Read the article

  • jQuery .animate() not animating backgroundPosition in IE

    - by mikemike
    I'm trying to animate a background image to move down a set amount of pixels but remain in the center of the page. Upon another click of an element I need it to move back to the top, but still remain in the center. Below is the current code: $(document).ready(function() { $('#email_campaigns').click(function(){ var width = $(window).width(); width = (width / 2) - 700; if($('#email_campaigns_box').css('display') == 'none'){ //$('body').css('background-position','center 119px'); $('body').animate({ backgroundPosition: (width + "px 119px") }, {duration:500}); } else { //$('body').css('background-position','center top'); $('body').animate({ backgroundPosition: (width + "px 0px") }, {duration:500}); } $('#email_campaigns_box').slideToggle("slow"); $('#client_login_box').slideUp("slow"); }); $('#client_login').click(function(){ var width = $(window).width(); width = (width / 2) - 700; alert(width); if($('#client_login_box').css('display') == 'none'){ //$('body').css('background-position','center 119px'); $('body').animate({ backgroundPosition: (width + "px 119px") }, {duration:500}); } else { //$('body').css('background-position','center top'); $('body').animate({ backgroundPosition: (width + "px 0px") }, {duration:500}); } $('#client_login_box').slideToggle("slow"); $('#email_campaigns_box').slideUp("slow"); }); }); I cannot pass 'center', as it will onyl accept numeric values. My goal is to calulate the center of the page in pixels (width = (width / 2) - 700;), and then animate to this rough position (it's normally out by a few pixels due to scrollbars, and then force to the center using a .css() call. The problem is that IE does not want to play ball. IE will not animate at all. Firefox/Safari/Chrome all work as expected. Below is a live example: http://recklessnewmedia.com/new/# (click 'email campaigns' at the top). Thanks

    Read the article

  • How can I handle events within my custom control?

    - by highone
    I am not looking to create new events. I need to create a canvas control that optionally fades in or out depending on whether or not the mouse is over it. The code below probably explains what I want to do better than I can. private Storyboard fadeInStoryboard; private Storyboard fadeOutStoryboard; public FadingOptionPanel() { InitializeComponent(); } public static readonly DependencyProperty FadeEnabledProperty = DependencyProperty.Register("IsFadeEnabled", typeof(bool), typeof(FadingOptionPanel), new FrameworkPropertyMetadata(true, OnFadeEnabledPropertyChanged, OnCoerceFadeEnabledProperty)); public bool IsFadeEnabled { get { return (bool)GetValue(FadeEnabledProperty); } set { SetValue(FadeEnabledProperty, value); } } private static void OnFadeEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { } private static object OnCoerceFadeEnabledProperty(DependencyObject sender, object data) { if (data.GetType() != typeof(bool)) { data = true; } return data; } private void FadingOptionPanel_MouseEnter(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeInStoryboard.Begin(this); } } private void FadingOptionPanel_MouseLeave(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeOutStoryboard.Begin(this); } } private void FadingOptionsPanel_Loaded(object sender, RoutedEventArgs e) { //Initialize Fade In Animation DoubleAnimation fadeInDoubleAnimation = new DoubleAnimation(); fadeInDoubleAnimation.From = 0; fadeInDoubleAnimation.To = 1; fadeInDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.5)); fadeInStoryboard = new Storyboard(); fadeInStoryboard.Children.Add(fadeInDoubleAnimation); Storyboard.SetTargetName(fadeInDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeInDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); //Initialize Fade Out Animation DoubleAnimation fadeOutDoubleAnimation = new DoubleAnimation(); fadeOutDoubleAnimation.From = 1; fadeOutDoubleAnimation.To = 0; fadeOutDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.2)); fadeOutStoryboard = new Storyboard(); fadeOutStoryboard.Children.Add(fadeOutDoubleAnimation); Storyboard.SetTargetName(fadeOutDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeOutDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); } I originally was using this code inside a usercontrol instead of a custom control before I found out that usercontrols don't support content.

    Read the article

  • DBD::SQLite::st execute failed: datatype mismatch

    - by Barton Chittenden
    Here's a snippit of perl code: sub insert_timesheet { my $dbh = shift; my $entryref = shift; my $insertme = join(',', @_); my $values_template = '?, ' x scalar(@_); chop $values_template; chop $values_template; #remove trailing comma my $insert = "INSERT INTO timesheet( $insertme ) VALUES ( $values_template );"; my $sth = $dbh->prepare($insert); debug("$insert"); my @values; foreach my $entry (@_){ push @values, $$entryref{$entry} } debug("@values"); my $rv = $sth->execute( @values ) or die $dbh->errstr; debug("sql return value: $rv"); $dbh->disconnect; } The value of $insert: [INSERT INTO timesheet( idx,Start_Time,End_Time,Project,Ticket_Number,Site,Duration,Notes ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );] Here are @values: [null '1270950742' '1270951642' 'asdf' 'asdf' 'adsf' 15 ''] Here's the schema of 'timesheet' timesheet( idx INTEGER PRIMARY KEY AUTOINCREMENT, Start_Time VARCHAR, End_Time VARCHAR, Duration INTEGER, Project VARCHAR, Ticket_Number VARCHAR, Site VARCHAR, Notes VARCHAR) Here's how things line up: ---- Insert Statement Schema @values ---- idx idx INTEGER PRIMARY KEY AUTOINCREMENT null: # this is not a mismatch, passing null will allow auto-increment. Start_Time Start_Time VARCHAR '1270950742' End_Time End_Time VARCHAR '1270951642' Project Project VARCHAR 'asdf' Ticket_Number Ticket_Number VARCHAR 'asdf' Site Site VARCHAR 'adsf' Duration Duration INTEGER 15 Notes Notes VARCHAR '' ... I can't see the data-type mis-match.

    Read the article

  • How do I animate UserControl objects using Storyboard and DoubleAnimation?

    - by Neo
    In my WPF application, I have a Canvas object that contains some UserControl objects. I wish to animate the UserControl objects within the Canvas using DoubleAnimation so that they go from the right of the Canvas to the left of the Canvas. This is how I have done it so far (by passing the UserControl objects into the function): private void Animate(FrameworkElement e) { DoubleAnimation ani = new DoubleAnimation() { From = _container.ActualWidth, To = 0.0, Duration = new Duration(new TimeSpan(0, 0, 10), TargetElement = e }; TranslateTransform trans = new TranslateTransform(); e.RenderTransform = trans; trans.BeginAnimation(TranslateTransform.XProperty, ani, HandoffBehavior.Compose); } However, this doesn't allow me to pause the animation, so I have considered using a Storyboard instead to do this, but I'm not sure how to implement this. This has been my attempt so far: private void Animate(FrameworkElement e) { DoubleAnimation ani = new DoubleAnimation() { From = _container.ActualWidth, To = 0.0, Duration = new Duration(new TimeSpan(0, 0, 10), TargetElement = e }; Storyboard stb = new Storyboard(); Storyboard.SetTarget(ani, e); Storyboard.SetTargetProperty(ani, "Left"); stb.Children.Add(ani); stb.Begin(); } Of course, this fails as UserControl doesn't have a Left property. How can I achieve what I'm after? Thanks.

    Read the article

  • Scheduling of tasks to a single resource using Prolog

    - by Reed Debaets
    I searched through here as best I could and though I found some relevant questions, I don't think they covered the question at hand: Assume a single resource and a known list of requests to schedule a task. Each request includes a start_after, start_by, expected_duration, and action. The goal is to schedule the tasks for execution as soon as possible while keeping each task scheduled between start_after and start_by. I coded up a simple prolog example that I "thought" should work but I've been unfortunately getting errors during run time: "=/2: Arguments are not sufficiently instantiated". Any help or advice would be greatly appreciated startAfter(1,0). startAfter(2,0). startAfter(3,0). startBy(1,100). startBy(2,500). startBy(3,300). duration(1,199). duration(2,199). duration(3,199). action(1,'noop1'). action(2,'noop2'). action(3,'noop3'). can_run(R,T) :- startAfter(R,TA),startBy(R,TB),T>=TA,T=<TB. conflicts(T,R1,T1) :- duration(R1,D1),T=<D1+T1,T>T1. schedule(R1,T1,R2,T2,R3,T3) :- can_run(R1,T1),\+conflicts(T1,R2,T2),\+conflicts(T1,R3,T3), can_run(R2,T2),\+conflicts(T2,R1,T1),\+conflicts(T2,R3,T3), can_run(R3,T3),\+conflicts(T3,R1,T1),\+conflicts(T3,R2,T2). % when traced I *should* see T1=0, T2=400, T3=200 Edit: conflicts goal wasn't quite right: needed extra TT1 clause. Edit: Apparently my schedule goal works if I supply valid Request,Time pairs ... but I'm stucking trying to force prolog to find valid values for T1..3 when given R1..3?

    Read the article

  • JavaScript: Achieving precise animation end values?

    - by bobthabuilda
    I'm currently trying to write my own JavaScript library. I'm in the middle of writing an animation callback, but I'm having trouble getting precise end values, especially when animation duration times are smaller. Right now, I'm only targeting positional animation (left, top, right, bottom). When my animations complete, they end up having an error margin of 5px~ on faster animations, and 0.5px~ on animations 1000+ ms or greater. Here's the bulk of the callback, with notes following. var current = parseFloat( this[0].style[prop] || 0 ) // If our target value is greater than the current , gt = !!( value > current ) , delta = ( Math.abs(current - value) / (duration / 13) ) * (gt ? 1 : -1) , elem = this[0] , anim = setInterval( function(){ elem.style[prop] = ( current + delta ) + 'px'; current = parseFloat( elem.style[prop] ); if ( gt && current >= value || !gt && current <= value ) clearInterval( anim ); }, 13 ); this[0] and elem both reference the target DOM element. prop references the property to animate, left, top, bottom, right, etc. current is the current value of the DOM element's property. value is the desired value to animate to. duration is the specified duration (in ms) that the animation should last. 13 is the setInterval delay (which should roughly be the absolute minimal for all browsers). gt is a var that is true if value exceeds the initial current, else it is false. How can I resolve the error margin?

    Read the article

  • How to access Youtube_it ruby query results?

    - by spectro
    I am trying to implement the youtube_it youtube api wrapper for ruby and have it working except I'm stumped as to how the query results should be accessed. Here is my query: client.videos_by(:query => "penguin", :max_results => 1) Submitting request [url=http://gdata.youtube.com/feeds/api/videos?max-results=1&start-index=1&vq=penguin]. => #<YouTubeIt::Response::VideoSearch:0xb6c41b14 @feed_id="http://gdata.youtube.com/feeds/api/videos", @updated_at=Wed Nov 03 18:01:39 UTC 2010, @videos=[#<YouTubeIt::Model::Video:0xb6c424d8 @thumbnails=[#<YouTubeIt::Model::Thumbnail:0xb6c6b694 @url="http://i.ytimg.com/vi/oSbLpQEZP1Y/2.jpg", @width=120, @height=90, @time="00:01:34">, #<YouTubeIt::Model::Thumbnail:0xb6c6b248 @url="http://i.ytimg.com/vi/oSbLpQEZP1Y/1.jpg", @width=120, @height=90, @time="00:00:47">, #<YouTubeIt::Model::Thumbnail:0xb6c6a988 @url="http://i.ytimg.com/vi/oSbLpQEZP1Y/3.jpg", @width=120, @height=90, @time="00:02:21">, #<YouTubeIt::Model::Thumbnail:0xb6c69e34 @url="http://i.ytimg.com/vi/oSbLpQEZP1Y/0.jpg", @width=320, @height=240, @time="00:01:34">], @categories=[#<YouTubeIt::Model::Category:0xb6ca5d6c @term="Music", @label="Music">], @noembed=false, @racy=false, @favorite_count=7862, @duration=188, @author=#<YouTubeIt::Model::Author:0xb6c9942c @name="wili", @uri="http://gdata.youtube.com/feeds/api/users/wili">, @updated_at=Tue Nov 02 08:45:25 UTC 2010, @longitude=nil, @position=nil, @view_count=1682350, @html_content="penguin", @media_content=[#<YouTubeIt::Model::Content:0xb6c770d4 @url="http://www.youtube.com/v/oSbLpQEZP1Y?f=videos&app=youtube_gdata", @duration=188, @format=#<YouTubeIt::Model::Video::Format:0xb656d108 @name=:swf, @format_code=5>, @default=true, @mime_type="application/x-shockwave-flash">, #<YouTubeIt::Model::Content:0xb6c766d4 @url="rtsp://v5.cache3.c.youtube.com/CiILENy73wIaGQlWPxkBpcsmoRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp", @duration=188, @format=#<YouTubeIt::Model::Video::Format:0xb656d11c @name=:rtsp, @format_code=1>, @default=false, @mime_type="video/3gpp">, #<YouTubeIt::Model::Content:0xb6c75d38 @url="rtsp://v8.cache3.c.youtube.com/CiILENy73wIaGQlWPxkBpcsmoRMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp", @duration=188, @format=#<YouTubeIt::Model::Video::Format:0xb656d0f4 @name=:three_gpp, @format_code=6>, @default=false, @mime_type="video/3gpp">], @description="penguin", @latitude=nil, @title="penguin", @published_at=Mon May 08 18:11:01 UTC 2006, @player_url="http://www.youtube.com/watch?v=oSbLpQEZP1Y&feature=youtube_gdata_player", @rating=#<YouTubeIt::Model::Rating:0xb6c5eb4c @min=1, @max=5, @average=4.676985, @rater_count=2746>, @keywords=["pigloo", "penguin"], @video_id="http://gdata.youtube.com/feeds/api/videos/oSbLpQEZP1Y", @where=nil>], @total_result_count=291282, @offset=1, @max_result_count=1> I would like to retrieve the URL and thumbnail links. Any ideas?

    Read the article

  • jquery - problem with executing annimation of two separate objects, one after another

    - by MoreThanChaos
    Hello I have problem to put together animations of two separate objects to second one start when first one ends. I tried to use callback but it seems that i make some syntax misteakes which crash jQuery or cause some unexpected behaviour. It seems that i'm stuck so I'd like to ask You for best way to put these animations together to act the way I want. in mouseenter 1st .pp grows, 2nd .tt fade in in mouseleave 1st .tt fade out, 2nd .pp shrink It's alsp relevant that animations doesn't pile up, i mean here animation called by one event doesnt wait until other animation in progress will end. In generall exactly what is below but yo be animated one after another, not simultanously. $('.pp').bind({ mouseenter: function() { $(this).animate({ width: $(this).children(".tt").outerWidth(), height: $(this).children(".tt").outerHeight() },{duration:1000,queue:false} ); $(this).children(".tt").animate({ opacity: 1.0 }, {duration:1000,queue:false}); }, mouseleave: function() { $(this).children(".tt").animate({ opacity: 0 }, {duration:1000,queue:false}); $(this).animate({ width: 17, height: 17 }, {duration:1000,queue:false}); } });

    Read the article

  • Android: How to change my ExpandAnimation class to handle animation correctly?

    - by IamStalker
    here is my animation class that i have taken from Udnic - thanks m8, but i'm using it "not from closed position but from opened" and it's jumps and not behaving correctly. what should i do? public class ExpandAnimation extends Animation { private View mAnimatedView; private LinearLayout.LayoutParams mViewLayoutParams; public int mMarginStart, mMarginEnd; private boolean mIsVisibleAfter = false; private boolean mWasEndedAlready = false; private ImageView mImageView; /** * Initialize the animation * @param view The layout we want to animate * @param duration The duration of the animation, in ms */ public ExpandAnimation(View view, int duration, ImageView imageView) { setDuration(duration); mImageView = imageView; mAnimatedView = view; mViewLayoutParams = (LinearLayout.LayoutParams) view.getLayoutParams(); mMarginStart = mMarginEnd = 0; // decide to show or hide the view mIsVisibleAfter = (view.getVisibility() == View.VISIBLE); //mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0); mMarginStart = mViewLayoutParams.bottomMargin; if(mMarginStart != 0) mMarginStart = 0 - view.getHeight(); mMarginEnd = (mMarginStart == 0 ? (0 - view.getHeight()) : 0); view.setVisibility(View.VISIBLE); mImageView.setImageResource(R.drawable.expand_open); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime < 1.0f) { // Calculating the new bottom margin, and setting it mViewLayoutParams.bottomMargin = mMarginStart + (int) ((mMarginEnd - mMarginStart) * interpolatedTime); // Invalidating the layout, making us seeing the changes we made mAnimatedView.requestLayout(); // Making sure we didn't run the ending before (it happens!) } else if (!mWasEndedAlready) { mViewLayoutParams.bottomMargin = mMarginEnd; mAnimatedView.requestLayout(); // if (mIsVisibleAfter) { if(mMarginEnd != 0) { mAnimatedView.setVisibility(View.GONE); mImageView.setImageResource(R.drawable.expand_close); } mWasEndedAlready = true; } } }

    Read the article

  • How to find nearest week day for an arbitrary date?

    - by Stig Brautaset
    Is there a more elegant way than the below to find the nearest day of the week for a given date using JodaTime? I initially thought setCopy() would be it, but this sets the day to the particular day in the same week. Thus, if ld is 2011-11-27 and day is "Monday" the following function returns 2011-11-21, and not 2011-11-28 as I want. // Note that "day" can be _any_ day of the week, not just weekdays. LocalDate getNearestDayOfWeek(LocalDate ld, String day) { return ld.dayOfWeek().setCopy(day); } Below is a work-around I came up with that works for the particular constraints in my current situation, but I'd love to get help find a completely generic solution that works always. LocalDate getNearestDayOfWeek(LocalDate ld, String day) { LocalDate target = ld.dayOfWeek().setCopy(day); if (ld.getDayOfWeek() > DateTimeConstants.SATURDAY) { target = target.plusWeeks(1); } return target; } Looking more into this I came up with this, which seems to be a more correct solution, though it seems awfully complicated: LocalDate getNearestDayOfWeek(LocalDate ld, String day) { LocalDate target = ld.dayOfWeek().setCopy(day); if (target.isBefore(ld)) { LocalDate nextTarget = target.plusWeeks(1); Duration sincePrevious = new Duration(target.toDateMidnight(), ld.toDateMidnight()); Duration untilNext = new Duration(ld.toDateMidnight(), nextTarget.toDateMidnight()); if (sincePrevious.isLongerThan(untilNext)) { target = nextTarget; } } return target; }

    Read the article

  • WPF Animate and change Opacity of Image in sequence

    - by user1103757
    I have three images, two of these images animate as follow and third image should blink: <Window.Resources> <Storyboard x:Key="AnimateTarget" RepeatBehavior="Forever"> <DoubleAnimationUsingKeyFrames BeginTime="0:0:0" Duration="0:00:03" Storyboard.TargetName="img1" Storyboard.TargetProperty="Y"> <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0" /> <EasingDoubleKeyFrame KeyTime="0:0:1" Value="200" /> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="0:0:2" Duration="0:00:03" Storyboard.TargetName="img2" Storyboard.TargetProperty="x"> <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0" /> <EasingDoubleKeyFrame KeyTime="0:0:1" Value="200" /> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0" /> </DoubleAnimationUsingKeyFrames> <DoubleAnimation BeginTime="0:0:4" Duration="0:0:0.5" Storyboard.TargetProperty="(Image.Opacity)" Storyboard.TargetName="img3" From="1.0" To="0.0" RepeatBehavior="Forever" AutoReverse="True" /> </Storyboard> </Window.Resources> The first two images are animating fine but the third image doesn’t blink, it will do nothing and just stay there as you can see I have used the following code for blinking the third image: <DoubleAnimation BeginTime="0:0:4" Duration="0:0:0.5" Storyboard.TargetProperty="(Image.Opacity)" Storyboard.TargetName="img3" From="1.0" To="0.0" RepeatBehavior="Forever" AutoReverse="True" /> Also this is a code for the third image: <Image Height="65" Name="image1" Stretch="Fill" Width="67" Source="/PicTakeWPF;component/Images/422505_110594629067212_100003500265268_37406_1212153553_n.jpg"> <Image.RenderTransform> <TranslateTransform x:Name="img3"></TranslateTransform> </Image.RenderTransform> </Image> I would appreciate if someone helps me on this Thanks,

    Read the article

  • image transistion

    - by Jeff Main
    Hi all. I've gotten stuck again. I've got an image (album cover) that I'll be changing in code behind, and wish to basicaly do the following. When a new album cover image is determine and aquired, I want the current image in the image control to fade out, get updated with the new cover, and then fade back in. I'm not seeing very many good examples on how to accomplish this in code behind. The following was my latest failed attempt... if (currentTrack != previousTrack) { BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; image.UriSource = new Uri(Address, UriKind.Absolute); image.EndInit(); Storyboard MyStoryboard = new Storyboard(); DoubleAnimation FadeOut = new DoubleAnimation(); FadeOut.From = 1.0; FadeOut.To = 0.0; FadeOut.Duration = new Duration(TimeSpan.FromSeconds(.5)); MyStoryboard.Children.Add(FadeOut); Storyboard.SetTargetName(FadeOut, CoverArt.Name); Storyboard.SetTargetProperty(FadeOut, new PropertyPath(Rectangle.OpacityProperty)); CoverArt.Source = image; DoubleAnimation Fadein = new DoubleAnimation(); Fadein.From = 0.0; Fadein.To = 1.0; Fadein.Duration = new Duration(TimeSpan.FromSeconds(.5)); MyStoryboard.Children.Add(Fadein); Storyboard.SetTargetName(Fadein, CoverArt.Name); Storyboard.SetTargetProperty(Fadein, new PropertyPath(Rectangle.OpacityProperty)); MyStoryboard.Begin(this); } I'd prefer to do this in code behind simply because that is where I'm aquiring the image. Otherwise, I'm not sure how I'd trigger it. An example would be greatly appriciated. Thanks.

    Read the article

  • WPF animation: binding to the "To" attribute of storyboard animation.

    - by bozalina
    Hi, I'm trying to create a button that behaves similarly to the "slide" button on the iPhone. I have an animation that adjusts the position and width of the button, but I want these values to be based on the text used in the control. Currently, they're hardcoded. Here's my working XAML, so far: <CheckBox x:Class="Smt.Controls.SlideCheckBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Smt.Controls" xmlns:System.Windows="clr-namespace:System.Windows;assembly=PresentationCore" Name="SliderCheckBox" mc:Ignorable="d"> <CheckBox.Resources> <System.Windows:Duration x:Key="AnimationTime">0:0:0.2</System.Windows:Duration> <Storyboard x:Key="OnChecking"> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)" Duration="{StaticResource AnimationTime}" To="40" /> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="41" /> </Storyboard> <Storyboard x:Key="OnUnchecking"> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)" Duration="{StaticResource AnimationTime}" To="0" /> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="40" /> </Storyboard> <Style x:Key="SlideCheckBoxStyle" TargetType="{x:Type local:SlideCheckBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:SlideCheckBox}"> <Canvas> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" RecognizesAccessKey="True" VerticalAlignment="Center" HorizontalAlignment="Center" /> <Canvas> <!--Background--> <Rectangle Width="{Binding ElementName=ButtonText, Path=ActualWidth}" Height="{Binding ElementName=ButtonText, Path=ActualHeight}" Fill="LightBlue" /> </Canvas> <Canvas> <!--Button--> <Button Width="{Binding ElementName=CheckedText, Path=ActualWidth}" Height="{Binding ElementName=ButtonText, Path=ActualHeight}" Name="CheckButton" Command="{x:Static local:SlideCheckBox.SlideCheckBoxClicked}"> <Button.RenderTransform> <TransformGroup> <TranslateTransform /> </TransformGroup> </Button.RenderTransform> </Button> </Canvas> <Canvas> <!--Text--> <StackPanel Name="ButtonText" Orientation="Horizontal" IsHitTestVisible="False"> <Grid Name="CheckedText"> <Label Margin="7 0" Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:SlideCheckBox}}, Path=CheckedText}" /> </Grid> <Grid Name="UncheckedText" HorizontalAlignment="Right"> <Label Margin="7 0" Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:SlideCheckBox}}, Path=UncheckedText}" /> </Grid> </StackPanel> </Canvas> </Canvas> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource OnChecking}" /> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource OnUnchecking}" /> </Trigger.ExitActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </CheckBox.Resources> <CheckBox.CommandBindings> <CommandBinding Command="{x:Static local:SlideCheckBox.SlideCheckBoxClicked}" Executed="OnSlideCheckBoxClicked" /> </CheckBox.CommandBindings> </CheckBox> And the code behind: using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Smt.Controls { public partial class SlideCheckBox : CheckBox { public SlideCheckBox() { InitializeComponent(); Loaded += OnLoaded; } public static readonly DependencyProperty CheckedTextProperty = DependencyProperty.Register("CheckedText", typeof(string), typeof(SlideCheckBox), new PropertyMetadata("Checked Text")); public string CheckedText { get { return (string)GetValue(CheckedTextProperty); } set { SetValue(CheckedTextProperty, value); } } public static readonly DependencyProperty UncheckedTextProperty = DependencyProperty.Register("UncheckedText", typeof(string), typeof(SlideCheckBox), new PropertyMetadata("Unchecked Text")); public string UncheckedText { get { return (string)GetValue(UncheckedTextProperty); } set { SetValue(UncheckedTextProperty, value); } } public static readonly RoutedCommand SlideCheckBoxClicked = new RoutedCommand(); void OnLoaded(object sender, RoutedEventArgs e) { Style style = TryFindResource("SlideCheckBoxStyle") as Style; if (!ReferenceEquals(style, null)) { Style = style; } } void OnSlideCheckBoxClicked(object sender, ExecutedRoutedEventArgs e) { IsChecked = !IsChecked; } } } The problem comes when I try to bind the "To" attribute in the DoubleAnimations to the actual width of the text, the same as I'm doing in the ControlTemplate. If I bind the values to an ActualWidth of an element in the ControlTemplate, the control comes up as a blank checkbox (my base class). However, I'm binding to the same ActualWidths in the ControlTemplate itself without any problems. Just seems to be the CheckBox.Resources that have a problem with it. For instance, the following will break it: <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="{Binding ElementName=CheckedText, Path=ActualWidth}" /> I don't know whether this is because it's trying to bind to a value that doesn't exist until a render pass is done, or if it's something else. Anyone have any experience with this sort of animation binding?

    Read the article

  • Adding a second table in a database

    - by MB
    Hi everyone. I used the code provided by the NoteExample from the developers doc to create a database. Now I want to add a second table to store different data. I simply "copied" the given code, but when I try to insert into the new table I get an error saying: "0ERROR/Database(370): android.database.sqlite.SQLiteException: no such table: routes: , while compiling: INSERT INTO routes(line, arrival, duration, start) VALUES(?, ?, ?, ?);" Can someone please take quick look at my DbAdapter class and give me a hint or a solution? I really don't see any problem. my code compiles without any errors.. thanks in advance! CODE: import static android.provider.BaseColumns._ID; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DbAdapter { public static final String KEY_FROM = "title"; public static final String KEY_TO = "body"; public static final String KEY_ROWID = "_id"; public static final String KEY_START = "start"; public static final String KEY_ARRIVAL = "arrival"; public static final String KEY_LINE = "line"; public static final String KEY_DURATION = "duration"; private static final String DATABASE_NAME = "data"; private static final String DATABASE_NOTESTABLE = "notes"; private static final String DATABASE_ROUTESTABLE = "routes"; private static final String TAG = "DbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; /** * Database creation sql statement */ private static final String DATABASE_CREATE_NOTES = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null)"; private static final String DATABASE_CREATE_ROUTES = "create table routes (_id integer primary key autoincrement, " + "start text not null, arrival text not null, " + "line text not null, duration text not null);"; private static final int DATABASE_VERSION = 2; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE_NOTES); Log.d(TAG, "created notes table"); db.execSQL(DATABASE_CREATE_ROUTES); //CREATE LOKALTABLE db.execSQL("CREATE TABLE " + DATABASE_ROUTESTABLE + " " + "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_START + " TEXT NOT NULL, " + KEY_ARRIVAL + " TEXT NOT NULL, " + KEY_LINE + " TEXT NOT NULL, " + KEY_DURATION + " TEXT NOT NULL"); Log.d(TAG, "created routes table"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public DbAdapter(Context ctx) { this.mCtx = ctx; } /** * Open the notes database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public DbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } /** * Create a new note using the title and body provided. If the note is * successfully created return the new rowId for that note, otherwise return * a -1 to indicate failure. * * @param title the title of the note * @param body the body of the note * @return rowId or -1 if failed */ public long createNote(String title, String body) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_FROM, title); initialValues.put(KEY_TO, body); return mDb.insert(DATABASE_NOTESTABLE, null, initialValues); } /** * Create a new route using the title and body provided. If the route is * successfully created return the new rowId for that route, otherwise return * a -1 to indicate failure. * * @param start the start time of the route * @param arrival the arrival time of the route * @param line the line number of the route * @param duration the routes duration * @return rowId or -1 if failed */ public long createRoute(String start, String arrival, String line, String duration){ ContentValues initialValues = new ContentValues(); initialValues.put(KEY_START, start); initialValues.put(KEY_ARRIVAL, arrival); initialValues.put(KEY_LINE, line); initialValues.put(KEY_DURATION, duration); return mDb.insert(DATABASE_ROUTESTABLE, null, initialValues); } /** * Delete the note with the given rowId * * @param rowId id of note to delete * @return true if deleted, false otherwise */ public boolean deleteNote(long rowId) { return mDb.delete(DATABASE_NOTESTABLE, KEY_ROWID + "=" + rowId, null) > 0; } /** * Return a Cursor over the list of all notes in the database * * @return Cursor over all notes */ public Cursor fetchAllNotes() { return mDb.query(DATABASE_NOTESTABLE, new String[] {KEY_ROWID, KEY_FROM, KEY_TO}, null, null, null, null, null); } /** * Return a Cursor over the list of all routes in the database * * @return Cursor over all routes */ public Cursor fetchAllRoutes() { return mDb.query(DATABASE_ROUTESTABLE, new String[] {KEY_ROWID, KEY_START, KEY_ARRIVAL, KEY_LINE, KEY_DURATION}, null, null, null, null, null); } /** * Return a Cursor positioned at the note that matches the given rowId * * @param rowId id of note to retrieve * @return Cursor positioned to matching note, if found * @throws SQLException if note could not be found/retrieved */ public Cursor fetchNote(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_NOTESTABLE, new String[] {KEY_ROWID, KEY_FROM, KEY_TO}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a Cursor positioned at the route that matches the given rowId * * @param rowId id of route to retrieve * @return Cursor positioned to matching route * @throws SQLException if note could not be found/retrieved */ public Cursor fetchRoute(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_ROUTESTABLE, new String[] {KEY_ROWID, KEY_START, KEY_ARRIVAL, KEY_LINE, KEY_DURATION}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Update the note using the details provided. The note to be updated is * specified using the rowId, and it is altered to use the title and body * values passed in * * @param rowId id of note to update * @param title value to set note title to * @param body value to set note body to * @return true if the note was successfully updated, false otherwise */ public boolean updateNote(long rowId, String title, String body) { ContentValues args = new ContentValues(); args.put(KEY_FROM, title); args.put(KEY_TO, body); return mDb.update(DATABASE_NOTESTABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } }

    Read the article

  • how to use 3D map Actionscript class in mxml file for display map.

    - by nemade-vipin
    hello friends, I have created the application in which I have to use 3D map Action Script class in mxml file to display a map in form. that is in tab navigator last tab. My ActionScript 3D map class is(FlyingDirections):- package src.SBTSCoreObject { import src.SBTSCoreObject.JSONDecoder; import com.google.maps.InfoWindowOptions; import com.google.maps.LatLng; import com.google.maps.LatLngBounds; import com.google.maps.Map3D; import com.google.maps.MapEvent; import com.google.maps.MapOptions; import com.google.maps.MapType; import com.google.maps.MapUtil; import com.google.maps.View; import com.google.maps.controls.NavigationControl; import com.google.maps.geom.Attitude; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.Marker; import com.google.maps.overlays.MarkerOptions; import com.google.maps.services.Directions; import com.google.maps.services.DirectionsEvent; import com.google.maps.services.Route; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.DropShadowFilter; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; public class FlyingDirections extends Map3D { /** * Panoramio home page. */ private static const PANORAMIO_HOME:String = "http://www.panoramio.com/"; /** * The icon for the car. */ [Embed("assets/car-icon-24px.png")] private static const Car:Class; /** * The Panoramio icon. */ [Embed("assets/iw_panoramio.png")] private static const PanoramioIcon:Class; /** * We animate a zoom in to the start the route before the car starts * to move. This constant sets the time in seconds over which this * zoom occurs. */ private static const LEAD_IN_DURATION:Number = 3; /** * Duration of the trip in seconds. */ private static const TRIP_DURATION:Number = 40; /** * Constants that define the geometry of the Panoramio image markers. */ private static const BORDER_T:Number = 3; private static const BORDER_L:Number = 10; private static const BORDER_R:Number = 10; private static const BORDER_B:Number = 3; private static const GAP_T:Number = 2; private static const GAP_B:Number = 1; private static const IMAGE_SCALE:Number = 1; /** * Trajectory that the camera follows over time. Each element is an object * containing properties used to generate parameter values for flyTo(..). * fraction = 0 corresponds to the start of the trip; fraction = 1 * correspondsto the end of the trip. */ private var FLY_TRAJECTORY:Array = [ { fraction: 0, zoom: 6, attitude: new Attitude(0, 0, 0) }, { fraction: 0.2, zoom: 8.5, attitude: new Attitude(30, 30, 0) }, { fraction: 0.5, zoom: 9, attitude: new Attitude(30, 40, 0) }, { fraction: 1, zoom: 8, attitude: new Attitude(50, 50, 0) }, { fraction: 1.1, zoom: 8, attitude: new Attitude(130, 50, 0) }, { fraction: 1.2, zoom: 8, attitude: new Attitude(220, 50, 0) }, ]; /** * Number of panaramio photos for which we load data. We&apos;ll select a * subset of these approximately evenly spaced along the route. */ private static const NUM_GEOTAGGED_PHOTOS:int = 50; /** * Number of panaramio photos that we actually show. */ private static const NUM_SHOWN_PHOTOS:int = 7; /** * Scaling between real trip time and animation time. */ private static const SCALE_TIME:Number = 0.001; /** * getTimer() value at the instant that we start the trip. If this is 0 then * we have not yet started the car moving. */ private var startTimer:int = 0; /** * The current route. */ private var route:Route; /** * The polyline for the route. */ private var polyline:IPolyline; /** * The car marker. */ private var marker:Marker; /** * The cumulative duration in seconds over each step in the route. * cumulativeStepDuration[0] is 0; cumulativeStepDuration[1] adds the * duration of step 0; cumulativeStepDuration[2] adds the duration * of step 1; etc. */ private var cumulativeStepDuration:/*Number*/Array = []; /** * The cumulative distance in metres over each vertex in the route polyline. * cumulativeVertexDistance[0] is 0; cumulativeVertexDistance[1] adds the * distance to vertex 1; cumulativeVertexDistance[2] adds the distance to * vertex 2; etc. */ private var cumulativeVertexDistance:Array; /** * Array of photos loaded from Panoramio. This array has the same format as * the &apos;photos&apos; property within the JSON returned by the Panoramio API * (see http://www.panoramio.com/api/), with additional properties added to * individual photo elements to hold the loader structures that fetch * the actual images. */ private var photos:Array = []; /** * Array of polyline vertices, where each element is in world coordinates. * Several computations can be faster if we can use world coordinates * instead of LatLng coordinates. */ private var worldPoly:/*Point*/Array; /** * Whether the start button has been pressed. */ private var startButtonPressed:Boolean = false; /** * Saved event from onDirectionsSuccess call. */ private var directionsSuccessEvent:DirectionsEvent = null; /** * Start button. */ private var startButton:Sprite; /** * Alpha value used for the Panoramio image markers. */ private var markerAlpha:Number = 0; /** * Index of the current driving direction step. Used to update the * info window content each time we progress to a new step. */ private var currentStepIndex:int = -1; /** * The fly directions map constructor. * * @constructor */ public function FlyingDirections() { key="ABQIAAAA7QUChpcnvnmXxsjC7s1fCxQGj0PqsCtxKvarsoS-iqLdqZSKfxTd7Xf-2rEc_PC9o8IsJde80Wnj4g"; super(); addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize); addEventListener(MapEvent.MAP_READY, onMapReady); } /** * Handles map preintialize. Initializes the map center and zoom level. * * @param event The map event. */ private function onMapPreinitialize(event:MapEvent):void { setInitOptions(new MapOptions({ center: new LatLng(-26.1, 135.1), zoom: 4, viewMode: View.VIEWMODE_PERSPECTIVE, mapType:MapType.PHYSICAL_MAP_TYPE })); } /** * Handles map ready and looks up directions. * * @param event The map event. */ private function onMapReady(event:MapEvent):void { enableScrollWheelZoom(); enableContinuousZoom(); addControl(new NavigationControl()); // The driving animation will be updated on every frame. addEventListener(Event.ENTER_FRAME, enterFrame); addStartButton(); // We start the directions loading now, so that we&apos;re ready to go when // the user hits the start button. var directions:Directions = new Directions(); directions.addEventListener( DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener( DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure); directions.load("48 Pirrama Rd, Pyrmont, NSW to Byron Bay, NSW"); } /** * Adds a big blue start button. */ private function addStartButton():void { startButton = new Sprite(); startButton.buttonMode = true; startButton.addEventListener(MouseEvent.CLICK, onStartClick); startButton.graphics.beginFill(0x1871ce); startButton.graphics.drawRoundRect(0, 0, 150, 100, 10, 10); startButton.graphics.endFill(); var startField:TextField = new TextField(); startField.autoSize = TextFieldAutoSize.LEFT; startField.defaultTextFormat = new TextFormat("_sans", 20, 0xffffff, true); startField.text = "Start!"; startButton.addChild(startField); startField.x = 0.5 * (startButton.width - startField.width); startField.y = 0.5 * (startButton.height - startField.height); startButton.filters = [ new DropShadowFilter() ]; var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.addChild(startButton); startButton.x = 0.5 * (container.width - startButton.width); startButton.y = 0.5 * (container.height - startButton.height); var panoField:TextField = new TextField(); panoField.autoSize = TextFieldAutoSize.LEFT; panoField.defaultTextFormat = new TextFormat("_sans", 11, 0x000000, true); panoField.text = "Photos provided by Panoramio are under the copyright of their owners."; container.addChild(panoField); panoField.x = container.width - panoField.width - 5; panoField.y = 5; } /** * Handles directions success. Starts flying the route if everything * is ready. * * @param event The directions event. */ private function onDirectionsSuccess(event:DirectionsEvent):void { directionsSuccessEvent = event; flyRouteIfReady(); } /** * Handles click on the start button. Starts flying the route if everything * is ready. */ private function onStartClick(event:MouseEvent):void { startButton.removeEventListener(MouseEvent.CLICK, onStartClick); var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.removeChild(startButton); startButtonPressed = true; flyRouteIfReady(); } /** * If we have loaded the directions and the start button has been pressed * start flying the directions route. */ private function flyRouteIfReady():void { if (!directionsSuccessEvent || !startButtonPressed) { return; } var directions:Directions = directionsSuccessEvent.directions; // Extract the route. route = directions.getRoute(0); // Draws the polyline showing the route. polyline = directions.createPolyline(); addOverlay(directions.createPolyline()); // Creates a car marker that is moved along the route. var car:DisplayObject = new Car(); marker = new Marker(route.startGeocode.point, new MarkerOptions({ icon: car, iconOffset: new Point(-car.width / 2, -car.height) })); addOverlay(marker); transformPolyToWorld(); createCumulativeArrays(); // Load Panoramio data for the region covered by the route. loadPanoramioData(directions.bounds); var duration:Number = route.duration; // Start a timer that will trigger the car moving after the lead in time. var leadInTimer:Timer = new Timer(LEAD_IN_DURATION * 1000, 1); leadInTimer.addEventListener(TimerEvent.TIMER, onLeadInDone); leadInTimer.start(); var flyTime:Number = -LEAD_IN_DURATION; // Set up the camera flight trajectory. for each (var flyStep:Object in FLY_TRAJECTORY) { var time:Number = flyStep.fraction * duration; var center:LatLng = latLngAt(time); var scaledTime:Number = time * SCALE_TIME; var zoom:Number = flyStep.zoom; var attitude:Attitude = flyStep.attitude; var elapsed:Number = scaledTime - flyTime; flyTime = scaledTime; flyTo(center, zoom, attitude, elapsed); } } /** * Loads Panoramio data for the route bounds. We load data about more photos * than we need, then select a subset lying along the route. * @param bounds Bounds within which to fetch images. */ private function loadPanoramioData(bounds:LatLngBounds):void { var params:Object = { order: "popularity", set: "full", from: "0", to: NUM_GEOTAGGED_PHOTOS.toString(10), size: "small", minx: bounds.getWest(), miny: bounds.getSouth(), maxx: bounds.getEast(), maxy: bounds.getNorth() }; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "http://www.panoramio.com/map/get_panoramas.php?" + paramsToString(params)); loader.addEventListener(Event.COMPLETE, onPanoramioDataLoaded); loader.addEventListener(IOErrorEvent.IO_ERROR, onPanoramioDataFailed); loader.load(request); } /** * Transforms the route polyline to world coordinates. */ private function transformPolyToWorld():void { var numVertices:int = polyline.getVertexCount(); worldPoly = new Array(numVertices); for (var i:int = 0; i < numVertices; ++i) { var vertex:LatLng = polyline.getVertex(i); worldPoly[i] = fromLatLngToPoint(vertex, 0); } } /** * Returns the time at which the route approaches closest to the * given point. * @param world Point in world coordinates. * @return Route time at which the closest approach occurs. */ private function getTimeOfClosestApproach(world:Point):Number { var minDistSqr:Number = Number.MAX_VALUE; var numVertices:int = worldPoly.length; var x:Number = world.x; var y:Number = world.y; var minVertex:int = 0; for (var i:int = 0; i < numVertices; ++i) { var dx:Number = worldPoly[i].x - x; var dy:Number = worldPoly[i].y - y; var distSqr:Number = dx * dx + dy * dy; if (distSqr < minDistSqr) { minDistSqr = distSqr; minVertex = i; } } return cumulativeVertexDistance[minVertex]; } /** * Returns the array index of the first element that compares greater than * the given value. * @param ordered Ordered array of elements. * @param value Value to use for comparison. * @return Array index of the first element that compares greater than * the given value. */ private function upperBound(ordered:Array, value:Number, first:int=0, last:int=-1):int { if (last < 0) { last = ordered.length; } var count:int = last - first; var index:int; while (count > 0) { var step:int = count >> 1; index = first + step; if (value >= ordered[index]) { first = index + 1; count -= step - 1; } else { count = step; } } return first; } /** * Selects up to a given number of photos approximately evenly spaced along * the route. * @param ordered Array of photos, each of which is an object with * a property &apos;closestTime&apos;. * @param number Number of photos to select. */ private function selectEvenlySpacedPhotos(ordered:Array, number:int):Array { var start:Number = cumulativeVertexDistance[0]; var end:Number = cumulativeVertexDistance[cumulativeVertexDistance.length - 2]; var closestTimes:Array = []; for each (var photo:Object in ordered) { closestTimes.push(photo.closestTime); } var selectedPhotos:Array = []; for (var i:int = 0; i < number; ++i) { var idealTime:Number = start + ((end - start) * (i + 0.5) / number); var index:int = upperBound(closestTimes, idealTime); if (index < 1) { index = 0; } else if (index >= ordered.length) { index = ordered.length - 1; } else { var errorToPrev:Number = Math.abs(idealTime - closestTimes[index - 1]); var errorToNext:Number = Math.abs(idealTime - closestTimes[index]); if (errorToPrev < errorToNext) { --index; } } selectedPhotos.push(ordered[index]); } return selectedPhotos; } /** * Handles completion of loading the Panoramio index data. Selects from the * returned photo indices a subset of those that lie along the route and * initiates load of each of these. * @param event Load completion event. */ private function onPanoramioDataLoaded(event:Event):void { var loader:URLLoader = event.target as URLLoader; var decoder:JSONDecoder = new JSONDecoder(loader.data as String); var allPhotos:Array = decoder.getValue().photos; for each (var photo:Object in allPhotos) { var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); photo.closestTime = getTimeOfClosestApproach(fromLatLngToPoint(latLng, 0)); } allPhotos.sortOn("closestTime", Array.NUMERIC); photos = selectEvenlySpacedPhotos(allPhotos, NUM_SHOWN_PHOTOS); for each (photo in photos) { var photoLoader:Loader = new Loader(); // The images aren&apos;t on panoramio.com: we can&apos;t acquire pixel access // using "new LoaderContext(true)". photoLoader.load( new URLRequest(photo.photo_file_url)); photo.loader = photoLoader; // Save the loader info: we use this to find the original element when // the load completes. photo.loaderInfo = photoLoader.contentLoaderInfo; photoLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onPhotoLoaded); } } /** * Creates a MouseEvent listener function that will navigate to the given * URL in a new window. * @param url URL to which to navigate. */ private function createOnClickUrlOpener(url:String):Function { return function(event:MouseEvent):void { navigateToURL(new URLRequest(url)); }; } /** * Handles completion of loading an individual Panoramio image. * Adds a custom marker that displays the image. Initially this is made * invisible so that it can be faded in as needed. * @param event Load completion event. */ private function onPhotoLoaded(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; // We need to find which photo element this image corresponds to. for each (var photo:Object in photos) { if (loaderInfo == photo.loaderInfo) { var imageMarker:Sprite = createImageMarker(photo.loader, photo.owner_name, photo.owner_url); var options:MarkerOptions = new MarkerOptions({ icon: imageMarker, hasShadow: true, iconAlignment: MarkerOptions.ALIGN_BOTTOM | MarkerOptions.ALIGN_LEFT }); var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); var marker:Marker = new Marker(latLng, options); photo.marker = marker; addOverlay(marker); // A hack: we add the actual image after the overlay has been added, // which creates the shadow, so that the shadow is valid even if we // don&apos;t have security privileges to generate the shadow from the // image. marker.foreground.visible = false; marker.shadow.alpha = 0; var imageHolder:Sprite = new Sprite(); imageHolder.addChild(photo.loader); imageHolder.buttonMode = true; imageHolder.addEventListener( MouseEvent.CLICK, createOnClickUrlOpener(photo.photo_url)); imageMarker.addChild(imageHolder); return; } } trace("An image was loaded which could not be found in the photo array."); } /** * Creates a custom marker showing an image. */ private function createImageMarker(child:DisplayObject, ownerName:String, ownerUrl:String):Sprite { var content:Sprite = new Sprite(); var panoramioIcon:Bitmap = new PanoramioIcon(); var iconHolder:Sprite = new Sprite(); iconHolder.addChild(panoramioIcon); iconHolder.buttonMode = true; iconHolder.addEventListener(MouseEvent.CLICK, onPanoramioIconClick); panoramioIcon.x = BORDER_L; panoramioIcon.y = BORDER_T; content.addChild(iconHolder); // NOTE: we add the image as a child only after we&apos;ve added the marker // to the map. Currently the API requires this if it&apos;s to generate the // shadow for unprivileged content. // Shrink the image, so that it doesn&apos;t obcure too much screen space. // Ideally, we&apos;d subsample, but we don&apos;t have pixel level access. child.scaleX = IMAGE_SCALE; child.scaleY = IMAGE_SCALE; var imageW:Number = child.width; var imageH:Number = child.height; child.x = BORDER_L + 30; child.y = BORDER_T + iconHolder.height + GAP_T; var authorField:TextField = new TextField(); authorField.autoSize = TextFieldAutoSize.LEFT; authorField.defaultTextFormat = new TextFormat("_sans", 12); authorField.text = "author:"; content.addChild(authorField); authorField.x = BORDER_L; authorField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var ownerField:TextField = new TextField(); ownerField.autoSize = TextFieldAutoSize.LEFT; var textFormat:TextFormat = new TextFormat("_sans", 14, 0x0e5f9a); ownerField.defaultTextFormat = textFormat; ownerField.htmlText = "<a href=\"" + ownerUrl + "\" target=\"_blank\">" + ownerName + "</a>"; content.addChild(ownerField); ownerField.x = BORDER_L + authorField.width; ownerField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var totalW:Number = BORDER_L + Math.max(imageW, ownerField.width + authorField.width) + BORDER_R; var totalH:Number = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B + ownerField.height + BORDER_B; content.graphics.beginFill(0xffffff); content.graphics.drawRoundRect(0, 0, totalW, totalH, 10, 10); content.graphics.endFill(); var marker:Sprite = new Sprite(); marker.addChild(content); content.x = 30; content.y = 0; marker.graphics.lineStyle(); marker.graphics.beginFill(0xff0000); marker.graphics.drawCircle(0, totalH + 30, 3); marker.graphics.endFill(); marker.graphics.lineStyle(2, 0xffffff); marker.graphics.moveTo(30 + 10, totalH - 10); marker.graphics.lineTo(0, totalH + 30); return marker; } /** * Handles click on the Panoramio icon. */ private function onPanoramioIconClick(event:MouseEvent):void { navigateToURL(new URLRequest(PANORAMIO_HOME)); } /** * Handles failure of a Panoramio image load. */ private function onPanoramioDataFailed(event:IOErrorEvent):void { trace("Load of image failed: " + event); } /** * Returns a string containing cgi query parameters. * @param Associative array mapping query parameter key to value. * @return String containing cgi query parameters. */ private static function paramsToString(params:Object):String { var result:String = ""; var separator:String = ""; for (var key:String in params) { result += separator + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); separator = "&"; } return result; } /** * Called once the lead-in flight is done. Starts the car driving along * the route and starts a timer to begin fade in of the Panoramio * images in 1.5 seconds. */ private function onLeadInDone(event:Event):void { // Set startTimer non-zero so that the car starts to move. startTimer = getTimer(); // Start a timer that will fade in the Panoramio images. var fadeInTimer:Timer = new Timer(1500, 1); fadeInTimer.addEventListener(TimerEvent.TIMER, onFadeInTimer); fadeInTimer.start(); } /** * Handles the fade in timer&apos;s TIMER event. Sets markerAlpha above zero * which causes the frame enter handler to fade in the markers. */ private function onFadeInTimer(event:Event):void { markerAlpha = 0.01; } /** * The end time of the flight. */ private function get endTime():Number { if (!cumulativeStepDuration || cumulativeStepDuration.length == 0) { return startTimer; } return startTimer + cumulativeStepDuration[cumulativeStepDuration.length - 1]; } /** * Creates the cumulative arrays, cumulativeStepDuration and * cumulativeVertexDistance. */ private function createCumulativeArrays():void { cumulativeStepDuration = new Array(route.numSteps + 1); cumulativeVertexDistance = new Array(polyline.getVertexCount() + 1); var polylineTotal:Number = 0; var total:Number = 0; var numVertices:int = polyline.getVertexCount(); for (var stepIndex:int = 0; stepIndex < route.numSteps; ++stepIndex) { cumulativeStepDuration[stepIndex] = total; total += route.getStep(stepIndex).duration; var startVertex:int = stepIndex >= 0 ? route.getStep(stepIndex).polylineIndex : 0; var endVertex:int = stepIndex < (route.numSteps - 1) ? route.getStep(stepIndex + 1).polylineIndex : numVertices; var duration:Number = route.getStep(stepIndex).duration; var stepVertices:int = endVertex - startVertex; var latLng:LatLng = polyline.getVertex(startVertex); for (var vertex:int = startVertex; vertex < endVertex; ++vertex) { cumulativeVertexDistance[vertex] = polylineTotal; if (vertex < numVertices - 1) { var nextLatLng:LatLng = polyline.getVertex(vertex + 1); polylineTotal += nextLatLng.distanceFrom(latLng); } latLng = nextLatLng; } } cumulativeStepDuration[stepIndex] = total; } /** * Opens the info window above the car icon that details the given * step of the driving directions. * @param stepIndex Index of the current step. */ private function openInfoForStep(stepIndex:int):void { // Sets the content of the info window. var content:String; if (stepIndex >= route.numSteps) { content = "<b>" + route.endGeocode.address + "</b>" + "<br /><br />" + route.summaryHtml; } else { content = "<b>" + stepIndex + ".</b> " + route.getStep(stepIndex).descriptionHtml; } marker.openInfoWindow(new InfoWindowOptions({ contentHTML: content })); } /** * Displays the driving directions step appropriate for the given time. * Opens the info window showing the step instructions each time we * progress to a new step. * @param time Time for which to display the step. */ private function displayStepAt(time:Number):void { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex >= 0 && stepIndex <= maxStepIndex && currentStepIndex != stepIndex) { openInfoForStep(stepIndex); currentStepIndex = stepIndex; } } /** * Returns the LatLng at which the car should be positioned at the given * time. * @param time Time for which LatLng should be found. * @return LatLng. */ private function latLngAt(time:Number):LatLng { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex < minStepIndex) { return route.startGeocode.point; } else if (stepIndex > maxStepIndex) { return route.endGeocode.point; } var stepStart:Number = cumulativeStepDuration[stepIndex]; var stepEnd:Number = cumulativeStepDuration[stepIndex + 1]; var stepFraction:Number = (time - stepStart) / (stepEnd - stepStart); var startVertex:int = route.getStep(stepIndex).polylineIndex; var endVertex:int = (stepIndex + 1) < route.numSteps ? route.getStep(stepIndex + 1).polylineIndex : polyline.getVertexCount(); var stepVertices:int = endVertex - startVertex; var stepLeng

    Read the article

  • SQL Profiler: Read/Write units

    - by Ian Boyd
    i've picked a query out of SQL Server Profiler that says it took 1,497 reads: EventClass: SQL:BatchCompleted TextData: SELECT Transactions.... CPU: 406 Reads: 1497 Writes: 0 Duration: 406 So i've taken this query into Query Analyzer, so i may try to reduce the number of reads. But when i turn on SET STATISTICS IO ON to see the IO activity for the query, i get nowhere close to one thousand reads: Table Scan Count Logical Reads =================== ========== ============= FintracTransactions 4 20 LCDs 2 4 LCTs 2 4 FintracTransacti... 0 0 Users 1 2 MALs 0 0 Patrons 0 0 Shifts 1 2 Cages 1 1 Windows 1 3 Logins 1 3 Sessions 1 6 Transactions 1 7 Which if i do my math right, there is a total of 51 reads; not 1,497. So i assume Reads in SQL Profiler is an arbitrary metric. Does anyone know the conversion of SQL Server Profiler Reads to IO Reads? See also SQL Profiler CPU / duration unit Query Analyzer VS. Query Profiler Reads, Writes, and Duration Discrepencies

    Read the article

  • How to get image to pulse with opacity with JQuery

    - by Alex
    I am trying to get an image to change opacity smoothly over a duration of time. Here's the code I have for it. <script type="text/javascript"> pulsem(elementid){ var element = document.getElementById(elementid) jquery(element).pulse({opacity: [0,1]}, { duration: 100, // duration of EACH individual animation times: 3, // Will go three times through the pulse array [0,1] easing: 'linear', // easing function for each individual animation complete: function() { alert("I'm done pulsing!"); } }) </script> <a href="city.htm"><img src="waterloo.png" onmouseover="javascript:pulsem("waterloo")" border="0" class="env" id="waterloo"/></a> Also, is there a way for this to happen automatically without the need of a mouseover? Thanks.

    Read the article

  • Creating an Excel 2007 bubble chart with date values in axis

    - by Shadowfoot
    I'm trying to create a graph showing the duration of issue resolution. I believe a bubble chart in excel will show what I want but I can't manage to get it working correctly. For each date I have a number of days (duration) and a number of issues (magnitude). Most dates have a duration of 1 with a large magnitude, and I want to avoid the outliers dominating the chart. e.g. 1-Feb, 1, 15 1-Feb, 2, 10 1-Feb, 9, 1 2-Feb, 1, 11 2-Feb, 2, 14 2-Feb, 6, 2 2-Feb, 18, 1 etc. I want the data in this example to give me 2 columns of bubbles. When I try to get excel to create the chart I can't get the date to appear at on the x axis; I get a count (representing the row of the data) instead, and as each row is a separate column, the values don't line up for the date. Can this be done in Excel 2007 without using VBA?

    Read the article

  • Can anyone telme whats wrong in this part of code

    - by Mobin
    string name = ((DateTimePicker)sender).Name.ToString(); name = name.Substring(0, name.Length - 1); name = name + "4"; TimeSpan duration = new TimeSpan(); duration = ((DateTimePicker)sender).Value - ((DateTimePicker)panel2.Controls[name]).Value; name = name.Substring(0, name.Length - 1); name = name + "6"; ((MaskedTextBox)panel2.Controls[name]).Text = duration.ToString(); on execution it gives me Object reference not set to instance of an object similar functionality is used on other places but can't find out what i have to reinitialize here :$

    Read the article

  • Can anyone tell me what's wrong in this part of code

    - by Mobin
    string name = ((DateTimePicker)sender).Name.ToString(); name = name.Substring(0, name.Length - 1); name = name + "4"; TimeSpan duration = new TimeSpan(); duration = ((DateTimePicker)sender).Value - ((DateTimePicker)panel2.Controls[name]).Value; name = name.Substring(0, name.Length - 1); name = name + "6"; ((MaskedTextBox)panel2.Controls[name]).Text = duration.ToString(); On execution it gives me Object reference not set to instance of an object similar functionality is used on other places but I can't find out what I have to reinitialize here :$ The casting for datetimepicker is fine I have to get a name for the datetiempicker to identify the row it's on in my form and the picker before that to calculate their differences and then print that difference in a maskedtext box from the control whose name I make using names of two datetimepickers but when I access controls in the error line I get this message.

    Read the article

  • Crystal Report Function for converting Seconds to Timespan format.

    - by arakkots
    I have a crystal report where it shows the Agent's activities throughout the day with a pie chart. In the details section it is displaying: Activity [string] StartedAt [DateTime] EndedAt [DateTime] Duration [The difference between EndedAt and StartedAt in seconds - Integer] Report data is GroupedBy Activity and summarized by Duration. Currently Duration is shown in seconds but I need to format it 02h:30m:22s:15ms. For that I wrote a custom function in Crystal Report in the Formula Workshop editor as follows, but it looks like the syntax is not right (Error message on keyword Long: "A variable type (for example, 'String') is missing."). Can someone help? Function GetTimeSpanString(seconds as Long) Dim ts As TimeSpan = TimeSpan.FromSeconds( seconds ); GetTimeSpan = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds) End Function

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >