public void Moment_ToStringTest()
        {

            var moment = new Moment(-173.87, Moment.PoundInches);

            moment.ToString().Should().Be("-173.87 lb-in.");
        }
示例#2
0
        public void String()
        {
            var expected = new DateTime(1995, 12, 25);
            var actual = new Moment(true) { Year = 1995, Month = 12, Day = 25 }.DateTime();

            Assert.AreEqual(expected, actual, "Not the same");
        }
示例#3
0
 internal static void Second(ref Moment moment)
 {
     while (moment.Second >= 60)
     {
         moment.Second = moment.Second - 60;
         moment.Minute++;
     }
 }
示例#4
0
 internal static void Minute(ref Moment moment)
 {
     while (moment.Minute >= 60)
     {
         moment.Minute = moment.Minute - 60;
         moment.Hour++;
     }
 }
示例#5
0
 internal static void Hour(ref Moment moment)
 {
     while (moment.Hour >= 24)
     {
         moment.Hour = moment.Hour - 24;
         moment.Hour++;
     }
 }
示例#6
0
 internal static void Millisecond(ref Moment moment)
 {
     while (moment.Millisecond >= 1000)
     {
         moment.Millisecond = moment.Millisecond - 1000;
         moment.Second++;
     }
 }
示例#7
0
 internal static void Month(ref Moment moment)
 {
     while (moment.Month >= 12)
     {
         moment.Month = moment.Month - 12;
         moment.Year++;
     }
 }
示例#8
0
 internal static void Day(ref Moment moment)
 {
     var daysThisMonth = moment.DateTime().DaysInMonth();
     while (moment.Day >= daysThisMonth)
     {
         moment.Day = moment.Day - daysThisMonth;
         moment.Month++;
     }
 }
示例#9
0
 public void TestScheduleJob()
 {
     Uri testUri = new Uri("http://google.com");
     // You will need an app.config with this setting available
     Moment a = new Moment(ConfigurationManager.AppSettings["MomentApp.ApiKey"]);
     var job = a.ScheduleJob(new Job()
     {
         at = DateTime.Now.AddMinutes(1),
         method = "GET",
         uri = testUri
     });
     Assert.IsNotNull(job.id);
 }
