public override void DrawAgentGUI(Samples s)
 {
     GUILayout.Label("is Play Services Available: " + PlayServicesAgent.instance.isPlayServicesAvailable(false));
     if (!PlayServicesAgent.instance.isPlayServicesAvailable(false))
     {
         if (GUILayout.Button("Show Error", s.ButtonStyle1)) PlayServicesAgent.instance.isPlayServicesAvailable(true);
     }
     if (PlayServicesAgent.instance.isPlayServicesAvailable(false))
     {
         GUILayout.Label("is Connected: " + PlayServicesAgent.instance.isConnected());
         if (!PlayServicesAgent.instance.isConnected())
         {
             GUILayout.Label("is Connecting: " + PlayServicesAgent.instance.isConnecting());
             if (GUILayout.Button("Connect", s.ButtonStyle1)) PlayServicesAgent.instance.Connect();
         } else
         {
             if (GUILayout.Button("Show Leaderboards", s.ButtonStyle1))
                 PlayServicesAgent.instance.ShowLeaderboards();
             if (GUILayout.Button("Show Achievements", s.ButtonStyle1))
                 PlayServicesAgent.instance.ShowAchievements();
             if (GUILayout.Button("Submit Score", s.ButtonStyle1))
                 PlayServicesAgent.instance.SubmitScore("CgkI-eHf1dcFEAIQBg", Random.Range(0, Random.Range(100, 1000)));
             if (GUILayout.Button("Unlock Achievement", s.ButtonStyle1))
                 PlayServicesAgent.instance.UnlockAchievement("CgkI-eHf1dcFEAIQAQ");
             if (GUILayout.Button("Increament Achievement", s.ButtonStyle1))
                 PlayServicesAgent.instance.IncrementAchievement("CgkI-eHf1dcFEAIQBQ", 1);
         }
     }
 }
Exemplo n.º 2
0
    public override void DrawAgentGUI(Samples s)
    {
        GUILayout.Label("Path to public images: " + ScreenshotAgent.instance.GetPublicGalleryPath("Agents"));
        GUILayout.Label("Path to private images: " + ScreenshotAgent.instance.GetPrivateFolderPath("Agents"));

        if (GUILayout.Button("Capture to Gallery", s.ButtonStyle1))
        {
            ScreenshotAgent.instance.SaveScreenshotToPublicGalleryAsync(
                System.DateTime.Now.ToString("MMM-d-yyyy-H-mm-ss") + ".jpg", "Agents",
            delegate(ScreenshotAgent.SaveScreenshotEvent e)
            {

            });
        }

        if (GUILayout.Button("Capture to Private folder", s.ButtonStyle1))
        {
            ScreenshotAgent.instance.SaveScreenshotToPrivateFolderAsync(
                System.DateTime.Now.ToString("MMM-d-yyyy-H-mm-ss") + ".jpg", "Agents",
            delegate(ScreenshotAgent.SaveScreenshotEvent e)
            {

            });
        }
    }
Exemplo n.º 3
0
        public unsafe Samples Resample(Samples source, float targetBitrate)
        {
            var values = source.Values;
            var k = targetBitrate/source.Bitrate;
            var newLength = (int)Math.Round(k*source.Values.Length);
            var resValues = new float[newLength];
            var l = values.Length;

            fixed (float* valuesPtr = values)
            {
                var ptr = valuesPtr;
                for (int i = 0; i < l; i++)
                {
                    var j = (int)(k * i);
                    resValues[j] += *ptr;
                    ptr++;
                }
            }

            l = resValues.Length;

            fixed (float* valuesPtr = resValues)
            {
                var ptr = valuesPtr;
                for (int i = 0; i < l; i++)
                {
                    *ptr *= k;
                    ptr++;
                }
            }

            return new Samples() {Values = resValues, Bitrate = targetBitrate};
        }
 public override void DrawAgentGUI(Samples s)
 {
     if (GUILayout.Button("Query Available Products", s.ButtonStyle1))
     {
         PlayStoreBillingAgent.instacne.QueryAvailableProducts(SampleProducts);
     }
     if (GUILayout.Button("Query Purchased", s.ButtonStyle1))
     {
         PlayStoreBillingAgent.instacne.QueryPurchasedProducts();
     }
     if (GUILayout.Button("Static Purchase Success", s.ButtonStyle1))
     {
     #if USE_BILLING_ON_ANDROID
         PlayStoreBillingAgent.instacne.PurchaseProduct(PlayStoreBillingAgent.ReservedID_Purchased);
     #endif
     }
     if (GUILayout.Button("Static Purchase Failed", s.ButtonStyle1))
     {
     #if USE_BILLING_ON_ANDROID
         PlayStoreBillingAgent.instacne.PurchaseProduct(PlayStoreBillingAgent.ReservedID_ItemUnavailable);
     #endif
     }
     if (GUILayout.Button("Make Real Purchase", s.ButtonStyle1))
     {
         PlayStoreBillingAgent.instacne.PurchaseProduct(SamplePurchasID);
     }
 }
Exemplo n.º 5
0
    public override void DrawAgentGUI(Samples s)
    {
        if (SampleBannerID == 0)
        {
            if (GUILayout.Button("Create New Banner", s.ButtonStyle1))
            {
                if (SampleBannerID == 0)
                {
                    SampleBannerID = AdmobAgent.instance.CreateBanner(AdmobAgent.AdmobBannerSize.SmartBanner, BannerUID,
                    delegate(AdmobAgent.AdmobEvent e, int width, int height, string error)
                    {
                        Debug.Log("Admob Banner Event: " + e + " >>> Width: " + width + " >>> height: " + height );
                    });
                } else
                    AdmobAgent.instance.RefreshBanner(SampleBannerID);

            }
        } else
        {
            GUILayout.Label("is Banner Received Ad: " + AdmobAgent.instance.GetBanner(SampleBannerID).AdLoaded);
            if (AdmobAgent.instance.GetBanner(SampleBannerID).AdLoaded)
            {
                if (GUILayout.Button("Show/Hide Banner", s.ButtonStyle1))
                {
                    AdmobAgent.instance.SetBannerVisibility(SampleBannerID, !AdmobAgent.instance.isBannerVisible(SampleBannerID));
                }
                if (GUILayout.Button("Move Banner", s.ButtonStyle1))
                {
                    AdmobAgent.instance.SetBannerPosition(SampleBannerID, 0, Random.Range(0, 100));
                }
                if (GUILayout.Button("Refresh Ad", s.ButtonStyle1))
                {
                    AdmobAgent.instance.RefreshBanner(SampleBannerID);
                }
                if (GUILayout.Button("Destroy Banner", s.ButtonStyle1))
                {
                    AdmobAgent.instance.DestroyBanner(ref SampleBannerID);
                }
            }
            GUILayout.Space(5);
            if (GUILayout.Button("Request Fullscreen Banner", s.ButtonStyle1))
            {
                isFullscreenBannerLoaded = false;
                AdmobAgent.instance.RequestFullscreenAd(BannerUID);
            }
            if (isFullscreenBannerLoaded)
            {
                if (GUILayout.Button("Show Fullscreen Banner", s.ButtonStyle1))
                {
                    isFullscreenBannerLoaded = false;
                    AdmobAgent.instance.ShowFullscreenAd();
                }
            }
        }
    }
