public void Moment_ToStringTest()
        {

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

            moment.ToString().Should().Be("-173.87 lb-in.");
        }
Example #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");
        }
Example #3
0
 internal static void Second(ref Moment moment)
 {
     while (moment.Second >= 60)
     {
         moment.Second = moment.Second - 60;
         moment.Minute++;
     }
 }
Example #4
0
 internal static void Millisecond(ref Moment moment)
 {
     while (moment.Millisecond >= 1000)
     {
         moment.Millisecond = moment.Millisecond - 1000;
         moment.Second++;
     }
 }
Example #5
0
 internal static void Hour(ref Moment moment)
 {
     while (moment.Hour >= 24)
     {
         moment.Hour = moment.Hour - 24;
         moment.Hour++;
     }
 }
Example #6
0
 internal static void Month(ref Moment moment)
 {
     while (moment.Month >= 12)
     {
         moment.Month = moment.Month - 12;
         moment.Year++;
     }
 }
Example #7
0
 internal static void Minute(ref Moment moment)
 {
     while (moment.Minute >= 60)
     {
         moment.Minute = moment.Minute - 60;
         moment.Hour++;
     }
 }
Example #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++;
     }
 }
Example #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);
 }
Example #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);
        }
Example #12
0
        public async Task <List <Media> > GetMediaForMoment(Moment moment)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Softrocket-Api-Key", API_KEY);
            String url = String.Format("{0}/{1}/{2}", BASE_URL, "getMomentMedia", moment.GUID);
            HttpResponseMessage response = await client.GetAsync(url);

            String result = await response.Content.ReadAsStringAsync();

            if (!String.IsNullOrEmpty(result))
            {
                var mediaList = JsonConvert.DeserializeObject <List <Media> > (result);
                return(mediaList);
            }
            return(null);
        }
Example #13
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Order moment: " + Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine("Order status: " + Status);
            sb.AppendLine("Client: " + Client);
            sb.AppendLine("Order items:");

            foreach (OrderItem item in Items)
            {
                sb.AppendLine(item.ToString());
            }

            sb.AppendLine("Total price: $" + Total().ToString("F2", CultureInfo.InvariantCulture));
            return(sb.ToString());
        }
Example #14
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes.ToString());
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString());
            sb.AppendLine(Content);
            sb.AppendLine("Comments:");
            foreach (Comment x in Comments)
            {
                sb.AppendLine(x.ToString());
            }

            return(sb.ToString());
        }
Example #15
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("---------- RESUMO DO PEDIDO -----------");
            sb.AppendLine("Data pedido: " + Moment.ToString("dd/mm/yyyy HH:mm:ss"));
            sb.AppendLine("Status do Pedido: " + Status);
            sb.AppendLine("Cliente: " + Cliente);
            sb.AppendLine("Itens do pedido: ");

            foreach (OrderItem itensPed in Items)
            {
                sb.AppendLine(itensPed.ToString());
            }
            sb.AppendLine("Total price: $" + Total().ToString("F2", CultureInfo.InvariantCulture));
            return(sb.ToString());
        }
Example #16
0
        public void Should_create_a_moment()
        {
            var expectedMoment = new
            {
                User        = UserBuilder.Instance().Build(),
                ElapsedTime = faker.Date.ToString(),
                Picture     = faker.Internet.Url(),
                Reactions   = faker.Random.Number()
            };

            var moment = new Moment(expectedMoment.User,
                                    expectedMoment.ElapsedTime,
                                    expectedMoment.Picture,
                                    expectedMoment.Reactions);

            expectedMoment.ToExpectedObject().ShouldMatch(moment);
        }
Example #17
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments:");
            foreach (Comment comment in Comments)
            {
                sb.AppendLine(comment.Text);
            }

            return(sb.ToString());
        }
Example #18
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("ORDER SUMMARY:");
            sb.AppendLine("Order moment: " + Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine("Order status: " + Status);
            sb.AppendLine("Client: " + Client);
            sb.AppendLine("Order items: ");

            foreach (OrderItem item in Items)
            {
                sb.AppendLine(item.ToString());
            }

            return(sb.ToString());
        }