示例#10
0
        public void CalendarTest()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN");
            var m = new Moment(); 
            var str = m.Calendar();
            Assert.AreEqual(str.IndexOf("今天"), 0, "should be Today");

            var str2 = m.Calendar(DateTime.Now.AddDays(-1)); 
            Assert.AreEqual(str2.IndexOf("明天"), 0, "should be Tomorrow");

            var str3 = m.Calendar(DateTime.Now.AddDays(1));
            Assert.AreEqual(str3.IndexOf("昨天"), 0, "should be Yesterday");

        }
        public async Task<ActionResult> GetSentToMe(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return HttpBadRequest();
            }
            var result = await Repository.FindSentTo(userId);

            if (result.Any() == false)
            {
                result = new Moment[] { new Moment { Id = "No moments yet!" } };
            }
            return Json(result);
        }
        public async Task<HttpStatusCodeResult> Post([FromBody]MomentBody body)
        {
            if (ModelState.IsValid == false)
            {
                return HttpBadRequest();
            }
            var recipients = body.Recipients;

            if (body.IsValid() == false)
            {
                return HttpBadRequest();
            }
            var validRecipients = body.SanitizeRecipients();
            if (validRecipients.Any() == false)
            {
                return HttpBadRequest();
            }
            if (body.ContainsAttachedContent)
            {
                body.Url = await StoreImageBlob(body.Attached);
            }

            foreach (var user in validRecipients)
            {
                var moment = new Moment
                {
                    MomentUrl = body.Url ?? string.Empty,
                    SenderUserId = body.SenderId,
                    //SenderName = body.SenderName,
                    SenderProfileImage = body.SenderProfileImage ?? string.Empty,
                    RecipientUserId = user,
                    DisplayTime = body.DisplayTime,
                    TimeSent = DateTime.Now
                };

                Repository.Add(moment);
            }
            Repository.Commit();

            return new HttpStatusCodeResult((int)HttpStatusCode.Created);
        }
    private void Start()
    {
        mDataDoc.Load("SceneBreakdown.xml");
        if (mDataDoc.ChildNodes.Count != 1)
        {
            Debug.Log("Data file did not load.");
        }

        //loop acts and add to script
        XmlNodeList actsNodeList = mDataDoc.SelectNodes("script/act");
        Debug.Log("loading " + actsNodeList.Count + " acts...");
        foreach (XmlElement act in actsNodeList)
        {
            Act newAct = new Act();
            newAct.Number = Int32.Parse(act.Attributes.GetNamedItem("number").Value);
            //loop scenes and add to act
            XmlNodeList scenesNodeList = act.SelectNodes("scene");
            Debug.Log("loading " + scenesNodeList.Count + " scenes...");
            foreach (XmlElement scene in scenesNodeList)
            {
                Scene newScene = new Scene();
                newScene.Number = Int32.Parse(scene.Attributes.GetNamedItem("number").Value);
                //loop moments and add to scene
                XmlNodeList momentsNodeList = scene.SelectNodes("moment");
                Debug.Log("loading " + momentsNodeList.Count + " moments...");
                foreach (XmlElement moment in momentsNodeList)
                {
                    string title = moment.Attributes.GetNamedItem("title").Value;
                    string line = moment.Attributes.GetNamedItem("line").Value;

                    Moment newMoment = new Moment(title, line);
                    newScene.moments.Add(newMoment);
                }
                newAct.scenes.Add(newScene);
            }
            m_Script.acts.Add(newAct);
        }
    }
        private void OnHarvest(object state)
        {
            float usage = theCPUCounter.NextValue();
            Thread.Sleep(1000);
            float usage2 = theCPUCounter.NextValue();

            float memory = theMemCounter.NextValue();

            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");

            IDatabase database = redis.GetDatabase();

            Moment<double> cpuMoment = new Moment<double>("CPU", Math.Round((usage + usage2), 2), DateTime.UtcNow);
            Moment<float> memoryFreeMoment = new Moment<float>("Free Memory", memory, DateTime.UtcNow);

            string cpuMomentJson = JsonConvert.SerializeObject(cpuMoment);
            string memoryMomentJson = JsonConvert.SerializeObject(memoryFreeMoment);

            database.ListLeftPush("counters:cpu", cpuMomentJson, When.Always, CommandFlags.HighPriority);
            database.ListLeftPush("counters:freememory", memoryMomentJson, When.Always, CommandFlags.HighPriority);

            Console.WriteLine($"CPU: {Math.Round(usage + usage2, 2)}%");
            Console.WriteLine($"Free Memory: {memory}Mb");
        }
 private static string BuildTijden(Moment[] momenten)
 {
   var builder = new StringBuilder();
   builder.AppendLine("<table>");
   foreach(var datum in momenten.Select(m => string.Format("<tr><th style=\"text-align: left;\">{0}</th><td>{1} - {2}</td></tr>", m.Datum, m.Begintijd, m.Eindtijd))){
     builder.AppendLine(datum);
   }
   builder.AppendLine("</table>");
   return builder.ToString();
 }
    public DataManager()
    {
        mDataDoc.Load(@"./Assets/Code/Resources/SceneBreakdown.xml");
        if (mDataDoc.ChildNodes.Count != 1)
        {
            Debug.Log("Data file did not load.");
        }

        XmlNode scriptNode = mDataDoc.SelectSingleNode("script");

        TimeSpan totalFilmSpan = TimeSpan.Parse (scriptNode.Attributes.GetNamedItem("filmLength").Value);
        m_Script.totalSpan = totalFilmSpan;
        //TimeSpan prevSceneSpan = TimeSpan.Zero;
        Scene prevScene = new Scene();
        //loop acts and add to script
        XmlNodeList actsNodeList = mDataDoc.SelectNodes("script/act");
        foreach (XmlElement act in actsNodeList)
        {
            Act newAct = new Act();
            newAct.number = Int32.Parse(act.Attributes.GetNamedItem("number").Value);

            //loop scenes and add to act
            XmlNodeList scenesNodeList = act.SelectNodes("scene");

            int momentCounter = 0;

            foreach (XmlElement scene in scenesNodeList)
            {
                Scene newScene = new Scene();
                newScene.number = Int32.Parse(scene.Attributes.GetNamedItem("number").Value);
                newScene.startTime = TimeSpan.Parse(scene.Attributes.GetNamedItem("time").Value);
         		//newScene.totalTime = newScene.startTime - prevSceneSpan;
         		prevScene.totalTime = newScene.startTime - prevScene.startTime;
         		//prevSceneSpan = newScene.startTime;
                //loop moments and add to scene
                XmlNodeList momentsNodeList = scene.SelectNodes("moment");
                foreach (XmlElement moment in momentsNodeList)
                {
                    momentCounter++;
                    string title = moment.Attributes.GetNamedItem("title").Value;
                    string line = moment.Attributes.GetNamedItem("line").Value;
                    string locationAsString = ("0.0, 0.0, 0.0");
                    string durationAsString = "";
                    string sfxName = "";
                    float duration = 0f;
                    Vector3 location = Vector3.zero;

                    if(moment.HasAttribute("duration"))
                    {
                        durationAsString = moment.Attributes.GetNamedItem ("duration").Value;
                        if(!Single.TryParse(durationAsString, out duration))
                            Debug.Log ("XML moment earsing error, duration had invalid format");
                    }

                    if(moment.HasAttribute ("location"))
                    {
                        locationAsString = moment.Attributes.GetNamedItem ("location").Value;
                        location = Vector3Helper.StringToVector3(locationAsString);
                    }

                    if(moment.HasAttribute ("sfx"))
                       sfxName = moment.Attributes.GetNamedItem ("sfx").Value;

                    Moment newMoment = new Moment(title, line, duration, location ,sfxName, momentCounter);
                    newScene.moments.Add(newMoment);
                }
                newAct.scenes.Add(newScene);
                prevScene = newScene;
            }
            m_Script.acts.Add(newAct);
        }
    }
        /// <summary>
        /// Write an app activity to Google using the Google+ API logging that the user
        /// has uploaded a Photo.
        /// </summary>
        /// <param name="user">The PhotoHunt user who uploaded the Photo.</param>
        /// <param name="dbPhoto">The Photo that was just uploaded.</param>
        public void WriteGooglePlusPhotoAppActivity(User user, Photo dbPhoto)
        {
            _authState = CreateState(user.googleAccessToken, user.googleRefreshToken,
                user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt);

            AuthorizationServerDescription description = GoogleAuthenticationServer.Description;
            var provider = new WebServerClient(description);
            provider.ClientIdentifier = CLIENT_ID;
            provider.ClientSecret = CLIENT_SECRET;
            var authenticator =
                new OAuth2Authenticator<WebServerClient>(
                    provider,
                    GetAuthorization)
                {
                    NoCaching = true
                };
            ps = new PlusService(new BaseClientService.Initializer()
            {
                Authenticator = authenticator
            });

            Moment body = new Moment();
            ItemScope target = new ItemScope();

            target.Url = BASE_URL + "photo.aspx?photoId=" + dbPhoto.id;

            body.Target = target;
            body.Type = ADD_ACTIVITY_TYPE;

            MomentsResource.InsertRequest insert =
                new MomentsResource.InsertRequest(ps, body, "me", MomentsResource.Collection.Vault);
            try
            {
                insert.Fetch();
            }
            catch (GoogleApiRequestException gare)
            {
                Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message +
                    "\nThis could happen if the Google+ proxy can't access your server.");
            }
        }