Exemplo n.º 6
0
    public override void DrawAgentGUI(Samples s)
    {
        GUILayout.Label("is Session Open: " + FacebookAgent.instance.isSessionOpened());
        GUILayout.Label("Session State: " + FacebookAgent.instance.getSessionState());
        if (!FacebookAgent.instance.isSessionOpened())
        {
            if (GUILayout.Button("Open For Read", s.ButtonStyle1))
            {
                FacebookAgent.instance.OpenForRead(new string[] { "email" }, null);
            }
            if (GUILayout.Button("Open For Publish", s.ButtonStyle1))
            {
                FacebookAgent.instance.OpenForPublish(new string[] { "publish_actions" }, null);
            }
        } else
        {
            GUILayout.Label("Session Control");
            if (GUILayout.Button("Close", s.ButtonStyle1))
            {
                FacebookAgent.instance.Close();
            }
            if (GUILayout.Button("Close And Clear", s.ButtonStyle1))
            {
                FacebookAgent.instance.CloseAndClear();
            }
            GUILayout.Label("Permissions");
            GUILayout.Label("Publish permission: " + FacebookAgent.instance.hasPublishPermission());
            GUILayout.Label("Email permission: " + FacebookAgent.instance.hasPermission("email"));
            if (!FacebookAgent.instance.hasPermission("email"))
            {
                if (GUILayout.Button("Request New Read Permission", s.ButtonStyle1))
                {
                    FacebookAgent.instance.RequestNewReadPermission(new string[] { "email" },
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });
                }
            } else
            {
                GUILayout.Label("Read");
                if (GUILayout.Button("Request Me", s.ButtonStyle1))
                {
                    FacebookAgent.instance.ExecuteMeRequest(
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });
                }
                if (GUILayout.Button("Request My Friends", s.ButtonStyle1))
                {
                    FacebookAgent.instance.ExecuteMyFriendsRequest(
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });
                }
            }
            if (!FacebookAgent.instance.hasPublishPermission())
            {
                if (GUILayout.Button("Request New Publish Permission", s.ButtonStyle1))
                {
                    FacebookAgent.instance.RequestNewPublishPermission(new string[] { "publish_actions" },
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });
                }
            } else
            {
                GUILayout.Label("Publish");
                if (GUILayout.Button("Request Photo upload", s.ButtonStyle1))
                {
                    FacebookAgent.instance.ExecuteUploadPhotoRequest("This is a test", UploadPhoto,
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });
                }
                if (GUILayout.Button("Request Status update", s.ButtonStyle1))
                {
                    FacebookAgent.instance.ExecuteStatusUpdateRequest(
                    FacebookBundle.CreateBundle("Name", "Caption goes here", "Message goes here", "http://www.nemo-games.com", ""),
                    delegate(FacebookAgent.FacebookRequestEvent e, string error)
                    {
                        Debug.Log("Request Result: " + e + " > error? " + error);
                    });

                }
                if (GUILayout.Button("Request Graph path", s.ButtonStyle1))
                {

                }
                if (GUILayout.Button("Show Feed dialog", s.ButtonStyle1))
                {
                    FacebookAgent.instance.ShowFeedDialog(
                    FacebookBundle.CreateBundle("Name", "Caption goes here", "Message goes here", "http://www.nemo-games.com", ""),
                    delegate(FacebookAgent.FacebookDialogEvent e, string error)
                    {
                        Debug.Log("Dialog Result: " + e + " > error? " + error);
                    });
                }
            }
        }
    }
Exemplo n.º 7
0
        private async Task CreateFile(string studyInstanceUid, string seriesInstanceUid, string sopInstanceUid)
        {
            DicomFile dicomFile1 = Samples.CreateRandomDicomFile(studyInstanceUid, seriesInstanceUid, sopInstanceUid);

            await _client.StoreAsync(new[] { dicomFile1 }, studyInstanceUid);
        }
Exemplo n.º 8
0
 public override string ToString()
 {
     return(Id.ToString() + ": " + Samples.ToString() + " samples, " + SamplesPerSecond.ToString() + " samples/sec, size: " + RoundSize.ToString());
 }