Example #19
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);
            UIBarButtonItem deleteItem = new UIBarButtonItem(UIBarButtonSystemItem.Trash, delegate {
                UIAlertView alert = new UIAlertView("Delete Moment", "Are you sure you want to delete this moment?", null, "Yes", "No");
                alert.Clicked    += (sender, e) => {
                    if (e.ButtonIndex == 0)
                    {
                        AppDelegate.MomentsManager.DeleteMoment(this.moment);
                        this.moment = null;
                        this.NavigationController.PopViewController(true);
                    }
                };
                alert.Show();
            });

            this.NavigationController.SetToolbarHidden(false, true);
            this.SetToolbarItems(new UIBarButtonItem[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), deleteItem }, true);
            List <String> emojis = new List <string> ();

            emojis.AddRange(EmojiFactory.GetEmojieCodes());
            if (this.moment.Emojis.Count > 0)
            {
                int index = emojis.IndexOf(this.moment.Emojis [0]);
                emojiCollectionView.ScrollToItem(NSIndexPath.FromRowSection(index, 0), UICollectionViewScrollPosition.CenteredHorizontally, false);
            }

            this.indicator                  = new UIActivityIndicatorView(new CGRect(0, 0, 30, 30));
            this.indicator.Color            = this.NavigationController.NavigationBar.TintColor;
            this.indicator.HidesWhenStopped = true;

            this.NavigationItem.RightBarButtonItem = new UIBarButtonItem(this.indicator);
            syncedChanged();
            if (this.moment != null)
            {
                AppDelegate.MomentsManager.SyncMoment(this.moment);
                this.imagesCollectionView.ReloadData();
                this.videosCollectionView.ReloadData();
            }
            this.mapView.Frame = new CGRect(0, 0, this.TableView.Bounds.Width, 120);
            this.Reload();

            AppDelegate.MomentsManager.Synced -= momentsSynced;
            AppDelegate.MomentsManager.Synced += momentsSynced;
        }
Example #20
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Order Moment: " + Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine("Örder Status: " + Status);
            sb.AppendLine("Client Information :" + Client.ToString());
            sb.AppendLine("Order items:");

            foreach (OrderItem item in Items)
            {
                Items.ToString();
            }

            sb.AppendLine("Total Price:" + Total().ToString());

            return(sb.ToString());
        }
Example #21
0
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine(Title);
            builder.Append(Likes);
            builder.Append(" Likes - ");
            builder.AppendLine(Moment.ToString("dd/MM/YYYY HH:mm:ss"));
            builder.AppendLine(Content);
            builder.AppendLine("Comments: ");

            foreach (Comment obj in Comments)
            {
                builder.AppendLine(obj.Text);
            }

            return(builder.ToString());
        }
Example #22
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments:");
            //Percorrer a lista de comentários e adcionar no StringBuilder
            foreach (Comment c in comments)
            {
                sb.AppendLine(c.Text);
            }

            return(sb.ToString());
        }
Example #23
0
        public void arcchr(Moment[] par, Moment res)
        {
            double d = par[0].Real;

            try
            {
                d = Math.Log(d + Math.Sqrt(d * d - 1));
                if (Double.IsNaN(d))
                {
                    PutErr("Гиперболический арккосинус от недопустимого аргумента", res);
                }
                else
                {
                    res.Real = d;
                }
            }
            catch { PutErr("Гиперболический арккосинус от недопустимого аргумента", res); }
        }
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Oder moment: " + Moment.ToString("dd/MM/YYYY HH:mm:ss"));
            builder.AppendLine("Order status: " + Status);
            builder.AppendLine("Client: " + Client);
            builder.AppendLine("Order items: ");

            foreach (OrderItem obj in Items)
            {
                builder.AppendLine(obj.ToString());
            }

            builder.AppendLine("Total price: " + Total().ToString("F2", CultureInfo.InvariantCulture));

            return(builder.ToString());
        }
Example #25
0
        public TimeZoneImplementation ToTimeZoneImplementation(
            AbstractDaylightSavingsAdjustment daylightSavingsAdjustment)
        {
            var effectiveTo = new Moment();

            if (null != Until)
            {
                // TODO: Add proper DST offset..
                effectiveTo = Until.ToMoment(Gmtoff, TimeSpan.Zero);
            }
            // if until is null set this to max moment
            else
            {
                effectiveTo = new Moment(long.MaxValue);
            }

            return(new TimeZoneImplementation(effectiveTo, Gmtoff, daylightSavingsAdjustment, Format));
        }
Example #26
0
        public override string ToString()
        {
            // Utilização do stringBuilder para mostrar os dados convertendo-os pra string
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes -");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments :");
            // Criando um foreach para percorrer os comentarios
            foreach (Comment c in Comments)
            {
                sb.AppendLine(c.Text);
            }
            return(sb.ToString());
        }