示例#18
0
        static void Main(string[] args)
        {
            //Scopes for use with Google+ API
            // activating Google+ API in console
            // Documentation:  https://developers.google.com/+/api/oauth
            string[] scopes = new string[] {
                PlusService.Scope.PlusLogin,
                PlusService.Scope.UserinfoEmail,
                PlusService.Scope.UserinfoProfile ,"profile" };

            string _client_id = "1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
            string _client_secret = "NDmluNfTgUk6wgmy7cFo64RV";
       // https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com&redirect_uri=http://localhost:15918/authorize/&scope=https://www.googleapis.com/auth/plus.login%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&data-requestvisibleactions=http://schema.org/AddAction
            PlusService service = null;
            UserCredential credential = null;
            try
            {
               
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret },
                                                                                     scopes, 
                                                                                     Environment.UserName,
                                                                                     CancellationToken.None,
                                                                                     new FileDataStore("Daimto.GooglePlusm.Auth.Store")).Result;
            }
            catch (Exception ex)
            {

                
                //If the user hits cancel you wont get access.
                if (ex.InnerException.Message.IndexOf("access_denied") != -1)
                {
                    Console.WriteLine("User declined access");
                    Console.ReadLine();
                    return;
                }
                else
                {
                    Console.WriteLine("Unknown Authentication Error:" + ex.Message);
                    Console.ReadLine();
                    return;
                }
            }

            // Now we create a Google service. All of our requests will be run though this.
            service = new PlusService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Google Plus Sample",  

            });

          
            Moment body = new Moment();
            body.Type = "http://schema.org/AddAction";           
           
            ItemScope itemScope = new ItemScope();
            itemScope.Id = "target-id-1" ;
            itemScope.Type = "http://schema.org/AddAction";
            itemScope.Name = "The Google+ Platform";
            itemScope.Description = "A page that describes just how awesome Google+ is!";
            itemScope.Image = "https://developers.google.com/+/plugins/snippet/examples/thing.png";
            body.Object = itemScope;

            try
            {
                var l = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault);
                l.Execute();
            }
            catch (Exception ex)
            {
                int i = 1;


            }
            // Getting a list of ALL a users public activities.
            IList<Activity> _Activities = DaimtoGooglePlusHelper.GetAllActivities(service, "me");

            foreach (Activity item in _Activities)
            {

                Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems);
            }


            //Just getting an activity that has some comments for the example below.
            Activity withComment = _Activities.Where(x => x.Object.Replies.TotalItems > 0).FirstOrDefault();
            // Getting a list of all the comments for an activity
            IList<Comment> _comments = DaimtoGooglePlusHelper.GetAllComments(service, withComment.Id);
            foreach (Comment item in _comments)
            {

                Console.WriteLine("Comment " + item.Actor.DisplayName + " Plus 1s: " + item.Plusoners.TotalItems);
            }

            //Listing of all the people the user has circled.
            IList<Person> people = DaimtoGooglePlusHelper.GetAllPeople(service, "me");


            Console.ReadLine();

        }
 public bool ContainsMoment(Moment moment)
 {
     return moments.Contains (moment);
 }
    private DateTime? ParseDateTime(Moment moment, Func<Moment, string> datumSelector, Func<Moment, string> tijdSelector)
    {
      if(moment != null)
      {
        try
        {
          var datum = datumSelector(moment);
          var tijd = tijdSelector(moment);

          if(datum.Length == 10 && tijd.Length == 5)
          {
            return new DateTime(int.Parse(datum.Substring(0, 4)), int.Parse(datum.Substring(5, 2)), int.Parse(datum.Substring(8, 2)),
              int.Parse(tijd.Substring(0, 2)), int.Parse(tijd.Substring(3, 2)), 0).ToUniversalTime();
          }
        }
        catch
        {
          return null;
        }
      }

      return null;
    }