Exemplo n.º 9
0
        public async Task GivenANonexistentResource_WhenUpsertingWithCreateDisabled_ThenAMethodNotAllowedExceptionIsThrown()
        {
            await SetAllowCreateForOperation(
                false,
                async() =>
            {
                var ex = await Assert.ThrowsAsync <MethodNotAllowedException>(() => Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight")));

                Assert.Equal(Resources.ResourceCreationNotAllowed, ex.Message);
            });
        }
Exemplo n.º 10
0
        protected override async Task OnInitializedAsync()
        {
            // Test case #1
            // Create resources that directly referenced by the Patient resource
            Organization = await TestFhirClient.CreateAsync(Samples.GetJsonSample <Organization>("Organization"));

            string organizationReference = $"Organization/{Organization.Id}";

            // Create Patient resource
            Patient patientToCreate = Samples.GetJsonSample <Patient>("Patient-f001");

            patientToCreate.ManagingOrganization.Reference = organizationReference;
            patientToCreate.GeneralPractitioner            = new List <ResourceReference>
            {
                new(organizationReference),
            };
            Patient = await TestFhirClient.CreateAsync(patientToCreate);

            string patientReference = $"Patient/{Patient.Id}";

            // Create resources that references the Patient resource
            Device deviceToCreate = Samples.GetJsonSample <Device>("Device-d1");

            deviceToCreate.Patient = new ResourceReference(patientReference);
            Device = await TestFhirClient.CreateAsync(deviceToCreate);

            // Create Patient compartment resources
            Observation observationToCreate = Samples.GetJsonSample <Observation>("Observation-For-Patient-f001");

            observationToCreate.Subject.Reference = patientReference;
            Observation = await TestFhirClient.CreateAsync(observationToCreate);

            Encounter encounterToCreate = Samples.GetJsonSample <Encounter>("Encounter-For-Patient-f001");

            encounterToCreate.Subject.Reference = patientReference;
            Encounter = await TestFhirClient.CreateAsync(encounterToCreate);

            Appointment appointmentToCreate = Samples.GetJsonSample <Appointment>("Appointment");

            appointmentToCreate.Participant = new List <Appointment.ParticipantComponent>
            {
                new()
                {
                    Actor = new ResourceReference(patientReference),
                },
            };
            Appointment = await TestFhirClient.CreateAsync(appointmentToCreate);

            // Test case #2
            // Create resources for a non-existent patient
            patientToCreate.Id = "non-existent-patient-id";
            NonExistentPatient = await TestFhirClient.CreateAsync(patientToCreate);

            patientReference = $"Patient/{NonExistentPatient.Id}";

            deviceToCreate.Patient     = new ResourceReference(patientReference);
            DeviceOfNonExistentPatient = await TestFhirClient.CreateAsync(deviceToCreate);

            observationToCreate.Subject.Reference = patientReference;
            ObservationOfNonExistentPatient       = await TestFhirClient.CreateAsync(observationToCreate);

            await TestFhirClient.DeleteAsync(NonExistentPatient);
        }
Exemplo n.º 11
0
    void Brush(Vector2 p1, Vector2 p2)
    {
        NumSamples = AntiAlias;
        if (p2 == Vector2.zero)
        {
            p2 = p1;
        }

        PaintLine(p1, p2, brush.width, col, brush.hardness, baseTex);
        baseTex.Apply();
    }
Exemplo n.º 12
0
        protected override InputConfiguration CreateInputConfiguration()
        {
            var inputConfiguration = new InputConfiguration();

            // Keyboard
            inputConfiguration.AddDigitalButton("Back").Assign(KeyboardKeys.Escape)
                //.MapClickTo(gt => this.screenNavigation.Exit());
                .MapClickTo(gt => this.Exit());

            inputConfiguration.AddDigitalButton("GotoSandbox").Assign(KeyboardKeys.D1)
                .MapClickTo(gt => this.LaunchSandboxSample());

            inputConfiguration.AddDigitalButton("GotoShootEmUp").Assign(KeyboardKeys.D2)
                .MapClickTo(gt => this.LaunchShootEmUpSample());

            inputConfiguration.AddDigitalButton("GotoTiled").Assign(KeyboardKeys.D3)
                .MapClickTo(gt => this.LaunchTiledSample());

            inputConfiguration.AddDigitalButton("GotoTouch").Assign(KeyboardKeys.D4)
                .MapClickTo(gt => this.LaunchTouchSample());

            // Mouse
            Func<RectangleHit, Samples> hitToSampleFunc = hit =>
            {
                if (hit != null)
                {
                    if (hit.RectangleElement == this.sandboxRectangle) return Samples.Sandbox;
                    if (hit.RectangleElement == this.shootEmUpRectangle) return Samples.ShootEmUp;
                    if (hit.RectangleElement == this.tiledRectangle) return Samples.Tiled;
                    if (hit.RectangleElement == this.touchRectangle) return Samples.Touch;
                }

                return Samples.None;
            };

            inputConfiguration.CreateMouseTracking(this.Camera).OnUpdate((mt, e) =>
            {
                this.mouseState = mt;

                var hit = this.Scene.GetHits(this.mouseState.AbsolutePosition, this.Camera).OfType<RectangleHit>().FirstOrDefault();
                this.hoveringSample = hitToSampleFunc(hit);
            });

            inputConfiguration.AddDigitalButton("MouseSelection").Assign(MouseButtons.Left).MapClickTo(elapse =>
            {
                var hit = this.Scene.GetHits(this.mouseState.AbsolutePosition, this.Camera).OfType<RectangleHit>().FirstOrDefault();
                var hitSample = hitToSampleFunc(hit);

                switch (hitSample)
                {
                    case Samples.Sandbox:
                        this.LaunchSandboxSample();
                        break;
                    case Samples.ShootEmUp:
                        this.LaunchShootEmUpSample();
                        break;
                    case Samples.Tiled:
                        this.LaunchTiledSample();
                        break;
                    case Samples.Touch:
                        this.LaunchTouchSample();
                        break;
                }
            });

            // Touch
            inputConfiguration.CreateTouchTracking(this.Camera).OnUpdate((ts, gt) =>
            {
                this.touchState = ts;

                if (this.touchState.Touches.Any())
                {
                    var hit = this.touchState.Touches
                        .SelectMany(t => this.Scene.GetHits(t.Position, this.Camera))
                        .OfType<RectangleHit>().FirstOrDefault();

                    this.hoveringSample = hitToSampleFunc(hit);
                }
            });

            inputConfiguration.AddEvent("TouchSelection").Assign(TouchGestureType.Tap).MapTo(gt =>
            {
                var hit = this.Scene.GetHits(this.touchState.CurrentGesture.Position, this.Camera)
                    .OfType<RectangleHit>().FirstOrDefault();

                var hitSample = hitToSampleFunc(hit);

                switch (hitSample)
                {
                    case Samples.Sandbox:
                        this.LaunchSandboxSample();
                        break;
                    case Samples.ShootEmUp:
                        this.LaunchShootEmUpSample();
                        break;
                    case Samples.Tiled:
                        this.LaunchTiledSample();
                        break;
                    case Samples.Touch:
                        this.LaunchTouchSample();
                        break;
                }
            });

            return inputConfiguration;
        }
Exemplo n.º 13
0
        public async Task GivenAnUnsupportedResourceType_WhenPostingToHttp_TheServerShouldRespondWithANotFoundResponse()
        {
            FhirException ex = await Assert.ThrowsAsync <FhirException>(() => Client.CreateAsync("NotObservation", Samples.GetDefaultObservation().ToPoco <Observation>()));

            Assert.Equal(HttpStatusCode.NotFound, ex.StatusCode);
        }
Exemplo n.º 14
0
 private void LaunchTiledSample()
 {
     this.currentSample = Samples.Tiled;
     this.screenNavigation.NavigateTo<TiledScreen>();
 }
Exemplo n.º 15
0
 private void LaunchTouchSample()
 {
     this.currentSample = Samples.Touch;
     this.screenNavigation.NavigateTo<TouchScreen>();
 }
Exemplo n.º 16
0
 private void LaunchShootEmUpSample()
 {
     this.currentSample = Samples.ShootEmUp;
     this.screenNavigation.NavigateTo<ShootEmUpScreen>();
 }
Exemplo n.º 17
0
 private void LaunchSandboxSample()
 {
     this.currentSample = Samples.Sandbox;
     this.screenNavigation.NavigateTo<SandboxScreen>();
 }
Exemplo n.º 18
0
 void Eraser(Vector2 p1, Vector2 p2)
 {
     NumSamples = AntiAlias;
     if (p2 == Vector2.zero)
     {
         p2 = p1;
     }
     PaintLine(p1, p2, eraser.width, Color.white, eraser.hardness, baseTex);
     baseTex.Apply();
 }
        public void GivenABundleRequestWithANonBundleResourceRequest_WhenExecutingAnAction_ThenValuesShouldBeSetOnFhirRequestContext()
        {
            _actionExecutingContext.ActionArguments.Add(KnownActionParameterNames.Bundle, Samples.GetDefaultObservation().ToPoco <Observation>());

            ExecuteAndValidateFilter(AuditEventSubType.BundlePost, AuditEventSubType.BundlePost);
        }
Exemplo n.º 20
0
    void Update()
    {
        Rect imgRect = new Rect(5 + 100, 5, baseTex.width * zoom, baseTex.height * zoom);
        Vector2 mouse = Input.mousePosition;
        mouse.y = Screen.height - mouse.y;

        if (Input.GetKeyDown("t"))
        {
            test();
        }
        if (Input.GetKeyDown("mouse 0"))
        {

            if (imgRect.Contains(mouse))
            {
                if (tool == Tool.Vector)
                {
                    var m2 = mouse - new Vector2(imgRect.x, imgRect.y);
                    m2.y = imgRect.height - m2.y;
                    var bz = new ArrayList(BezierPoints);
                    bz.Add(new BezierPoint(m2, m2 - new Vector2(50, 10), m2 + new Vector2(50, 10)));
                    BezierPoints = (BezierPoint[])bz.ToArray();
                    DrawBezier(BezierPoints, lineTool.width, col, baseTex);
                }

                dragStart = mouse - new Vector2(imgRect.x, imgRect.y);
                dragStart.y = imgRect.height - dragStart.y;
                dragStart.x = Mathf.Round(dragStart.x / zoom);
                dragStart.y = Mathf.Round(dragStart.y / zoom);
                //LineStart (mouse - Vector2 (imgRect.x,imgRect.y));

                dragEnd = mouse - new Vector2(imgRect.x, imgRect.y);
                dragEnd.x = Mathf.Clamp(dragEnd.x, 0, imgRect.width);
                dragEnd.y = imgRect.height - Mathf.Clamp(dragEnd.y, 0, imgRect.height);
                dragEnd.x = Mathf.Round(dragEnd.x / zoom);
                dragEnd.y = Mathf.Round(dragEnd.y / zoom);
            }
            else
            {
                dragStart = Vector3.zero;
            }

        }
        if (Input.GetKey("mouse 0"))
        {
            if (dragStart == Vector2.zero)
            {
                return;
            }
            dragEnd = mouse - new Vector2(imgRect.x, imgRect.y);
            dragEnd.x = Mathf.Clamp(dragEnd.x, 0, imgRect.width);
            dragEnd.y = imgRect.height - Mathf.Clamp(dragEnd.y, 0, imgRect.height);
            dragEnd.x = Mathf.Round(dragEnd.x / zoom);
            dragEnd.y = Mathf.Round(dragEnd.y / zoom);

            if (tool == Tool.Brush)
            {

                Debug.Log("brush");
                Brush(dragEnd, preDrag);
            }
            if (tool == Tool.Eraser)
            {
                Debug.Log("Eraser");
                Eraser(dragEnd, preDrag);
            }

        }
        if (Input.GetKeyUp("mouse 0") && dragStart != Vector2.zero)
        {
            if (tool == Tool.Line)
            {
                dragEnd = mouse - new Vector2(imgRect.x, imgRect.y);
                dragEnd.x = Mathf.Clamp(dragEnd.x, 0, imgRect.width);
                dragEnd.y = imgRect.height - Mathf.Clamp(dragEnd.y, 0, imgRect.height);
                dragEnd.x = Mathf.Round(dragEnd.x / zoom);
                dragEnd.y = Mathf.Round(dragEnd.y / zoom);
                Debug.Log("Draw Line");
                NumSamples = AntiAlias;
                if (stroke.enabled)
                {
                    baseTex = DrawLine(dragStart, dragEnd, lineTool.width, col, baseTex, true, col2, stroke.width);
                }
                else
                {
                    baseTex = DrawLine(dragStart, dragEnd, lineTool.width, col, baseTex);
                }
            }
            dragStart = Vector2.zero;
            dragEnd = Vector2.zero;
        }
        preDrag = dragEnd;
    }
Exemplo n.º 21
0
        private void createTicks()
        {
            if (TickDistance == 0)
            {
                return;
            }

            var length       = Curve.Distance;
            var tickDistance = Math.Min(TickDistance, length);
            var spanDuration = length / Velocity;

            var minDistanceFromEnd = Velocity * 0.01;

            AddNested(new Fruit
            {
                Samples     = Samples,
                ComboColour = ComboColour,
                StartTime   = StartTime,
                X           = X
            });

            for (var span = 0; span < this.SpanCount(); span++)
            {
                var spanStartTime = StartTime + span * spanDuration;
                var reversed      = span % 2 == 1;

                for (var d = tickDistance; d <= length; d += tickDistance)
                {
                    if (d > length - minDistanceFromEnd)
                    {
                        break;
                    }

                    var timeProgress     = d / length;
                    var distanceProgress = reversed ? 1 - timeProgress : timeProgress;

                    var lastTickTime = spanStartTime + timeProgress * spanDuration;
                    AddNested(new Droplet
                    {
                        StartTime   = lastTickTime,
                        ComboColour = ComboColour,
                        X           = Curve.PositionAt(distanceProgress).X / CatchPlayfield.BASE_WIDTH,
                        Samples     = new List <SampleInfo>(Samples.Select(s => new SampleInfo
                        {
                            Bank   = s.Bank,
                            Name   = @"slidertick",
                            Volume = s.Volume
                        }))
                    });
                }

                double tinyTickInterval = tickDistance / length * spanDuration;
                while (tinyTickInterval > 100)
                {
                    tinyTickInterval /= 2;
                }

                for (double t = 0; t < spanDuration; t += tinyTickInterval)
                {
                    double progress = reversed ? 1 - t / spanDuration : t / spanDuration;

                    AddNested(new TinyDroplet
                    {
                        StartTime   = spanStartTime + t,
                        ComboColour = ComboColour,
                        X           = Curve.PositionAt(progress).X / CatchPlayfield.BASE_WIDTH,
                        Samples     = new List <SampleInfo>(Samples.Select(s => new SampleInfo
                        {
                            Bank   = s.Bank,
                            Name   = @"slidertick",
                            Volume = s.Volume
                        }))
                    });
                }

                AddNested(new Fruit
                {
                    Samples     = Samples,
                    ComboColour = ComboColour,
                    StartTime   = spanStartTime + spanDuration,
                    X           = Curve.PositionAt(reversed ? 0 : 1).X / CatchPlayfield.BASE_WIDTH
                });
            }
        }
Exemplo n.º 22
0
        // play a file node (a single sample)
        private void PlayFile(Samples sample)
        {
            // closed high hat should always stop an open high hat
            // so we cut off the open high hat if we're playing the closed one
            // Classic drum machines do this by putting both on the same channel
            if (sample == Samples.ClosedHighHat)
                _fileNodes[(int)Samples.OpenHighHat].Stop();

            // Make sure to reset and start up the node
            _fileNodes[(int)sample].Reset();
            _fileNodes[(int)sample].Start();

            BlamePete();
        }
Exemplo n.º 23
0
 public override void DrawAgentGUI(Samples s)
 {
     GUILayout.Label("Flurry is integrated already. Nothing needs to be done.");
 }
Exemplo n.º 24
0
 static void Main(string[] args)
 {
     Samples.Sample1();
 }
Exemplo n.º 25
0
        public async Task GivenANewSearchParam_WhenReindexingComplete_ThenResourcesSearchedWithNewParamReturned()
        {
            var patientName = Guid.NewGuid().ToString().ComputeHash().Substring(28).ToLower();
            var patient     = new Patient {
                Name = new List <HumanName> {
                    new HumanName {
                        Family = patientName
                    }
                }
            };
            var searchParam = Samples.GetJsonSample <SearchParameter>("SearchParameter");

            searchParam.Code = "fooCode";

            // POST a new patient
            FhirResponse <Patient> expectedPatient = await Client.CreateAsync(patient);

            // POST a second patient to show it is filtered and not returned when using the new search parameter
            await Client.CreateAsync(Samples.GetJsonSample <Patient>("Patient"));

            // POST a new Search parameter
            FhirResponse <SearchParameter> searchParamPosted = null;

            try
            {
                searchParamPosted = await Client.CreateAsync(searchParam);
            }
            catch (Exception)
            {
                // if the SearchParameter exists, we should delete it and recreate it
                var searchParamBundle = await Client.SearchAsync(ResourceType.SearchParameter, $"url={searchParam.Url}");

                if (searchParamBundle.Resource?.Entry[0] != null && searchParamBundle.Resource?.Entry[0].Resource.ResourceType == ResourceType.SearchParameter)
                {
                    await DeleteSearchParameterAndVerify(searchParamBundle.Resource?.Entry[0].Resource as SearchParameter);

                    searchParamPosted = await Client.CreateAsync(searchParam);
                }
                else
                {
                    throw;
                }
            }

            Uri reindexJobUri;

            try
            {
                // Start a reindex job
                (_, reindexJobUri) = await Client.PostReindexJobAsync(new Parameters());
            }
            catch (FhirException ex) when(ex.StatusCode == HttpStatusCode.BadRequest && ex.Message.Contains("not enabled"))
            {
                Skip.If(!_fixture.IsUsingInProcTestServer, "Reindex is not enabled on this server.");
                return;
            }

            await WaitForReindexStatus(reindexJobUri, "Running", "Completed");

            FhirResponse <Parameters> reindexJobResult = await Client.CheckReindexAsync(reindexJobUri);

            Parameters.ParameterComponent param = reindexJobResult.Resource.Parameter.FirstOrDefault(p => p.Name == "searchParams");

            Assert.Contains("http://hl7.org/fhir/SearchParameter/Patient-foo", param.Value.ToString());

            await WaitForReindexStatus(reindexJobUri, "Completed");

            // When job complete, search for resources using new parameter
            await ExecuteAndValidateBundle($"Patient?{searchParam.Code}:exact={patientName}", expectedPatient.Resource);

            // Clean up new SearchParameter
            await DeleteSearchParameterAndVerify(searchParamPosted.Resource);
        }
Exemplo n.º 26
0
 private void OnSwitchStateChangedEvent(Samples.Devices.Fx2.Fx2Device sender, Samples.Devices.Fx2.SwitchStateChangedEventArgs eventArgs)
 {
     UpdateSwitchStateTable(eventArgs.SwitchState);
 }
Exemplo n.º 27
0
    static void Main(string[] args)
    {
        robots   = new List <Robot>();
        samples  = new List <Sample>();
        projects = new List <Project>();

        string[] inputs;
        bool     firstTurn    = true;
        int      projectCount = int.Parse(Console.ReadLine());

        for (int i = 0; i < projectCount; i++)
        {
            inputs = Console.ReadLine().Split(' ');
            int a = int.Parse(inputs[0]);
            int b = int.Parse(inputs[1]);
            int c = int.Parse(inputs[2]);
            int d = int.Parse(inputs[3]);
            int e = int.Parse(inputs[4]);
            projects.Add(new Project(new int[] { a, b, c, d, e }));
        }


        // game loop
        while (true)
        {
            robots.Clear();
            samples.Clear();

            for (int i = 0; i < 2; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                string target     = inputs[0];
                int    eta        = int.Parse(inputs[1]);
                int    score      = int.Parse(inputs[2]);
                int    storageA   = int.Parse(inputs[3]);
                int    storageB   = int.Parse(inputs[4]);
                int    storageC   = int.Parse(inputs[5]);
                int    storageD   = int.Parse(inputs[6]);
                int    storageE   = int.Parse(inputs[7]);
                int    expertiseA = int.Parse(inputs[8]);
                int    expertiseB = int.Parse(inputs[9]);
                int    expertiseC = int.Parse(inputs[10]);
                int    expertiseD = int.Parse(inputs[11]);
                int    expertiseE = int.Parse(inputs[12]);
                Module modTarget  = null;

                switch (target)
                {
                case "START_POS":
                    modTarget = new StartPoint();
                    break;

                case "SAMPLES":
                    modTarget = new Samples();
                    break;

                case "DIAGNOSIS":
                    modTarget = new Diagnosis();
                    break;

                case "MOLECULES":
                    modTarget = new Molecules();
                    break;

                case "LABORATORY":
                    modTarget = new Laboratory();
                    break;

                default:
                    break;
                }

                robots.Add(new Robot(
                               modTarget,
                               eta,
                               score,
                               new int[] { storageA, storageB, storageC, storageD, storageE },
                               new int[] { expertiseA, expertiseB, expertiseC, expertiseD, expertiseE }
                               ));
            }
            inputs = Console.ReadLine().Split(' ');
            int availableA = int.Parse(inputs[0]);
            int availableB = int.Parse(inputs[1]);
            int availableC = int.Parse(inputs[2]);
            int availableD = int.Parse(inputs[3]);
            int availableE = int.Parse(inputs[4]);
            available = new int[] { availableA, availableB, availableC, availableD, availableE };
            int sampleCount = int.Parse(Console.ReadLine());
            for (int i = 0; i < sampleCount; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                int    sampleId      = int.Parse(inputs[0]);
                int    carriedBy     = int.Parse(inputs[1]);
                int    rank          = int.Parse(inputs[2]);
                string expertiseGain = inputs[3];
                int    health        = int.Parse(inputs[4]);
                int    costA         = int.Parse(inputs[5]);
                int    costB         = int.Parse(inputs[6]);
                int    costC         = int.Parse(inputs[7]);
                int    costD         = int.Parse(inputs[8]);
                int    costE         = int.Parse(inputs[9]);

                Sample thisSample = new Sample(
                    sampleId,
                    new int[] { costA, costB, costC, costD, costE },
                    health,
                    rank,
                    expertiseGain);

                switch (carriedBy)
                {
                case -1:
                    samples.Add(thisSample);
                    break;

                case 0:
                    robots[0].samples.Add(thisSample);
                    break;

                case 1:
                    robots[1].samples.Add(thisSample);
                    break;
                }
            }

            Robot myRobot = robots[0];

            Console.Error.WriteLine("Module : " + String.Join(" ", myRobot.target.ToString()));
            Console.Error.WriteLine("Storage (A B C D E) : " + String.Join(" ", myRobot.storage));
            Console.Error.WriteLine("Expert. (A B C D E) : " + String.Join(" ", myRobot.expertise));
            int[] potential = new int[5];
            for (int i = 0; i < 5; i++)
            {
                potential[i] = myRobot.storage[i] + myRobot.expertise[i];
            }

            foreach (Project project in projects)
            {
                Console.Error.WriteLine("Projet " + projects.IndexOf(project) + "  Expertise : " + String.Join(" ", project.expertise));
            }

            Console.Error.WriteLine("");
            Console.Error.WriteLine("=========== SAMPLES ===========");
            Console.Error.WriteLine("");

            Console.Error.WriteLine("Potential (A B C D E) : " + String.Join(" ", potential));
            Console.Error.WriteLine("Available (A B C D E) : " + String.Join(" ", available));
            Console.Error.WriteLine("");

            foreach (Sample sample in myRobot.samples.OrderByDescending(item => item.health))
            {
                Console.Error.WriteLine("Samp Cost (A B C D E) : " + String.Join(" ", sample.cost) + " - Rank " + sample.rank + " - Health : " + sample.health + " - Gain : " + sample.gain.ToString() + " - ID : " + sample.id);
            }

            myRobot.Update();
        }
    }
Exemplo n.º 28
0
        public async Task GivenAResourceAndMalformedProvenanceHeader_WhenPostingToHttp_TheServerShouldRespondSuccessfully()
        {
            var observation = Samples.GetDefaultObservation().ToPoco <Observation>();

            observation.Id = null;
            var exception = await Assert.ThrowsAsync <FhirException>(() => _client.CreateAsync(Samples.GetDefaultObservation().ToPoco <Observation>(), $"identifier={Guid.NewGuid().ToString()}", "Jibberish"));

            Assert.Equal(HttpStatusCode.BadRequest, exception.StatusCode);
        }
 public async Task GivenATransactionBundle_WhenContainsUniqueResources_NoExceptionShouldBeThrown()
 {
     var requestBundle = Samples.GetJsonSample("Bundle-TransactionWithValidBundleEntry");
     await _transactionBundleValidator.ValidateBundle(requestBundle.ToPoco <Hl7.Fhir.Model.Bundle>(), CancellationToken.None);
 }
        public async Task GivenAResource_WhenUpsertingConditionallyWithNoIdAndNoExisting_ThenTheServerShouldReturnTheUpdatedResourceSuccessfully()
        {
            ConditionalUpsertResourceRequest message = SetupConditionalUpdate(SaveOutcomeType.Created, Samples.GetDefaultObservation());

            UpsertResourceResponse result = await _mediator.Send <UpsertResourceResponse>(message);

            Assert.Equal(SaveOutcomeType.Created, result.Outcome.Outcome);
            var deserialized = result.Outcome.RawResourceElement.ToPoco <Observation>(Deserializers.ResourceDeserializer).ToResourceElement();
            await _fhirDataStore.Received().UpsertAsync(Arg.Is <ResourceWrapper>(x => x.ResourceId == deserialized.Id), null, true, true, Arg.Any <CancellationToken>());
        }
Exemplo n.º 31
0
 public async Task GivenANonexistentResource_WhenUpsertingWithCreateDisabledAndIntegerETagHeader_TheServerShouldReturnResourceNotFoundResponse(string versionId)
 {
     await SetAllowCreateForOperation(
         false,
         async() =>
     {
         await Assert.ThrowsAsync <ResourceNotFoundException>(async() =>
                                                              await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId(versionId)));
     });
 }
        public async Task GivenAResource_WhenUpsertingConditionallyWithAnIdAndNoExisting_ThenTheServerShouldReturnTheCreatedResourceSuccessfully()
        {
            string id = Guid.NewGuid().ToString();

            ConditionalUpsertResourceRequest message = SetupConditionalUpdate(SaveOutcomeType.Created, Samples.GetDefaultObservation().UpdateId(id));

            UpsertResourceResponse result = await _mediator.Send <UpsertResourceResponse>(message);

            Assert.Equal(SaveOutcomeType.Created, result.Outcome.Outcome);

            await _fhirDataStore.Received().UpsertAsync(Arg.Is <ResourceWrapper>(x => x.ResourceId == id), null, true, true, Arg.Any <CancellationToken>());
        }