Example #27
0
        public override string ToString() //Definir como o post será convertido para string.
        {
            //String builder, faz a montagem do string.
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments:");
            //Percorrer a lista de comentarios
            foreach (Comment c in Comments)
            {
                sb.AppendLine(c.Text);
            }
            return(sb.ToString());
        }
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Order moment: ");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.Append("Order status: ");
            sb.AppendLine(Status.ToString());
            sb.Append("Client: ");
            sb.AppendLine(Client.ToString());
            sb.AppendLine("Order items: ");
            foreach (OrderItem orderItem in Items)
            {
                sb.Append(orderItem.ToString());
            }
            sb.AppendLine(Total().ToString("F2"));
            return(sb.ToString());
        }
Example #29
0
        private void populateDescription()
        {
            sweph.obtainLock(h);
            Moment start = td.AddYears(de.startUT);
            Moment end   = td.AddYears(de.startUT + de.DasaLength);

            sweph.releaseLock(h);
            ZodiacHouse zh = new ZodiacHouse(de.ZHouse);

            if ((int)de.ZHouse != 0)
            {
                this.txtDesc.Text = string.Format("{0} - {1} to {2}", zh, start, end);
            }
            else
            {
                this.txtDesc.Text = string.Format("{0} - {1} to {2}", de.graha, start, end);
            }
        }
Example #30
0
        public void StringArgumentConstructorTest()
        {
            // arrange
            Moment time = new Moment("22:50:23");

            // act
            byte hours           = time.Hours;
            byte minutes         = time.Minutes;
            byte seconds         = time.Seconds;
            byte expectedHours   = 22;
            byte expectedMinutes = 50;
            byte expectedSeconds = 23;

            // assert
            Assert.AreEqual(hours, expectedHours);
            Assert.AreEqual(minutes, expectedMinutes);
            Assert.AreEqual(seconds, expectedSeconds);
        }
Example #31
0
        public void OneArgumentConstructorTest()
        {
            // arrange
            Moment time = new Moment(05);

            // act
            byte hours           = time.Hours;
            byte minutes         = time.Minutes;
            byte seconds         = time.Seconds;
            byte expectedHours   = 5;
            byte expectedMinutes = 0;
            byte expectedSeconds = 0;

            // assert
            Assert.AreEqual(hours, expectedHours);
            Assert.AreEqual(minutes, expectedMinutes);
            Assert.AreEqual(seconds, expectedSeconds);
        }
Example #32
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString("DD/MM/YYYY HH:MM:SS"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments:");

            foreach (Comment c in Comments)
            {
                sb.AppendLine(c.Text);
            }

            return(sb.ToString());
        }
Example #33
0
        public override string ToString()
        {
            StringBuilder summary = new StringBuilder();

            summary.Append("ORDER SUMMARY:");
            summary.Append("\nOrder moment: " + Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            summary.Append("\nOrder status: " + Status);
            summary.Append(Client.ToString());
            summary.Append("\nOrder items:");
            foreach (OrderItem item in Items)
            {
                summary.Append(item.ToString());
                Console.WriteLine();
            }

            summary.Append("\nTotal Price: $" + Total().ToString("F2", CultureInfo.InvariantCulture));
            return(summary.ToString());
        }
Example #34
0
        private string utTimeToString(double ut_event, double ut_sr, double sunrise)
        {
            Moment  m   = this.utToMoment(ut_event);
            HMSInfo hms = new HMSInfo(m.time);

            if (ut_event >= (ut_sr - (sunrise / 24.0) + 1.0))
            {
                if (false == opts.LargeHours)
                {
                    return(string.Format("*{0}:{1:00}", hms.degree, hms.minute));
                }
                else
                {
                    return(string.Format("{0:00}:{1:00}", hms.degree + 24, hms.minute));
                }
            }
            return(string.Format("{0:00}:{1:00}", hms.degree, hms.minute));
        }
Example #35
0
        public override string ToString()
        {
            StringBuilder txt = new StringBuilder();

            txt.AppendLine("Order Summary: ");
            txt.Append("Order Moment: ").AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            txt.Append("Order Status: ").AppendLine(Status.ToString());
            txt.Append("Client: ").AppendLine(Client.ToString());

            foreach (var item in Items)
            {
                txt.AppendLine(item.ToString());
            }

            txt.AppendLine("Total price: $" + Total().ToString("F2", CultureInfo.InvariantCulture));

            return(txt.ToString());
        }
Example #36
0
        public void timediffsdd(Moment[] par, Moment res)
        {
            DateTime m1 = par[1].Date;
            DateTime m2 = par[2].Date;

            try
            {
                switch (par[0].String.ToLower())
                {
                case "мс":
                case "ms":
                    res.Real = m1.Subtract(m2).TotalMilliseconds;
                    break;

                case "секунда":
                case "сек":
                case "second":
                    res.Real = m1.Subtract(m2).TotalSeconds;
                    break;

                case "минута":
                case "мин":
                case "minute":
                    res.Real = m1.Subtract(m2).TotalMinutes;
                    break;

                case "час":
                case "hour":
                    res.Real = m1.Subtract(m2).TotalHours;
                    break;

                case "сут":
                case "сутки":
                case "day":
                    res.Real = m1.Subtract(m2).TotalDays;
                    break;

                default:
                    PutErr("Недопустимые параметры функции РазностьВремен (TimeDiff)", res);
                    break;
                }
            }
            catch { PutErr("Недопустимые параметры функции РазностьВремен (TimeDiff)", res); }
        }
Example #37
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("ORDER SUMMARY: ");
            sb.Append("Order moment: ");
            sb.AppendLine(Moment.ToString("dd/MM/yyyy HH:mm:ss"));
            sb.Append("Order status: " + Status);
            sb.Append("Client: ");
            sb.AppendLine(Client.Name + " (" + Client.Birthday + ") - " + Client.Email);
            sb.AppendLine("Order items:");
            foreach (OrderItem obj in Items)
            {
                sb.AppendLine(obj.ToString());
            }

            sb.AppendLine("Total price: " + Total().ToString("F2", CultureInfo.InvariantCulture));
            return(sb.ToString());
        }