示例#21
0
        private void POstGooglePlus(UserCredential credential)
        {
            PlusService service = new PlusService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });

            Moment body = new Moment();
            body.Type = "http://schema.org/AddAction";

            ItemScope itemScope = new ItemScope();
            itemScope.Id = "target-id-1";
            itemScope.Type = "http://schema.org/AddAction";
            itemScope.Name = "The Google+ Platform";
            itemScope.Description = "A page that describes just how awesome Google+ is!";
            itemScope.Image = "https://developers.google.com/+/plugins/snippet/examples/thing.png";
            body.object__ = itemScope;

            var l = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault);
            l.Execute();

            PeopleResource.GetRequest personRequest = service.People.Get("me");
            Person _me = personRequest.Execute();
        }
示例#22
0
        private static void Run()
        {
            UserCredential credential;

            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = secrets,
                Scopes = new[] { PlusService.Scope.PlusLogin }
            };
            var flow = new AAGoogleAuthorizationCodeFlow(initializer);
            credential = new AuthorizationCodeInstalledApp(flow, new LocalServerCodeReceiver()).AuthorizeAsync
                ("user", CancellationToken.None).Result;

            // Create the service.
            var service = new PlusService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Gus API",
            });

            Moment body = new Moment();
            ItemScope target = new ItemScope();
            target.Url = "https://developers.google.com/+/web/snippet/examples/widget";
            target.Image = "http://picpaste.com/pics/001.1437292069.jpg";
            //target.Type = "http://schema.org/Thing";
            target.Description = "The description for the action";
            target.Name = "An example of add activity";
            body.Target = target;
            body.Type = "http://schemas.google.com/AddActivity";

            //PeopleResource.GetRequest personRequest = service.People.Get("me");
            //Person _me = personRequest.Execute();

            MomentsResource.InsertRequest insert =

                service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault);

            //new MomentsResource.InsertRequest(
            //    service,
            //    body,
            //    "me",
            //    MomentsResource.InsertRequest.CollectionEnum.Vault);

            Moment wrote = insert.Execute();

            MomentsResource.ListRequest ls = service.Moments.List("me", MomentsResource.ListRequest.CollectionEnum.Vault);
            MomentsFeed feeds = ls.Execute();
        }