Exemplo n.º 33
0
 public async Task GivenANonexistentResourceAndCosmosDb_WhenUpsertingWithCreateEnabledAndInvalidETagHeader_ThenResourceNotFoundIsThrown()
 {
     await Assert.ThrowsAsync <ResourceNotFoundException>(() => Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId("invalidVersion")));
 }
Exemplo n.º 34
0
 public void AddSample(Sample sample)
 {
     Samples.Add(sample);
 }
Exemplo n.º 35
0
 public override string ToString()
 {
     return(Headroom.ToString() + ", " + Codec.ToString() + ": " + Samples.ToString() + " samples, " + SamplesPerSecond.ToString() + " samples/sec");
 }
Exemplo n.º 36
0
 public void ClearSamples()
 {
     Samples.Clear();
 }
Exemplo n.º 37
0
        public void GivenAResourceWrapper_WhenGettingVersion_TheETagShouldBeUsedWhenVersionIsEmpty()
        {
            var wrapper = Samples.GetJsonSample <FhirCosmosResourceWrapper>("ResourceWrapperNoVersion");

            Assert.Equal("00002804-0000-0000-0000-59f272c60000", wrapper.Version);
        }
Exemplo n.º 38
0
        protected override void CreateNestedHitObjects()
        {
            base.CreateNestedHitObjects();

            var tickSamples = Samples.Select(s => new HitSampleInfo
            {
                Bank   = s.Bank,
                Name   = @"slidertick",
                Volume = s.Volume
            }).ToList();

            SliderEventDescriptor?lastEvent = null;

            foreach (var e in SliderEventGenerator.Generate(StartTime, SpanDuration, Velocity, TickDistance, Path.Distance, this.SpanCount(), LegacyLastTickOffset))
            {
                // generate tiny droplets since the last point
                if (lastEvent != null)
                {
                    double sinceLastTick = e.Time - lastEvent.Value.Time;

                    if (sinceLastTick > 80)
                    {
                        double timeBetweenTiny = sinceLastTick;
                        while (timeBetweenTiny > 100)
                        {
                            timeBetweenTiny /= 2;
                        }

                        for (double t = timeBetweenTiny; t < sinceLastTick; t += timeBetweenTiny)
                        {
                            AddNested(new TinyDroplet
                            {
                                Samples   = tickSamples,
                                StartTime = t + lastEvent.Value.Time,
                                X         = X + Path.PositionAt(
                                    lastEvent.Value.PathProgress + (t / sinceLastTick) * (e.PathProgress - lastEvent.Value.PathProgress)).X / CatchPlayfield.BASE_WIDTH,
                            });
                        }
                    }
                }

                // this also includes LegacyLastTick and this is used for TinyDroplet generation above.
                // this means that the final segment of TinyDroplets are increasingly mistimed where LegacyLastTickOffset is being applied.
                lastEvent = e;

                switch (e.Type)
                {
                case SliderEventType.Tick:
                    AddNested(new Droplet
                    {
                        Samples   = tickSamples,
                        StartTime = e.Time,
                        X         = X + Path.PositionAt(e.PathProgress).X / CatchPlayfield.BASE_WIDTH,
                    });
                    break;

                case SliderEventType.Head:
                case SliderEventType.Tail:
                case SliderEventType.Repeat:
                    AddNested(new Fruit
                    {
                        Samples   = Samples,
                        StartTime = e.Time,
                        X         = X + Path.PositionAt(e.PathProgress).X / CatchPlayfield.BASE_WIDTH,
                    });
                    break;
                }
            }
        }