Example #38
0
 //Записывает ошибку text в res, если она не совпадает с предыдущей
 public void PutErr(string text, Moment res)
 {
     if (res.Error != null)
     {
         _errorScalar = res.Error;
     }
     else
     {
         if (_errorScalar != null && _errorScalar.Parent == null && text == _errorScalar.Text)
         {
             res.Error = _errorScalar;
         }
         else
         {
             res.Error    = new ErrorCalc(text, _calc.FullCode);
             _errorScalar = res.Error;
         }
     }
 }
 public PublicationState(IPublication <T> publication, IComputed <T> computed, Moment createdAt, bool isDisposed,
                         TaskSource <Unit> whenInvalidatedSource = default,
                         TaskSource <Unit> whenOutdatedSource    = default)
 {
     if (whenInvalidatedSource.IsEmpty)
     {
         whenInvalidatedSource = TaskSource.New <Unit>(true);
     }
     if (whenOutdatedSource.IsEmpty)
     {
         whenOutdatedSource = TaskSource.New <Unit>(true);
     }
     Publication           = publication;
     CreatedAt             = createdAt;
     IsDisposed            = isDisposed;
     WhenInvalidatedSource = whenInvalidatedSource;
     WhenOutdatedSource    = whenOutdatedSource;
     Computed              = computed;
     computed.Invalidated += _ => WhenInvalidatedSource.TrySetResult(default);
        public async Task SendMomentAsync()
        {
            var user = await AmazonWebService.Instance.GetUserAsync();

            var moment = Moment.Create(user);

            moment.Position = App.Instance.CurrentPosition;
            moment.Address  = App.Instance.CurrentAddress;
            await AmazonWebService.Instance.SaveMomentAsync(moment, image);

            user.SentMomentsCount++;
            await AmazonWebService.Instance.SaveUserAsync(user);

            await LocalDataService.Instance.SaveMomentAsync(moment, image);

            await NavigationService.Instance.ShowMomentListAsync();

            DialogService.ShowSuccess("Moment sent!");
        }
        // Usando a classe StringBuilder para montagem mais eficiente para
        // montar saida de texto para o usuário.
        // Pertence ao Name Space System.Text
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(Title);
            sb.Append(Likes);
            sb.Append(" Likes - ");
            sb.AppendLine(Moment.ToString("dd/mm/yyyy HH:mm:ss"));
            sb.AppendLine(Content);
            sb.AppendLine("Comments: ");

            // Percorre a lista de comentários e passa para o objeto 'sb' instanciado com StringBuider
            // que será chamado pelo programa padrão.
            foreach (Comment c in Comments)
            {
                sb.AppendLine(c.Text);
            }
            return(sb.ToString());
        }
        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");
        }
Example #45
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;
        }
    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;
    }
 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();
 }
        /// <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.");
            }
        }
 public bool ContainsMoment(Moment moment)
 {
     return moments.Contains (moment);
 }
    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);
        }
    }
Example #51
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();
        }
Example #52
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();
        }
Example #53
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;
		}
        /// <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.");
            }
        }
Example #55
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();

        }