示例#23
0
        //****************************************************************************************************
		public VarBase Perform(ArgList al) {
			Namespace ns = new Namespace(InterprEnvironment.Instance.CurrentNamespace);
			ns["result"] = new IntVar(0);
			int argc = m_args.Count;
			if (al.Count != argc)
				throw new CalcException("Ќеверное число параметров");
			al.Reset();
			for (int i = 0; i < argc; i++) {
				ns[m_args[i] as System.String] = al.Get();
			}
			InterprEnvironment.Instance.CurrentNamespace = ns;
			Moment moment = new Moment(this);
			if (m_count > 1) {
				try {
					moment.Run();
				}
				catch (SyntaxErrorException ex) {
					throw ex;
				}
				catch (CalcException ex) {
					throw new CalcException("ќшибка в функции " + m_name + "[] в строке " + (moment.Pos + 1) + " : " + ex.Message);
				}
			}
			VarBase res = ns["result"];
			InterprEnvironment.Instance.CurrentNamespace = ns.PreviousNamespace;
			if (res == null)
				throw new CalcException("ќшибка в функции " + m_name + "[] : переменна¤ result не определена на момент выхода");
			return res;
		}
示例#24
0
        public Moment WriteDemoMoment()
        {
            Moment body = new Moment();
            ItemScope target = new ItemScope();

            target.Id = "replacewithuniqueforaddtarget";
            target.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
            target.Type = "";
            target.Description = "The description for the activity";
            target.Name = "An example of add activity";

            body.Target = target;
            body.Type = "http://schemas.google.com/AddActivity";

            MomentsResource.InsertRequest insert =
                new MomentsResource.InsertRequest(
                    plusService,
                    body,
                    "me",
                    MomentsResource.Collection.Vault);
            Moment m = insert.Fetch();
            return m;
        }
        /// <summary>
        /// Writes a Google+ App Activity to Google logging that the user has voted on a PhotoHunt
        /// photo.
        /// </summary>
        /// <param name="user">The user who has voted.</param>
        /// <param name="voteTarget">The photo the user has voted on.</param>
        public void WriteGooglePlusVoteAppActivity(User user, Photo voteTarget)
        {
            // Write an app activity for the vote.
            // Set the auth state in a the superclass for the authorization call.
            _authState = CreateState(user.googleAccessToken, user.googleRefreshToken,
                user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt);

            AuthorizationServerDescription description =
                GoogleAuthenticationServer.Description;
            var provider = new WebServerClient(description);
            provider.ClientIdentifier = CLIENT_ID;
            provider.ClientSecret = CLIENT_SECRET;
            var authenticator =
                new OAuth2Authenticator<WebServerClient>(
                    provider,
                    GetAuthorization)
                {
                    NoCaching = true
                };
            ps = new PlusService(new BaseClientService.Initializer()
            {
                Authenticator = authenticator
            });

            Moment body = new Moment();
            ItemScope target = new ItemScope();
            ItemScope result = new ItemScope();

            // The target (an image) will be parsed from this URL containing microdata.
            target.Url = BASE_URL + "photo.aspx?photoId=" + voteTarget.id;

            // Just use a static review result.
            result.Type = SCHEMA_REVIEW_TYPE;
            result.Name = "A vote for this PhotoHunt photo.";
            result.Url = target.Url;
            result.Text = "This photo embodies " + voteTarget.themeDisplayName;

            body.Target = target;
            body.Result = result;
            body.Type = REVIEW_ACTIVITY_TYPE;
            MomentsResource.InsertRequest insert =
                new MomentsResource.InsertRequest(
                    ps,
                    body,
                    "me",
                    MomentsResource.Collection.Vault);
            try
            {
                insert.Fetch();
            }
            catch (GoogleApiRequestException gare)
            {
                Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message +
                    "\nThis could happen if the Google+ proxy can't access your server.");
            }
        }