Exemplo n.º 39
0
        public async Task GivenPatientIdAndSmartAppUrl_WhenLaunchingApp_LaunchSequenceAndSignIn()
        {
            // There is no remote FHIR server. Skip test
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable($"TestEnvironmentUrl{Constants.TestEnvironmentVariableVersionSuffix}")))
            {
                return;
            }

            var options = new ChromeOptions();

            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--incognito");

            // TODO: We are accepting insecure certs to make it practical to run on build systems. A valid cert should be on the build system.
            options.AcceptInsecureCertificates = true;

            using FhirResponse <Patient> response = await _fixture.TestFhirClient.CreateAsync(Samples.GetDefaultPatient ().ToPoco <Patient>());

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Patient patient = response.Resource;

            // VSTS Hosted agents set the ChromeWebDriver Env, locally that is not the case
            // https://docs.microsoft.com/en-us/azure/devops/pipelines/test/continuous-test-selenium?view=vsts#decide-how-you-will-deploy-and-test-your-app
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ChromeWebDriver")))
            {
                Environment.SetEnvironmentVariable("ChromeWebDriver", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            }

            using (var driver = new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver"), options))
            {
                // TODO: This parameter has been set (too) conservatively to ensure that content
                //       loads on build machines. Investigate if one could be less sensitive to that.
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);

                void Advance()
                {
                    while (true)
                    {
                        try
                        {
                            var button = driver.FindElementById("idSIButton9");
                            if (button.Enabled)
                            {
                                button.Click();
                                return;
                            }
                        }
                        catch (StaleElementReferenceException)
                        {
                        }
                    }
                }

                driver.Navigate().GoToUrl(_fixture.SmartLauncherUrl);

                var patientElement = driver.FindElement(By.Id("patient"));
                patientElement.SendKeys(patient.Id);

                var launchButton = driver.FindElement(By.Id("launchButton"));
                if (launchButton.Enabled)
                {
                    launchButton.Click();
                }

                var testUserName     = TestUsers.AdminUser.UserId;
                var testUserPassword = TestUsers.AdminUser.Password;

                // Launcher opens a new tab, switch to it
                driver.SwitchTo().Window(driver.WindowHandles[1]);

                int waitCount = 0;
                while (!driver.Url.StartsWith($"https://login.microsoftonline.com"))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    Assert.InRange(waitCount++, 0, 10);
                }

                driver.FindElementByName("loginfmt").SendKeys(testUserName);
                Advance();

                // We need to add some delay before we start entering the password (to make sure
                // the element is available and we do not miss sending some keys).
                Thread.Sleep(TimeSpan.FromMilliseconds(1000));

                driver.FindElementByName("passwd").SendKeys(testUserPassword);
                Advance();

                // Consent, should only be done if we can find the button
                try
                {
                    // Sleep in case a light box is shown.
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    var button = driver.FindElementById("idSIButton9");
                    Advance();
                }
                catch (NoSuchElementException)
                {
                    // Nothing to do, we are assuming that we are at the SMART App screen.
                }

                var tokenResponseElement = driver.FindElement(By.Id("tokenresponsefield"));
                var tokenResponseText    = tokenResponseElement.GetAttribute("value");

                // It can take some time for the token to appear, we will wait
                waitCount = 0;
                while (string.IsNullOrWhiteSpace(tokenResponseText))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    tokenResponseText = tokenResponseElement.GetAttribute("value");
                    Assert.InRange(waitCount++, 0, 10);
                }

                // Check the token response, should have right audience
                var tokenResponse = JObject.Parse(tokenResponseElement.GetAttribute("value"));
                var jwtHandler    = new JwtSecurityTokenHandler();
                Assert.True(jwtHandler.CanReadToken(tokenResponse["access_token"].ToString()));
                var token = jwtHandler.ReadJwtToken(tokenResponse["access_token"].ToString());
                var aud   = token.Claims.Where(c => c.Type == "aud").ToList();
                Assert.Single(aud);
                var tokenAudience = aud.First().Value;
                Assert.Equal(Environment.GetEnvironmentVariable("TestEnvironmentUrl"), tokenAudience);

                // Check the patient
                var patientResponseElement = driver.FindElement(By.Id("patientfield"));
                var patientResource        = JObject.Parse(patientResponseElement.GetAttribute("value"));
                Assert.Equal(patient.Id, patientResource["id"].ToString());
            }
        }
Exemplo n.º 40
0
        public async Task WhenSubmittingABatch_GivenANonBundleResource_ThenBadRequestIsReturned()
        {
            FhirException ex = await Assert.ThrowsAsync <FhirException>(() => Client.PostBundleAsync(Samples.GetDefaultObservation().ToPoco <Observation>()));

            Assert.Equal(HttpStatusCode.BadRequest, ex.StatusCode);
        }
 public void GivenNormalTransactionRequest_WhenExecutingAnAction_ThenValuesShouldBeSetOnFhirRequestContext()
 {
     _actionExecutingContext.ActionArguments.Add(KnownActionParameterNames.Bundle, Samples.GetDefaultTransaction().ToPoco <Hl7.Fhir.Model.Bundle>());
     ExecuteAndValidateFilter(AuditEventSubType.BundlePost, AuditEventSubType.Transaction);
 }
Exemplo n.º 42
0
        private void createTicks()
        {
            if (TickDistance == 0)
            {
                return;
            }

            var length       = Curve.Distance;
            var tickDistance = Math.Min(TickDistance, length);

            var minDistanceFromEnd = Velocity * 0.01;

            for (var span = 0; span < this.SpanCount(); span++)
            {
                var spanStartTime = StartTime + span * SpanDuration;
                var reversed      = span % 2 == 1;

                for (var d = tickDistance; d <= length; d += tickDistance)
                {
                    if (d > length - minDistanceFromEnd)
                    {
                        break;
                    }

                    var distanceProgress = d / length;
                    var timeProgress     = reversed ? 1 - distanceProgress : distanceProgress;

                    var firstSample = Samples.FirstOrDefault(s => s.Name == SampleInfo.HIT_NORMAL) ?? Samples.FirstOrDefault(); // TODO: remove this when guaranteed sort is present for samples (https://github.com/ppy/osu/issues/1933)
                    var sampleList  = new List <SampleInfo>();

                    if (firstSample != null)
                    {
                        sampleList.Add(new SampleInfo
                        {
                            Bank   = firstSample.Bank,
                            Volume = firstSample.Volume,
                            Name   = @"slidertick",
                        });
                    }

                    AddNested(new SliderTick
                    {
                        SpanIndex   = span,
                        StartTime   = spanStartTime + timeProgress * SpanDuration,
                        Position    = Curve.PositionAt(distanceProgress),
                        StackHeight = StackHeight,
                        Scale       = Scale,
                        ComboColour = ComboColour,
                        Samples     = sampleList
                    });
                }
            }
        }
Exemplo n.º 43
0
        public async Task GivenAProperBundle_WhenSubmittingATransactionForCosmosDbDataStore_ThenNotSupportedIsReturned()
        {
            using FhirException ex = await Assert.ThrowsAsync <FhirException>(() => _client.PostBundleAsync(Samples.GetDefaultTransaction().ToPoco <Bundle>()));

            Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.StatusCode);
        }
Exemplo n.º 44
0
            public void AddSample(double sample, long interval = -1)
            {
                long nowInMillis = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

                //What interval of time is this sample over?  Provided in the function call or to be calculated from previous function calls...
                long interval2add;

                if (interval > 0)
                {
                    interval2add = interval;
                }
                else
                {
                    if (Samples.Count == 0)
                    {
                        interval2add = Interval;
                    }
                    else
                    {
                        long prevSampleTimeInMillis = _lastAddSampleAttempt.Ticks / TimeSpan.TicksPerMillisecond;
                        interval2add = nowInMillis - prevSampleTimeInMillis;
                    }
                }

                //do soe quality control checks
                bool rejectSample = false;

                //First one is if we care about how much the interval deviates from the expected Interval
                if (interval > 0 && IntervalDeviation >= 0 && System.Math.Abs(interval2add - Interval) > IntervalDeviation)
                {
                    rejectSample = true;
                }

                //Now record the latest sample attempt and if rejecting exit function
                _lastAddSampleAttempt = DateTime.Now;
                if (rejectSample)
                {
                    return;
                }

                //by here the sample is good
                Samples.Add(sample);
                SampleTimes.Add(nowInMillis);
                SampleIntervals.Add(interval2add);

                if (Samples.Count > SampleSize)
                {
                    Samples.RemoveAt(0);
                    SampleTimes.RemoveAt(0);
                    SampleIntervals.RemoveAt(0);
                }

                int    minIdx        = 0;
                int    maxIdx        = 0;
                double sampleTotal   = 0;
                long   durationTotal = 0;

                for (int i = 0; i < Samples.Count; i++)
                {
                    double val = Samples[i];
                    if (i > 0)
                    {
                        if (val < Samples[minIdx])
                        {
                            minIdx = i;
                        }
                        if (val > Samples[maxIdx])
                        {
                            maxIdx = i;
                        }
                    }
                    sampleTotal   += val;
                    durationTotal += SampleIntervals[i];
                }

                double average     = 0;
                int    sampleCount = 0;

                switch (Options)
                {
                case SamplingOptions.MEAN_COUNT:
                    sampleCount = Samples.Count;
                    average     = sampleTotal / (double)sampleCount;
                    break;

                case SamplingOptions.MEAN_COUNT_PRUNE_MIN_MAX:
                    if (Samples.Count > 2)
                    {
                        sampleTotal = (sampleTotal - Samples[minIdx] - Samples[maxIdx]);
                        sampleCount = Samples.Count - 2;
                        average     = sampleTotal / (double)(sampleCount);
                    }
                    else
                    {
                        sampleCount = Samples.Count;
                        average     = sampleTotal / (double)sampleCount;
                    }
                    break;

                case SamplingOptions.MEAN_INTERVAL:
                    sampleCount = Samples.Count;
                    average     = sampleTotal * (double)Interval / (double)durationTotal;
                    break;

                case SamplingOptions.MEAN_INTERVAL_PRUNE_MIN_MAX:
                    if (Samples.Count > 2)
                    {
                        sampleTotal   = (sampleTotal - Samples[minIdx] - Samples[maxIdx]);
                        sampleCount   = Samples.Count - 2;
                        durationTotal = durationTotal - SampleIntervals[minIdx] - SampleIntervals[maxIdx];
                        average       = sampleTotal / (double)durationTotal;
                    }
                    else
                    {
                        sampleCount = Samples.Count;
                        average     = sampleTotal / (double)durationTotal;
                    }
                    break;
                }

                //now assign values
                Average       = average;
                SampleTotal   = sampleTotal;
                SampleCount   = sampleCount;
                DurationTotal = durationTotal;
            }
Exemplo n.º 45
0
        public async Task GivenAResource_WhenPostingToHttpWithMaliciousUrl_TheServerShouldHandleRequest(string code)
        {
            FhirResponse <Observation> response = await Client.CreateAsync($"Observation?{code}", Samples.GetDefaultObservation().ToPoco <Observation>());

            // Status should always be created in these tests
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.NotNull(response.Headers.ETag);
            Assert.NotNull(response.Headers.Location);
            Assert.NotNull(response.Content.Headers.LastModified);
        }
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            try
            {
                #region pick database
                //string serverConnectionString = "Persist Security Info=True;server=localhost;database=microtingMySQL;uid=root;password=1234";
                string serverConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=v166;User Id=sa;Password=aiT1sueh;";

                Console.WriteLine("Enter database to use:");
                Console.WriteLine("> If left blank, it will use 'Microting'");
                Console.WriteLine("  Enter name of database to be used");
                string databaseName = Console.ReadLine();

                //if (databaseName.ToUpper() != "")
                //    serverConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=" + databaseName + ";Integrated Security=True";
                //if (databaseName.ToUpper() == "T")
                //    serverConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=" + "MicrotingTest" + ";Integrated Security=True";
                //if (databaseName.ToUpper() == "O")
                //    serverConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=" + "MicrotingOdense" + ";Integrated Security=True";

                Console.WriteLine(serverConnectionString);
                #endregion

                #region Console.WriteLine(...text...)
                Console.WriteLine("");
                Console.WriteLine("Enter one of the following keys to start:");
                Console.WriteLine("  'A', for Admin tools");
                Console.WriteLine("> 'S', for sample programs");
                Console.WriteLine("  'I', for purely run core");
                Console.WriteLine("");
                Console.WriteLine("Any other will close Console");
                string input = Console.ReadLine().ToUpper();
                #endregion


                var bus = Configure.With(new BuiltinHandlerActivator())
                          .Logging(l => l.ColoredConsole())
                          .Transport(t => t.UseSqlServerAsOneWayClient(connectionStringOrConnectionStringName: serverConnectionString, tableName: "Rebus"))
                          .Options(o =>
                {
                })
                          .Routing(r => r.TypeBased().Map <EformRetrieved>("eformsdk-input"))
                          .Start();

                if (input == "A")
                {
                    var program = new AdminTools(serverConnectionString);
                    program.RunConsole();
                }
                if (input == "S")
                {
                    var program = new Samples(serverConnectionString);
                    program.Run();
                }
                if (input == "I")
                {
                    var core = new Core();
                    core.Start(serverConnectionString);
                    #region keep core running
                    while (true)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Press any key to exit program,");
                        Console.ReadLine();
                        break;
                    }
                    #endregion
                }

                if (input == "E")
                {
                    var core = new Core();
                    core.Start(serverConnectionString);

                    Console.WriteLine("Sending EformRetrieved message");
                    bus.Send(new EformRetrieved("123", "123")).Wait();

                    Console.WriteLine("Hit a key to exit");
                    Console.ReadLine();
                }

                Console.WriteLine("");
                Console.WriteLine("Console will close in 1s");
                Thread.Sleep(1000);
                Environment.Exit(0);
            }
            #region ...catch all...
            catch (Exception ex)
            {
                Tools t = new Tools();

                try
                {
                    File.AppendAllText("FatalException_" + DateTime.Now.ToString("MM.dd_HH.mm.ss") + ".txt", t.PrintException("Fatal Exception", ex));
                }
                catch { }

                Console.WriteLine("");
                Console.WriteLine(t.PrintException("Fatal Exception", ex));
                Console.WriteLine("");
                Console.WriteLine("Fatal Exception found and logged. Fil can be found at log/");
                Console.WriteLine("Console will close in 6s");
                Thread.Sleep(6000);
                Environment.Exit(0);
            }
            #endregion
        }
Exemplo n.º 47
0
 public abstract void DrawAgentGUI(Samples s);
Exemplo n.º 48
0
        public async Task GivenASearchParam_WhenUpdatingParam_ThenResourcesIndexedWithUpdatedParam()
        {
            var patientName = Guid.NewGuid().ToString().ComputeHash().Substring(28).ToLower();
            var patient     = new Patient {
                Name = new List <HumanName> {
                    new HumanName {
                        Family = patientName
                    }
                }
            };
            var searchParam = Samples.GetJsonSample <SearchParameter>("SearchParameter");

            // POST a new patient
            FhirResponse <Patient> expectedPatient = await Client.CreateAsync(patient);

            // POST a new Search parameter
            FhirResponse <SearchParameter> searchParamPosted = null;

            try
            {
                searchParamPosted = await Client.CreateAsync(searchParam);
            }
            catch (FhirException)
            {
                // if the SearchParameter exists, we should delete it and recreate it
                var searchParamBundle = await Client.SearchAsync(ResourceType.SearchParameter, $"url={searchParam.Url}");

                if (searchParamBundle.Resource?.Entry[0] != null && searchParamBundle.Resource?.Entry[0].Resource.ResourceType == ResourceType.SearchParameter)
                {
                    await DeleteSearchParameterAndVerify(searchParamBundle.Resource?.Entry[0].Resource as SearchParameter);

                    searchParamPosted = await Client.CreateAsync(searchParam);
                }
                else
                {
                    throw;
                }
            }

            // now update the new search parameter
            searchParamPosted.Resource.Name = "foo2";
            searchParamPosted.Resource.Url  = "http://hl7.org/fhir/SearchParameter/Patient-foo2";
            searchParamPosted.Resource.Code = "foo2";
            searchParamPosted = await Client.UpdateAsync(searchParamPosted.Resource);

            Uri reindexJobUri;
            FhirResponse <Parameters> reindexJobResult;

            try
            {
                // Reindex just a single patient, so we can try searching with a partially indexed search param
                (reindexJobResult, reindexJobUri) = await Client.PostReindexJobAsync(new Parameters(), $"Patient/{expectedPatient.Resource.Id}/");

                Parameters.ParameterComponent param = reindexJobResult.Resource.Parameter.FirstOrDefault(p => p.Name == "foo2");

                Assert.Equal(patientName, param.Value.ToString());
            }
            catch (FhirException ex) when(ex.StatusCode == HttpStatusCode.BadRequest && ex.Message.Contains("not enabled"))
            {
                Skip.If(!_fixture.IsUsingInProcTestServer, "Reindex is not enabled on this server.");
                return;
            }

            // When job complete, search for resources using new parameter
            await ExecuteAndValidateBundle($"Patient?foo2:exact={patientName}", Tuple.Create("x-ms-use-partial-indices", "true"), expectedPatient.Resource);

            // Clean up new SearchParameter
            await DeleteSearchParameterAndVerify(searchParamPosted.Resource);
        }