Example #1
4
 /** 
  * Create a System.Random object from this RandomNumberGenerator
  */
 public SecureRandom(RandomNumberGenerator rng) {
   _rng = rng;
   _sample_buffer = new byte[4];
   _state = new Sample();
   _state.Val = 0;
   _state.Max = 1;
 }
 private void samplesTreeView_AfterSelect(object sender, TreeViewEventArgs e)
 {
     TreeNode currentNode = samplesTreeView.SelectedNode;
     currentSample = (Sample)currentNode.Tag;
     if (currentSample != null)
     {
         currentHarness = currentSample.Harness;
         runButton.Enabled = true;
         descriptionTextBox.Text = currentSample.Description;
         codeRichTextBox.Clear();
         codeRichTextBox.Text = currentSample.Code;
         colorizeCode(codeRichTextBox);
         outputTextBox.Clear();
     }
     else
     {
         currentHarness = null;
         runButton.Enabled = false;
         descriptionTextBox.Text = "Select a query from the tree to the left.";
         codeRichTextBox.Clear();
         outputTextBox.Clear();
         if (e.Action != TreeViewAction.Collapse && e.Action != TreeViewAction.Unknown)
             e.Node.Expand();
     }
 }
 public void ShouldReturnSameInstanceAfterCreatingDefaultValue()
 {
     var stub = new Sample();
     var value1 = stub.Child;
     var value2 = stub.Child;
     value1.ShouldBe(value2);
 }
Example #4
0
 public float PrimarySample(Sample u, int i, bool large_step, int time, int large_step_time)
 {
     if (u.modifyData[i] < time)
     {
         if (large_step)
         { // large step
             u.Push(i); // save state
             u.modifyData[i]  = time;
             u.sampleData[i] = rnd.NextFloat();
         }
         else
         { // small step
             if (u.modifyData[i] < large_step_time)
             {
                 u.modifyData[i]  = large_step_time;
                 u.sampleData[i] = rnd.NextFloat();
             }
             // lazy evaluation of mutations
             while (u.modifyData[i] < time - 1)
             {
                 u.sampleData[i] = MC.Mutate(rnd, u.sampleData[i]);
                 u.modifyData[i]++;
             }
             u.Push(i); // save state
             u.sampleData[i] = MC.Mutate(rnd, u.sampleData[i]);
             u.modifyData[i]++;
         }
     }
     return u.sampleData[i];
 }
Example #5
0
 public void CheckThatGetAttributeFromReturnsCorrectValues()
 {
     Sample s = new Sample();
     Assert.NotNull(s.GetAttributeFrom<RequiredAttribute>(nameof(s.IntProperty)));
     Assert.Null(s.GetAttributeFrom<StringLengthAttribute>(nameof(s.IntProperty)));
     Assert.NotNull(s.GetAttributeFrom<StringLengthAttribute>(nameof(s.StringProperty)));
 }
        public void CanGetUsingTestFieldUsingIndexesWithoutProblems()
        {
            var obj = new Sample { TestField = 42 };
            var prop = typeof(Sample).GetField("TestField").ToSettable();

            prop.Get(obj, 1, 2, 3).Should().Be(42);
        }
Example #7
0
 void Test01()
 {
     var gd = new Connect();
     var sample = new Sample
                      {
                          Method = "GET",
                          Uri = "/test",
                          Timestamp = DateTime.Now.TimeOfDay.TotalMilliseconds,
                          ResponseTime = 100,
                          CpuTime = 20,
                          Context =
                              new[]
                                  {
                                      new Context {Name = "/", ResponseTime = 11},
                                      new Context {Name = "/one", ResponseTime = 12},
                                      new Context {Name = "/two", ResponseTime = 13}
                                  }
                      };
     gd.Init("26873", "testing", logger, null);
     for (int i = 0; i < 1000; i++)
     {
         gd.Store(sample, logger, null);
         Thread.Sleep(300);
     }
     gd.Term(logger, null);
     Console.Read();
 }
        public void CanGetUsingTestProperty()
        {
            var obj = new Sample { TestProp = 42 };
            var prop = typeof(Sample).GetProperty("TestProp").ToSettable();

            prop.Get(obj).Should().Be(42);
        }
        private static void UsingPInvoke()
        {
            Console.WriteLine("exgetvec Using PInvoke");

            int i, j, nsig;
            Sample[] v;
            Signal[] s;

            nsig = PInvoke.isigopen("data/100s", null, 0);
            if (nsig < 1)
                return;
            s = new Signal[nsig];

            if (PInvoke.isigopen("data/100s", s, nsig) != nsig)
                return;

            v = new Sample[nsig];
            for (i = 0; i < 10; i++)
            {
                if (PInvoke.getvec(v) < 0)
                    break;
                for (j = 0; j < nsig; j++)
                    Console.Write("{0} \t", v[j]);
                Console.WriteLine();
            }
            PInvoke.wfdbquit();
        }
Example #10
0
		public void TutorialTitlesAreSplitAndAllOtherCategoriesAreNotSplit()
		{
			var game = new Sample("DoNotSplit", SampleCategory.Game, "A.sln", "B.csproj", "C.exe");
			var tutorial = new Sample("SplitThis", SampleCategory.Tutorial, "A.sln", "B.csproj", "C.exe");
			Assert.AreEqual("DoNotSplit", game.Title);
			Assert.AreEqual("Split This", tutorial.Title);
		}
Example #11
0
        protected void Compare(Template template, Sample sample)
        {
            try
            {
                // Process the sample and create a feature set for the enrollment purpose.
                //MemoryStream ms = new MemoryStream(Funciones.ImageToByteArray(this.picHuella.Image));
                //DPFP.Sample sample = new DPFP.Sample(ms);
                DPFP.FeatureSet features = ExtractFeatures(sample, DPFP.Processing.DataPurpose.Verification);

                // Check quality of the sample and start verification if it's good
                // TODO: move to a separate task
                if (features != null)
                {
                    // Compare the feature set with our template
                    DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
                    Verificator.Verify(features, template, ref result);
                    //UpdateStatus(result.FARAchieved);
                    if (result.Verified)
                    {
                        MessageBox.Show(this, "El usuario coincide con el existente!", "Validador Huella", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        MakeReport("El usuario coincide con el existente!");
                    }
                    else
                    {
                        MessageBox.Show(this, "El usuario No coincide con el existente!", "Validador Huella", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        MakeReport("El usuario No coincide con el existente!.");
                    }
                }
            }
            catch (Exception ex)
            {
                MakeReport(ex.Message);
            }
        }
Example #12
0
 public float GetLDValue(Sample sample)
 {
     return ldSequence.NextValue(sample.Index++);
     //return (float)ldSequence.NextDouble();
     //return rnd.NextFloat();
     //return halton.NextFloat();
 }
Example #13
0
        static void Main(string[] args)
        {
            var s = new Sample();

            s.PropertyChanged += (_, e) =>
            {
                switch (e.PropertyName)
                {
                    case "X":
                        Console.WriteLine($"X = {s.X}");
                        break;
                    case "Y":
                        Console.WriteLine($"Y = {s.Y}");
                        break;
                }
            };

            s.X = 10;
            s.Y = 20;

/*
結果:

X = 10
Y = 20
*/
        }
Example #14
0
        public void AnovaDistribution()
        {
            Distribution sDistribution = new NormalDistribution();
            Random rng = new Random(1);

            Sample fSample = new Sample();

            // do 100 ANOVAs
            for (int t = 0; t < 100; t++) {
                // each ANOVA has 4 groups
                List<Sample> groups = new List<Sample>();
                for (int g = 0; g < 4; g++) {
                    // each group has 3 data points
                    Sample group = new Sample();
                    for (int i = 0; i < 3; i++) {
                        group.Add(sDistribution.GetRandomValue(rng));
                    }
                    groups.Add(group);
                }

                OneWayAnovaResult result = Sample.OneWayAnovaTest(groups);
                fSample.Add(result.Factor.Result.Statistic);

            }

            // compare the distribution of F statistics to the expected distribution
            Distribution fDistribution = new FisherDistribution(3, 8);
            Console.WriteLine("m={0} s={1}", fSample.PopulationMean, fSample.PopulationStandardDeviation);
            TestResult kResult = fSample.KolmogorovSmirnovTest(fDistribution);
            Console.WriteLine(kResult.LeftProbability);
            Assert.IsTrue(kResult.LeftProbability < 0.95);
        }
        private static void UsingPInvoke(int frequency)
        {
            try
            {
                Frequency f = frequency;
                Sample[] v = new Sample[2];
                Signal[] s = new Signal[2];
                Time t = 0, t0 = 0, t1 = 0;

                if (f <= 0)
                    f = PInvoke.sampfreq("data/100s");

                if (PInvoke.isigopen("data/100s", s, 2) < 1)
                    return;
                PInvoke.setifreq(f);
                t0 = PInvoke.strtim("1");
                PInvoke.isigsettime(t);
                t1 = PInvoke.strtim("2");
                for (t = t0; t <= t1; t++)
                {
                    if (PInvoke.getvec(v) < 0)
                        break;
                    Console.WriteLine("{0}\t{1}", v[0], v[1]);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #16
0
 static void Main(string[] args)
 {
     Class2 instance = new Class2();
     Sample sample = new Sample(instance.method);
     int result = sample(2 , 3);
     Console.WriteLine(result);
 }
        public void Serialize(string filename, Sample[] samples)
        {
            var sampleBrowser = new SampleBrowser {Samples = samples};

            using (var stream = new FileStream(filename, FileMode.Create))
                _serializer.Serialize(stream, sampleBrowser);
        }
Example #18
0
 public void ToStringTest()
 {
     var sample = new Sample(Title, SampleCategory.Game, "Game.sln", "Game.csproj", "Game.exe");
     Assert.AreEqual(
         "Sample: Title=" + Title + ", Category=" + Category + ", Description=" + Description,
         sample.ToString());
 }
Example #19
0
        public void CookieJar_Example1(int total, int choc1, int choc2, int expectedNumerator, int expectedDenominator)
        {
            var sample1 = new Sample<Cookie>("Jar1");
            var sample2 = new Sample<Cookie>("Jar2");
            var hypos = new HypoSet<Cookie>("All");

            hypos.Add(sample1, sample2);

            sample1.Add(total - choc1, n => new Cookie() { F = 'V' });
            sample1.Add(choc1, n => new Cookie() { F = 'C' });

            sample2.Add(total - choc2, n => new Cookie() { F = 'V' });
            sample2.Add(choc2, n => new Cookie() { F = 'C' });

            var choc = It.IsAny<Cookie>(c => c.F == 'C');
            var vani = It.IsAny<Cookie>(c => c.F == 'V');

            sample1.ProbabilityOfEvent(choc);
            sample2.ProbabilityOfEvent(choc);

            var postProb = hypos.PosterierProbability(sample1, vani);

            Assert.That(postProb.Numerator, Is.EqualTo(expectedNumerator));
            Assert.That(postProb.Denominator, Is.EqualTo(expectedDenominator));
        }
Example #20
0
 public Sample GetSample(Sample prevSample)
 {
     Sample sm;
     if (!lowLatency || (pass >= MagicValue2))
     {
         previewOver = true;
         // In order to improve ray coherency
         if (samplePerPixel == 1)
             sm = GetNextSample1x1(prevSample);
         else
             sm = GetNextSampleNxN(prevSample);
     }
     else if (previewOver || (pass >= MagicValue1))
     {
         previewOver = true;
         sm = GetNextSampleNxN(prevSample);
     }
     else
     {
         // In order to update the screen faster for the first 16 passes
         sm = GetNextSamplePreview();
     }
     TotalSamples++;
     //sm.imageY += screenStartLine;
     return sm;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet dataSet = null;
        using (Sample sample = new Sample())
        {
            //데이터 가져오기
            dataSet = sample.GetSampleDBData();

            //데이터 셋 제이슨으로 변경하기
            string resultJSON = String.Empty;
            resultJSON = JsonConvert.SerializeObject(dataSet, Formatting.Indented);

            //화면에 밀어 넣기 샘플
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "JCall11", resultJSON.ToString(), false);

            //스크립트 생성하기 샘플
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script language=""'javascript'"">");
            sb.Append(@"example();");
            sb.Append(@"</script>");
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "JCall1", sb.ToString(), false);

           JavaScriptSerializer serializer = new JavaScriptSerializer();
           serializer.Serialize(resultJSON);

        }
    }
Example #22
0
 public void ProcedureIsExecuted()
 {
     cellProcessor.Store(new Procedure("procedure", Parse.ParseFrom(noParameterProcedureHtml)));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), "procedure", new CellTree());
     Assert.AreEqual("hi", sample.Text);
 }
        public HaltonRsg(int dimensionality,
                         ulong seed ,
                         bool randomStart,
                         bool randomShift)
        {
            if(seed ==null) seed = 0;
            if(randomStart ==null) randomStart = true;
            if(randomShift ==null) randomShift = false;
            dimensionality_=dimensionality;
            sequenceCounter_ = 0;
            sequence_ = new Sample<List<double>>(new InitializedList<double>(dimensionality), 1.0);
            randomStart_= new InitializedList<ulong>(dimensionality, 0UL);
            randomShift_ = new InitializedList<double>(dimensionality, 0.0);

            if(!(dimensionality>0)) 
                throw new ArgumentException("dimensionality must be greater than 0");

            if (randomStart || randomShift) 
            {
                RandomSequenceGenerator<MersenneTwisterUniformRng>uniformRsg = 
                    new RandomSequenceGenerator<MersenneTwisterUniformRng>(dimensionality_, seed);
                if (randomStart)
                    randomStart_ = uniformRsg.nextInt32Sequence();
                if (randomShift)
                    randomShift_ = uniformRsg.nextSequence().value;
            }
        }
Example #24
0
 public void ProcedureIsExecutedOnACopyOfBody()
 {
     cellProcessor.Get<Procedures>().Save("procedure", Parse.ParseFrom(errorProcedureHtml));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), new MemberName("procedure"), new CellTree());
     Assert.AreEqual(errorProcedureHtml, cellProcessor.Get<Procedures>().GetValue("procedure").ToString());
 }
Example #25
0
 public void ParameterValueIsSubstituted()
 {
     cellProcessor.Store(new Procedure("procedure", Parse.ParseFrom(oneParameterProcedureHtml)));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), "procedure", new Parse("tr", "", new Parse("td", "actual", null, null), null));
     Assert.AreEqual("actual", sample.Text);
 }
        public ClientInstruments()
        {
            Samples = new List<float[]>();
            States = new List<bool>();

            var r = new Random();

            for (int i = 0; i < 16; i++)
            {
                States.Add(false);

                float vol = (float)r.NextDouble();
                float freq = (float)r.Next(500)+100.0f;

                var s = new Sample(0.25f, 8000);
                for (int j = 0; j < s.Count; j++)
                {

                    s[j].Volume = vol;
                    s[j].Frequency = freq;
                }

                var transform = r.Next(4);
                if (transform == 0)
                    Samples.Add(Transforms.GenerateSawtoothWaveform(s));
                if (transform == 1)
                    Samples.Add(Transforms.GenerateSineWaveform(s));
                if (transform == 2)
                    Samples.Add(Transforms.GenerateSquareWaveform(s));
                if (transform == 3)
                    Samples.Add(Transforms.GenerateTriangleWaveform(s));
            }
        }
Example #27
0
 public void ProcedureExecutionIsLogged()
 {
     cellProcessor.Get<Procedures>().Save("procedure", Parse.ParseFrom(noParameterProcedureHtml));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), new MemberName("procedure"), new CellTree());
     Assert.AreEqual("<br><table border=1><tr><td>settext</td></tr></table>", cellProcessor.TestStatus.LastAction);
 }
        public void KendallNullDistributionTest()
        {
            // pick independent distributions for x and y, which needn't be normal and needn't be related
            Distribution xDistrubtion = new LogisticDistribution();
            Distribution yDistribution = new ExponentialDistribution();
            Random rng = new Random(314159265);

            // generate bivariate samples of various sizes
            //int n = 64; {
            foreach (int n in TestUtilities.GenerateIntegerValues(4, 64, 8)) {

                Sample testStatistics = new Sample();
                Distribution testDistribution = null;

                for (int i = 0; i < 128; i++) {

                    BivariateSample sample = new BivariateSample();
                    for (int j = 0; j < n; j++) {
                        sample.Add(xDistrubtion.GetRandomValue(rng), yDistribution.GetRandomValue(rng));
                    }

                    TestResult result = sample.KendallTauTest();
                    testStatistics.Add(result.Statistic);
                    testDistribution = result.Distribution;
                }

                //TestResult r2 = testStatistics.KolmogorovSmirnovTest(testDistribution);
                //Console.WriteLine("n={0} P={1}", n, r2.LeftProbability);
                //Assert.IsTrue(r2.RightProbability > 0.05);

                Console.WriteLine("{0} {1}", testStatistics.PopulationVariance, testDistribution.Variance);
                Assert.IsTrue(testStatistics.PopulationMean.ConfidenceInterval(0.95).ClosedContains(testDistribution.Mean));
                Assert.IsTrue(testStatistics.PopulationVariance.ConfidenceInterval(0.95).ClosedContains(testDistribution.Variance));
            }
        }
Example #29
0
 public void ProcedureIsExecuted()
 {
     cellProcessor.Get<Procedures>().Save("procedure", new CellTree(new CellTree("define", "procedure"), new CellTree("settext")));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), new MemberName("procedure"), new CellTree());
     Assert.AreEqual("hi", sample.Text);
 }
Example #30
0
 public void ParameterValueIsSubstituted()
 {
     cellProcessor.Get<Procedures>().Save("procedure", new CellTree(new CellTree("define", "procedure", "parm"), new CellTree("settext", "parm")));
     var sample = new Sample();
     invokeProcedure.Invoke(new TypedValue(sample), new MemberName("procedure"), new CellTree("actual"));
     Assert.AreEqual("actual", sample.Text);
 }
Example #31
0
 	public void Clear()
 	{
 		for (int i = 0; i < size; i++)
 			sampleData[i] = new Sample();
 	}
Example #32
0
        public static void ReadData(string file)
        {
            List <Sample> edges = new List <Sample>();

            using (StreamReader reader = new StreamReader(file))
            {
                reader.ReadLine();

                while (!reader.EndOfStream)
                {
                    String[] line = reader.ReadLine().Split(", ");
                    if (line.Length != 4)
                    {
                        continue;
                    }
                    Sample s;
                    s.red      = (Town)Enum.Parse(typeof(Town), line[0]);
                    s.blue     = (Town)Enum.Parse(typeof(Town), line[1]);
                    s.redMoney = Double.Parse(line[2]) / 10000;
                    s.redWin   = Boolean.Parse(line[3]);
                    edges.Add(s);
                    if (!s.redWin)
                    {
                        Town t = s.red;
                        s.red      = s.blue;
                        s.blue     = t;
                        s.redWin   = true;
                        s.redMoney = -s.redMoney;
                        edges.Add(s);
                    }
                }
            }


            // Transitive  closure
            for (int i = 0; i < edges.Count; ++i)
            {
                Sample s = edges[i];
                if (s.redWin)
                {
                    TransitiveClosure(edges, s, (o, e) => o.red == e.red && e.redMoney >= o.redMoney && e.blueMoney <= o.redMoney, (o, e) => new Sample()
                    {
                        red = e.blue, blue = o.blue, redMoney = o.redMoney, redWin = true
                    });
                    TransitiveClosure(edges, s, (o, e) => o.blue == e.blue && e.blueMoney <= o.blueMoney && e.redMoney >= o.blueMoney, (o, e) => new Sample()
                    {
                        red = o.red, blue = e.red, redMoney = o.redMoney, redWin = true
                    });
                }
                else
                {
                    TransitiveClosure(edges, s, (o, e) => o.red == e.blue && e.blueMoney >= o.redMoney, (o, e) => new Sample()
                    {
                        red = e.red, blue = o.blue, redMoney = o.redMoney, redWin = false
                    });
                    TransitiveClosure(edges, s, (o, e) => o.blue == e.red && e.redMoney >= o.blueMoney, (o, e) => new Sample()
                    {
                        red = o.red, blue = e.blue, redMoney = o.redMoney, redWin = false
                    });
                }
            }


            //		while (queue.Count > 0)
            //	{
            //		ValueTuple<Town, double> n = queue.Dequeue();
            //		for (int j = 0; j < edges.Count; ++j)
            //		{
            //			Sample e = edges[j];

            //			if (e.red == n.Item1 && e.redWin && e.redMoney <= n.Item2)
            //			{
            //				Sample s = new Sample() { red = e.red }
            //			}
            //			if (e.blue == n.Item1 && e.redWin && e.redMoney <= n.Item2)
            //			{

            //			}
            //		}

            //	}
            //}

            foreach (Town red in Enum.GetValues(typeof(Town)))
            {
                Sample s;
                foreach (Town blue in Enum.GetValues(typeof(Town)))
                {
                    s.red      = red;
                    s.blue     = blue;
                    s.redWin   = false;
                    s.redMoney = -1;
                    data.Add(s);
                    s.redWin   = true;
                    s.redMoney = 1;
                    data.Add(s);

                    s.red      = red;
                    s.blue     = blue;
                    s.redWin   = true;
                    s.redMoney = 0;
                    data.Add(s);
                    s.redWin   = false;
                    s.redMoney = 0;
                    data.Add(s);
                }
            }
        }
 public override void SetOn(Sample sample, float value)
 {
     sample.SignalMappedVolume(value, this);
 }
Example #34
0
        public unsafe bool ProcessSample(Sample inputSample, out Sample outputSample)
        {
            bool Result = false;

            outputSample = null;

            if (inputSample == null)
            {
                return(false);
            }

            processor.ProcessInput(0, inputSample, 0);

            //if (processor.OutputStatus == (int)MftOutputStatusFlags.MftOutputStatusSampleReady)
            {
                processor.GetOutputStreamInfo(0, out TOutputStreamInformation streamInfo);

                MftOutputStreamInformationFlags flags = (MftOutputStreamInformationFlags)streamInfo.DwFlags;
                bool createSample = !flags.HasFlag(MftOutputStreamInformationFlags.MftOutputStreamProvidesSamples);

                // Create output sample
                if (createSample)
                {
                    outputSample = MediaFactory.CreateSample();

                    outputSample.SampleTime     = inputSample.SampleTime;
                    outputSample.SampleDuration = inputSample.SampleDuration;
                    outputSample.SampleFlags    = inputSample.SampleFlags;

                    using (var mediaBuffer = MediaFactory.CreateMemoryBuffer(streamInfo.CbSize))
                    {
                        outputSample.AddBuffer(mediaBuffer);
                    }
                }

                TOutputDataBuffer[] outputDataBuffer = new TOutputDataBuffer[1];

                var data = new TOutputDataBuffer
                {
                    DwStatus   = 0,
                    DwStreamID = 0,
                    PSample    = outputSample,
                    PEvents    = null,
                };
                outputDataBuffer[0] = data;

                var res = processor.TryProcessOutput(TransformProcessOutputFlags.None, outputDataBuffer, out TransformProcessOutputStatus status);
                if (res == SharpDX.Result.Ok)
                {
                    if (outputSample == null)
                    {
                        outputSample = outputDataBuffer[0].PSample;
                    }

                    Debug.Assert(outputSample != null, "res.Success && outputSample != null");

                    Result = true;
                }
                else if (res == SharpDX.MediaFoundation.ResultCode.TransformNeedMoreInput)
                {
                    logger.Warn(res.ToString() + " TransformNeedMoreInput");

                    Result = true;
                }
                else if (res == SharpDX.MediaFoundation.ResultCode.TransformStreamChange)
                {
                    logger.Warn(res.ToString() + " TransformStreamChange");

                    MediaType newOutputType = null;
                    try
                    {
                        processor.TryGetOutputAvailableType(outputStreamId, 0, out newOutputType);
                        processor.SetOutputType(outputStreamId, newOutputType, 0);

                        if (OutputMediaType != null)
                        {
                            OutputMediaType.Dispose();
                            OutputMediaType = null;
                        }
                        OutputMediaType = newOutputType;

                        logger.Info("============== NEW OUTPUT TYPE==================");
                        logger.Info(MfTool.LogMediaType(OutputMediaType));
                    }
                    finally
                    {
                        newOutputType?.Dispose();
                        newOutputType = null;
                    }
                }
                else
                {
                    res.CheckError();
                }
            }

            return(Result);
        }
Example #35
0
        public void Run()
        {
            var s = new Sample();

            s.X += 1;
        }
Example #36
0
        public void ReadBasicManifest_CanReadFile()
        {
            // create manifest data
            IDictionary <string, object> originalDependency = new Dictionary <string, object>
            {
                [nameof(IManifestDependency.UniqueID)] = Sample.String()
            };
            IDictionary <string, object> original = new Dictionary <string, object>
            {
                [nameof(IManifest.Name)]              = Sample.String(),
                [nameof(IManifest.Author)]            = Sample.String(),
                [nameof(IManifest.Version)]           = new SemanticVersion(Sample.Int(), Sample.Int(), Sample.Int(), Sample.String()),
                [nameof(IManifest.Description)]       = Sample.String(),
                [nameof(IManifest.UniqueID)]          = $"{Sample.String()}.{Sample.String()}",
                [nameof(IManifest.EntryDll)]          = $"{Sample.String()}.dll",
                [nameof(IManifest.MinimumApiVersion)] = $"{Sample.Int()}.{Sample.Int()}-{Sample.String()}",
                [nameof(IManifest.Dependencies)]      = new[] { originalDependency },
                ["ExtraString"] = Sample.String(),
                ["ExtraInt"]    = Sample.Int()
            };

            // write to filesystem
            string rootFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
            string modFolder  = Path.Combine(rootFolder, Guid.NewGuid().ToString("N"));
            string filename   = Path.Combine(modFolder, "manifest.json");

            Directory.CreateDirectory(modFolder);
            File.WriteAllText(filename, JsonConvert.SerializeObject(original));

            // act
            IModMetadata[] mods = new ModResolver().ReadManifests(new ModToolkit(), rootFolder, new ModDatabase()).ToArray();
            IModMetadata   mod  = mods.FirstOrDefault();

            // assert
            Assert.AreEqual(1, mods.Length, 0, "Expected to find one manifest.");
            Assert.IsNotNull(mod, "The loaded manifest shouldn't be null.");
            Assert.AreEqual(null, mod.DataRecord, "The data record should be null since we didn't provide one.");
            Assert.AreEqual(modFolder, mod.DirectoryPath, "The directory path doesn't match.");
            Assert.AreEqual(null, mod.Error, "The error should be null since parsing should have succeeded.");
            Assert.AreEqual(ModMetadataStatus.Found, mod.Status, "The status doesn't match.");

            Assert.AreEqual(original[nameof(IManifest.Name)], mod.DisplayName, "The display name should use the manifest name.");
            Assert.AreEqual(original[nameof(IManifest.Name)], mod.Manifest.Name, "The manifest's name doesn't match.");
            Assert.AreEqual(original[nameof(IManifest.Author)], mod.Manifest.Author, "The manifest's author doesn't match.");
            Assert.AreEqual(original[nameof(IManifest.Description)], mod.Manifest.Description, "The manifest's description doesn't match.");
            Assert.AreEqual(original[nameof(IManifest.EntryDll)], mod.Manifest.EntryDll, "The manifest's entry DLL doesn't match.");
            Assert.AreEqual(original[nameof(IManifest.MinimumApiVersion)], mod.Manifest.MinimumApiVersion?.ToString(), "The manifest's minimum API version doesn't match.");
            Assert.AreEqual(original[nameof(IManifest.Version)]?.ToString(), mod.Manifest.Version?.ToString(), "The manifest's version doesn't match.");

            Assert.IsNotNull(mod.Manifest.ExtraFields, "The extra fields should not be null.");
            Assert.AreEqual(2, mod.Manifest.ExtraFields.Count, "The extra fields should contain two values.");
            Assert.AreEqual(original["ExtraString"], mod.Manifest.ExtraFields["ExtraString"], "The manifest's extra fields should contain an 'ExtraString' value.");
            Assert.AreEqual(original["ExtraInt"], mod.Manifest.ExtraFields["ExtraInt"], "The manifest's extra fields should contain an 'ExtraInt' value.");

            Assert.IsNotNull(mod.Manifest.Dependencies, "The dependencies field should not be null.");
            Assert.AreEqual(1, mod.Manifest.Dependencies.Length, "The dependencies field should contain one value.");
            Assert.AreEqual(originalDependency[nameof(IManifestDependency.UniqueID)], mod.Manifest.Dependencies[0].UniqueID, "The first dependency's unique ID doesn't match.");
        }
Example #37
0
 /*********
 ** Private methods
 *********/
 /// <summary>Get a randomised basic manifest.</summary>
 /// <param name="id">The <see cref="IManifest.UniqueID"/> value, or <c>null</c> for a generated value.</param>
 /// <param name="name">The <see cref="IManifest.Name"/> value, or <c>null</c> for a generated value.</param>
 /// <param name="version">The <see cref="IManifest.Version"/> value, or <c>null</c> for a generated value.</param>
 /// <param name="entryDll">The <see cref="IManifest.EntryDll"/> value, or <c>null</c> for a generated value.</param>
 /// <param name="contentPackForID">The <see cref="IManifest.ContentPackFor"/> value.</param>
 /// <param name="minimumApiVersion">The <see cref="IManifest.MinimumApiVersion"/> value.</param>
 /// <param name="dependencies">The <see cref="IManifest.Dependencies"/> value.</param>
 private Manifest GetManifest(string id = null, string name = null, string version = null, string entryDll = null, string contentPackForID = null, string minimumApiVersion = null, IManifestDependency[] dependencies = null)
 {
     return(new Manifest
     {
         UniqueID = id ?? $"{Sample.String()}.{Sample.String()}",
         Name = name ?? id ?? Sample.String(),
         Author = Sample.String(),
         Description = Sample.String(),
         Version = version != null ? new SemanticVersion(version) : new SemanticVersion(Sample.Int(), Sample.Int(), Sample.Int(), Sample.String()),
         EntryDll = entryDll ?? $"{Sample.String()}.dll",
         ContentPackFor = contentPackForID != null ? new ManifestContentPackFor {
             UniqueID = contentPackForID
         } : null,
         MinimumApiVersion = minimumApiVersion != null ? new SemanticVersion(minimumApiVersion) : null,
         Dependencies = dependencies
     });
 }
Example #38
0
        private void load(AudioManager audio, OsuConfigManager config, OsuGameBase game)
        {
            var gameplayMods = Mods.Value.Select(m => m.DeepClone()).ToArray();

            if (Beatmap.Value is DummyWorkingBeatmap)
            {
                return;
            }

            IBeatmap playableBeatmap = loadPlayableBeatmap(gameplayMods);

            if (playableBeatmap == null)
            {
                return;
            }

            sampleRestart = audio.Samples.Get(@"Gameplay/restart");

            mouseWheelDisabled = config.GetBindable <bool>(OsuSetting.MouseDisableWheel);

            if (game != null)
            {
                gameActive.BindTo(game.IsActive);
            }

            if (game is OsuGame osuGame)
            {
                LocalUserPlaying.BindTo(osuGame.LocalUserPlaying);
            }

            DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, gameplayMods);
            dependencies.CacheAs(DrawableRuleset);

            ScoreProcessor = ruleset.CreateScoreProcessor();
            ScoreProcessor.ApplyBeatmap(playableBeatmap);
            ScoreProcessor.Mods.Value = gameplayMods;

            dependencies.CacheAs(ScoreProcessor);

            HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime);
            HealthProcessor.ApplyBeatmap(playableBeatmap);

            dependencies.CacheAs(HealthProcessor);

            if (!ScoreProcessor.Mode.Disabled)
            {
                config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode);
            }

            InternalChild = GameplayClockContainer = CreateGameplayClockContainer(Beatmap.Value, DrawableRuleset.GameplayStartTime);

            AddInternal(screenSuspension = new ScreenSuspensionHandler(GameplayClockContainer));

            Score = CreateScore(playableBeatmap);

            // ensure the score is in a consistent state with the current player.
            Score.ScoreInfo.BeatmapInfo = Beatmap.Value.BeatmapInfo;
            Score.ScoreInfo.Ruleset     = ruleset.RulesetInfo;
            if (ruleset.RulesetInfo.ID != null)
            {
                Score.ScoreInfo.RulesetID = ruleset.RulesetInfo.ID.Value;
            }
            Score.ScoreInfo.Mods = gameplayMods;

            dependencies.CacheAs(GameplayState = new GameplayState(playableBeatmap, ruleset, gameplayMods, Score));

            var rulesetSkinProvider = new RulesetSkinProvidingContainer(ruleset, playableBeatmap, Beatmap.Value.Skin);

            // load the skinning hierarchy first.
            // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources.
            GameplayClockContainer.Add(rulesetSkinProvider);

            rulesetSkinProvider.AddRange(new Drawable[]
            {
                failAnimationLayer = new FailAnimation(DrawableRuleset)
                {
                    OnComplete = onFailComplete,
                    Children   = new[]
                    {
                        // underlay and gameplay should have access to the skinning sources.
                        createUnderlayComponents(),
                        createGameplayComponents(Beatmap.Value, playableBeatmap)
                    }
                },
                FailOverlay = new FailOverlay
                {
                    OnRetry = Restart,
                    OnQuit  = () => PerformExit(true),
                },
                new HotkeyExitOverlay
                {
                    Action = () =>
                    {
                        if (!this.IsCurrentScreen())
                        {
                            return;
                        }

                        fadeOut(true);
                        PerformExit(false);
                    },
                },
            });

            if (Configuration.AllowRestart)
            {
                rulesetSkinProvider.Add(new HotkeyRetryOverlay
                {
                    Action = () =>
                    {
                        if (!this.IsCurrentScreen())
                        {
                            return;
                        }

                        fadeOut(true);
                        Restart();
                    },
                });
            }

            // add the overlay components as a separate step as they proxy some elements from the above underlay/gameplay components.
            // also give the overlays the ruleset skin provider to allow rulesets to potentially override HUD elements (used to disable combo counters etc.)
            // we may want to limit this in the future to disallow rulesets from outright replacing elements the user expects to be there.
            failAnimationLayer.Add(createOverlayComponents(Beatmap.Value));

            if (!DrawableRuleset.AllowGameplayOverlays)
            {
                HUDOverlay.ShowHud.Value    = false;
                HUDOverlay.ShowHud.Disabled = true;
                BreakOverlay.Hide();
            }

            DrawableRuleset.FrameStableClock.WaitingOnFrames.BindValueChanged(waiting =>
            {
                if (waiting.NewValue)
                {
                    GameplayClockContainer.Stop();
                }
                else
                {
                    GameplayClockContainer.Start();
                }
            });

            DrawableRuleset.IsPaused.BindValueChanged(paused =>
            {
                updateGameplayState();
                updateSampleDisabledState();
            });

            DrawableRuleset.FrameStableClock.IsCatchingUp.BindValueChanged(_ => updateSampleDisabledState());

            DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateGameplayState());

            // bind clock into components that require it
            DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);

            DrawableRuleset.NewResult += r =>
            {
                HealthProcessor.ApplyResult(r);
                ScoreProcessor.ApplyResult(r);
                GameplayState.ApplyResult(r);
            };

            DrawableRuleset.RevertResult += r =>
            {
                HealthProcessor.RevertResult(r);
                ScoreProcessor.RevertResult(r);
            };

            DimmableStoryboard.HasStoryboardEnded.ValueChanged += storyboardEnded =>
            {
                if (storyboardEnded.NewValue)
                {
                    progressToResults(true);
                }
            };

            // Bind the judgement processors to ourselves
            ScoreProcessor.HasCompleted.BindValueChanged(scoreCompletionChanged);
            HealthProcessor.Failed += onFail;

            // Provide judgement processors to mods after they're loaded so that they're on the gameplay clock,
            // this is required for mods that apply transforms to these processors.
            ScoreProcessor.OnLoadComplete += _ =>
            {
                foreach (var mod in gameplayMods.OfType <IApplicableToScoreProcessor>())
                {
                    mod.ApplyToScoreProcessor(ScoreProcessor);
                }
            };

            HealthProcessor.OnLoadComplete += _ =>
            {
                foreach (var mod in gameplayMods.OfType <IApplicableToHealthProcessor>())
                {
                    mod.ApplyToHealthProcessor(HealthProcessor);
                }
            };

            IsBreakTime.BindTo(breakTracker.IsBreakTime);
            IsBreakTime.BindValueChanged(onBreakTimeChanged, true);
        }
Example #39
0
        /// <summary>
        /// Adds the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Add(Sample entity)
        {
            var sample = entity;

            Debug.Assert(sample != null, "sample != null");
            using (var connection = new SqlConnection(DbConnection))
            {
                using (var command = new SqlCommand("PaSampleInsert", connection))
                {
                    var sqlParams = new List <SqlParameter>();
                    SqlHelper.AddReturnPara("@return_value", sqlParams);

                    SqlHelper.AddVarcharPara(sample.SessionKey, "@SessionKey", sqlParams);

                    SqlHelper.AddVarcharPara(sample.ClaimTypeDescription, "@ClaimTypeDescription", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ContractTypeDescription, "@ContractTypeDescription", sqlParams);
                    SqlHelper.AddVarcharPara(sample.SiteDescription, "@SiteDescription", sqlParams);
                    SqlHelper.AddVarcharPara(sample.EsaDescription, "@EsaDescription", sqlParams);
                    SqlHelper.AddVarcharPara(sample.OrgDescription, "@OrgDescription", sqlParams);

                    SqlHelper.AddBigIntPara(sample.ClaimId, "@ClaimId", sqlParams);
                    SqlHelper.AddIntPara(sample.ClaimSequenceNumber, "@ClaimSequenceNumber", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ClaimType, "@ClaimType", sqlParams);
                    SqlHelper.AddMoneyPara(sample.ClaimAmount, "@ClaimMoney", sqlParams);

                    SqlHelper.AddVarcharPara(sample.SiteCode, "@SiteCode", sqlParams);
                    SqlHelper.AddVarcharPara(sample.SupervisingSiteCode, "@SupervisingSiteCode", sqlParams);
                    SqlHelper.AddVarcharPara(sample.OrgCode, "@OrgCode", sqlParams);

                    SqlHelper.AddBigIntPara(sample.ActivityId, "@ActivityId", sqlParams);
                    SqlHelper.AddDatePara(sample.ClaimCreationDate, "@ClaimCreationDate", sqlParams);

                    SqlHelper.AddVarcharPara(sample.StatusCode, "@ClaimStatusCode", sqlParams);
                    SqlHelper.AddVarcharPara(sample.StatusCodeDescription, "@ClaimStatusDescription", sqlParams);

                    SqlHelper.AddVarcharPara(sample.StateCode, "@StateCode", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ManagedBy, "@ManagedBy", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ContractId, "@ContractId", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ContractType, "@ContractType", sqlParams);
                    SqlHelper.AddVarcharPara(sample.ContractTitle, "@ContractTitle", sqlParams);

                    SqlHelper.AddVarcharPara(sample.EsaCode, "@EsaCode", sqlParams);
                    SqlHelper.AddBigIntPara(sample.JobseekerId, "@JobseekerId", sqlParams);
                    SqlHelper.AddVarcharPara(sample.GivenName, "@GivenName", sqlParams);
                    SqlHelper.AddVarcharPara(sample.Surname, "@LastName", sqlParams);

                    SqlHelper.AddCharPara(sample.AutoSpecialClaimFlag, "@AutoSpecialClaimFlag", sqlParams);
                    SqlHelper.AddCharPara(sample.ManSpecialClaimFlag, "@ManualSpecialClaimFlag", sqlParams);

                    SqlHelper.AddVarcharPara(sample.CreatedBy, "@CreatedBy", sqlParams);

                    //  Output parameters
                    var paramId = new SqlParameter("@Id", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.InputOutput,
                        Value     = 0
                    };
                    sqlParams.Add(paramId);

                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddRange(sqlParams.ToArray());

                    connection.Open();

                    command.ExecuteNonQuery();

                    if (((Int32)command.Parameters["@return_value"].Value) != 0)
                    {
                        return;
                    }

                    sample.Id = (int)paramId.Value;
                }
            }
        }
Example #40
0
        public void ComputeLine()
        {
            SampleD s  = new SampleD();
            SampleD st = new SampleD();

            Sample minS = new Sample();
            Sample maxS = new Sample();

            //xMin = yMin = 1000000.0f;
            //xMax = yMax = -1000000.0f;

            if (Samples.Count > 0)
            {
                minS = Samples[0];
                maxS = Samples[0];
            }


            s.x  = s.y = s.z = s.t = 0.0;
            st.t = st.x = st.y = st.z = 1.0;

            int n = Samples.Count;

            for (int i = 0; i < n; ++i)
            {
                s.t += Samples[i].t;
                s.x += Samples[i].x;
                s.y += Samples[i].y;
                s.z += Samples[i].z;

                if (Samples[i].t < minS.t)
                {
                    minS = Samples[i];
                }
                if (Samples[i].t > maxS.t)
                {
                    maxS = Samples[i];
                }

                /*
                 * xMin = Math.Min( xMin, Samples[i].t );
                 * xMax = Math.Max( xMax, Samples[i].t );
                 * yMin = Math.Min( yMin, Samples[i].x );
                 * yMax = Math.Max( yMax, Samples[i].x );
                 * yMin = Math.Min( yMin, Samples[i].y );
                 * yMax = Math.Max( yMax, Samples[i].y );
                 * yMin = Math.Min( yMin, Samples[i].z );
                 * yMax = Math.Max( yMax, Samples[i].z );
                 * //*/
            }

            for (int i = 0; i < n; ++i)
            {
                double t = Samples[i].t - s.t / n;
                st.t += t * t;
                st.x += t * Samples[i].x;
                st.y += t * Samples[i].y;
                st.z += t * Samples[i].z;
            }

            dSlope.x = st.x / st.t;
            dSlope.y = st.y / st.t;
            dSlope.z = st.z / st.t;

            dIntercept.x = (s.x - s.t * dSlope.x) / n;
            dIntercept.y = (s.y - s.t * dSlope.y) / n;
            dIntercept.z = (s.z - s.t * dSlope.z) / n;
        }
Example #41
0
 	public void AddSample(Vector3 position, float deltaTime)
 	{
 		sampleData[nextIndex] = new Sample(position, deltaTime);
 		nextIndex = ++nextIndex % size;
 	}
    public static int test_5_newobj()
    {
        Sample s = new Sample(5);

        return(s.a);
    }
Example #43
0
 void ISampleCache.AddOrReplace(Sample sample)
 {
     _samples.AddOrReplace(sample);
 }
Example #44
0
File: Player.cs Project: eyx092/osu
        private void load(AudioManager audio, OsuConfigManager config, OsuGameBase game)
        {
            Mods.Value = base.Mods.Value.Select(m => m.CreateCopy()).ToArray();

            if (Beatmap.Value is DummyWorkingBeatmap)
            {
                return;
            }

            IBeatmap playableBeatmap = loadPlayableBeatmap();

            if (playableBeatmap == null)
            {
                return;
            }

            sampleRestart = audio.Samples.Get(@"Gameplay/restart");

            mouseWheelDisabled = config.GetBindable <bool>(OsuSetting.MouseDisableWheel);

            if (game != null)
            {
                gameActive.BindTo(game.IsActive);
            }

            if (game is OsuGame osuGame)
            {
                LocalUserPlaying.BindTo(osuGame.LocalUserPlaying);
            }

            DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, Mods.Value);
            dependencies.CacheAs(DrawableRuleset);

            ScoreProcessor = ruleset.CreateScoreProcessor();
            ScoreProcessor.ApplyBeatmap(playableBeatmap);
            ScoreProcessor.Mods.BindTo(Mods);

            dependencies.CacheAs(ScoreProcessor);

            HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime);
            HealthProcessor.ApplyBeatmap(playableBeatmap);

            dependencies.CacheAs(HealthProcessor);

            if (!ScoreProcessor.Mode.Disabled)
            {
                config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode);
            }

            InternalChild = GameplayClockContainer = CreateGameplayClockContainer(Beatmap.Value, DrawableRuleset.GameplayStartTime);

            AddInternal(GameplayBeatmap  = new GameplayBeatmap(playableBeatmap));
            AddInternal(screenSuspension = new ScreenSuspensionHandler(GameplayClockContainer));

            dependencies.CacheAs(GameplayBeatmap);

            var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin);

            // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation
            // full access to all skin sources.
            var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider, playableBeatmap));

            // load the skinning hierarchy first.
            // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources.
            GameplayClockContainer.Add(beatmapSkinProvider.WithChild(rulesetSkinProvider));

            rulesetSkinProvider.AddRange(new[]
            {
                // underlay and gameplay should have access the to skinning sources.
                createUnderlayComponents(),
                createGameplayComponents(Beatmap.Value, playableBeatmap)
            });

            // also give the HUD a ruleset container to allow rulesets to potentially override HUD elements (used to disable combo counters etc.)
            // we may want to limit this in the future to disallow rulesets from outright replacing elements the user expects to be there.
            var hudRulesetContainer = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider, playableBeatmap));

            // add the overlay components as a separate step as they proxy some elements from the above underlay/gameplay components.
            GameplayClockContainer.Add(hudRulesetContainer.WithChild(createOverlayComponents(Beatmap.Value)));

            if (!DrawableRuleset.AllowGameplayOverlays)
            {
                HUDOverlay.ShowHud.Value    = false;
                HUDOverlay.ShowHud.Disabled = true;
                BreakOverlay.Hide();
            }

            DrawableRuleset.FrameStableClock.WaitingOnFrames.BindValueChanged(waiting =>
            {
                if (waiting.NewValue)
                {
                    GameplayClockContainer.Stop();
                }
                else
                {
                    GameplayClockContainer.Start();
                }
            });

            DrawableRuleset.IsPaused.BindValueChanged(paused =>
            {
                updateGameplayState();
                updateSampleDisabledState();
            });

            DrawableRuleset.FrameStableClock.IsCatchingUp.BindValueChanged(_ => updateSampleDisabledState());

            DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateGameplayState());

            // bind clock into components that require it
            DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);

            DrawableRuleset.NewResult += r =>
            {
                HealthProcessor.ApplyResult(r);
                ScoreProcessor.ApplyResult(r);
                GameplayBeatmap.ApplyResult(r);
            };

            DrawableRuleset.RevertResult += r =>
            {
                HealthProcessor.RevertResult(r);
                ScoreProcessor.RevertResult(r);
            };

            DimmableStoryboard.HasStoryboardEnded.ValueChanged += storyboardEnded =>
            {
                if (storyboardEnded.NewValue && completionProgressDelegate == null)
                {
                    updateCompletionState();
                }
            };

            // Bind the judgement processors to ourselves
            ScoreProcessor.HasCompleted.BindValueChanged(_ => updateCompletionState());
            HealthProcessor.Failed += onFail;

            foreach (var mod in Mods.Value.OfType <IApplicableToScoreProcessor>())
            {
                mod.ApplyToScoreProcessor(ScoreProcessor);
            }

            foreach (var mod in Mods.Value.OfType <IApplicableToHealthProcessor>())
            {
                mod.ApplyToHealthProcessor(HealthProcessor);
            }

            IsBreakTime.BindTo(breakTracker.IsBreakTime);
            IsBreakTime.BindValueChanged(onBreakTimeChanged, true);
        }
Example #45
0
 private void load(AudioManager audio)
 {
     sampleOpen  = audio.Samples.Get(@"UI/dropdown-open");
     sampleClose = audio.Samples.Get(@"UI/dropdown-close");
 }
Example #46
0
        private void load(AudioManager audio)
        {
            sampleStart = audio.Samples.Get(@"SongSelect/confirm-selection");

            InternalChildren = new Drawable[]
            {
                beatmapAvailabilityTracker,
                new MultiplayerRoomSounds(),
                new GridContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    RowDimensions    = new[]
                    {
                        new Dimension(),
                        new Dimension(GridSizeMode.Absolute, 50)
                    },
                    Content = new[]
                    {
                        // Padded main content (drawable room + main content)
                        new Drawable[]
                        {
                            new Container
                            {
                                RelativeSizeAxes = Axes.Both,
                                Padding          = new MarginPadding
                                {
                                    Horizontal = WaveOverlayContainer.WIDTH_PADDING,
                                    Bottom     = 30
                                },
                                Children = new[]
                                {
                                    mainContent = new GridContainer
                                    {
                                        RelativeSizeAxes = Axes.Both,
                                        RowDimensions    = new[]
                                        {
                                            new Dimension(GridSizeMode.AutoSize),
                                            new Dimension(GridSizeMode.Absolute, 10)
                                        },
                                        Content = new[]
                                        {
                                            new Drawable[]
                                            {
                                                new DrawableMatchRoom(Room, allowEdit)
                                                {
                                                    OnEdit       = () => settingsOverlay.Show(),
                                                    SelectedItem = { BindTarget = SelectedItem }
                                                }
                                            },
                                            null,
                                            new Drawable[]
                                            {
                                                new Container
                                                {
                                                    RelativeSizeAxes = Axes.Both,
                                                    Children         = new[]
                                                    {
                                                        new Container
                                                        {
                                                            RelativeSizeAxes = Axes.Both,
                                                            Masking          = true,
                                                            CornerRadius     = 10,
                                                            Child            = new Box
                                                            {
                                                                RelativeSizeAxes = Axes.Both,
                                                                Colour           = Color4Extensions.FromHex(@"3e3a44") // Temporary.
                                                            },
                                                        },
                                                        new Container
                                                        {
                                                            RelativeSizeAxes = Axes.Both,
                                                            Padding          = new MarginPadding(20),
                                                            Child            = CreateMainContent(),
                                                        },
                                                        new Container
                                                        {
                                                            Anchor           = Anchor.BottomLeft,
                                                            Origin           = Anchor.BottomLeft,
                                                            RelativeSizeAxes = Axes.X,
                                                            AutoSizeAxes     = Axes.Y,
                                                            Child            = userModsSelectOverlay = new UserModSelectOverlay
                                                            {
                                                                SelectedMods = { BindTarget = UserMods },
                                                                IsValidMod   = _ => false
                                                            }
                                                        },
                                                    }
                                                }
                                            }
                                        }
                                    },
                                    new Container
                                    {
                                        RelativeSizeAxes = Axes.Both,
                                        // Resolves 1px masking errors between the settings overlay and the room panel.
                                        Padding = new MarginPadding(-1),
                                        Child   = settingsOverlay = CreateRoomSettingsOverlay(Room)
                                    }
                                },
                            },
                        },
                        // Footer
                        new Drawable[]
                        {
                            new Container
                            {
                                RelativeSizeAxes = Axes.Both,
                                Children         = new Drawable[]
                                {
                                    new Box
                                    {
                                        RelativeSizeAxes = Axes.Both,
                                        Colour           = Color4Extensions.FromHex(@"28242d") // Temporary.
                                    },
                                    new Container
                                    {
                                        RelativeSizeAxes = Axes.Both,
                                        Padding          = new MarginPadding(5),
                                        Child            = CreateFooter()
                                    },
                                }
                            }
                        }
                    }
                }
            };
        }
Example #47
0
        public void Run()
        {
            var s = new Sample(1);

            WriteLine(s.X);
        }
 private void load(AudioManager audio)
 {
     samplePopIn  = audio.Samples.Get(PopInSampleName);
     samplePopOut = audio.Samples.Get(PopOutSampleName);
 }
        private void PropertyControl_OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if (args.NewValue == _currentSample)
            {
                return;
            }

            _currentSample = DataContext as Sample;

            RootPanel.Children.Clear();

            if (_currentSample != null)
            {
                var propertyDesc = _currentSample.PropertyDescriptor;

                if (propertyDesc == null)
                {
                    return;
                }

                foreach (var option in propertyDesc.Options)
                {
                    // Label
                    var label = new TextBlock
                    {
                        Text       = option.Label + ":",
                        Foreground = new SolidColorBrush(Colors.Black)
                    };
                    RootPanel.Children.Add(label);

                    // Control
                    Control            controlToAdd;
                    DependencyProperty dependencyProperty;
                    IValueConverter    converter = null;

                    IDictionary <string, object> propertyDict = propertyDesc.Expando;

                    switch (option.Kind)
                    {
                    case PropertyKind.Slider:
                    case PropertyKind.DoubleSlider:
                        var slider       = new Slider();
                        var sliderOption = option as SliderPropertyOptions;
                        if (sliderOption != null)
                        {
                            slider.Minimum       = sliderOption.MinValue;
                            slider.Maximum       = sliderOption.MaxValue;
                            slider.StepFrequency = sliderOption.Step;
                        }

                        if (option.Kind == PropertyKind.DoubleSlider)
                        {
                            slider.StepFrequency = 0.01;
                        }

                        if ((propertyDict[option.Name] as ValueHolder).Value is double value)
                        {
                            slider.Value = value;
                        }

                        controlToAdd       = slider;
                        dependencyProperty = RangeBase.ValueProperty;

                        break;

                    case PropertyKind.Enum:
                        var enumType = option.DefaultValue.GetType();
                        var comboBox = new ComboBox
                        {
                            ItemsSource  = Enum.GetNames(enumType),
                            SelectedItem = (propertyDict[option.Name] as ValueHolder).Value.ToString()
                        };

                        converter          = new EnumConverter(enumType);
                        controlToAdd       = comboBox;
                        dependencyProperty = Selector.SelectedItemProperty;
                        break;

                    case PropertyKind.Bool:
                        var checkBox = new ToggleSwitch();

                        if ((propertyDict[option.Name] as ValueHolder).Value is bool isOn)
                        {
                            checkBox.IsOn = isOn;
                        }

                        controlToAdd       = checkBox;
                        dependencyProperty = ToggleSwitch.IsOnProperty;
                        break;

                    case PropertyKind.Brush:
                        var colorComboBox = new ComboBox();
                        var dataSource    = typeof(Colors).GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToList();
                        colorComboBox.ItemsSource = dataSource;

                        if ((propertyDict[option.Name] as ValueHolder).Value is SolidColorBrush brush &&
                            _colorNames.TryGetValue(brush.Color, out var color))
                        {
                            colorComboBox.SelectedIndex = dataSource.IndexOf(color);
                        }
                        else
                        {
                            colorComboBox.SelectedIndex = dataSource.IndexOf(option.DefaultValue.ToString());
                        }

                        converter = new SolidColorBrushConverter();

                        controlToAdd       = colorComboBox;
                        dependencyProperty = Selector.SelectedItemProperty;
                        break;
Example #50
0
 public IActionResult CreateSample([FromBody] Sample request)
 {
     return(Created(request));
 }
Example #51
0
 /// <summary>
 /// 初始化一个<see cref="TestBase"/>类型的实例
 /// </summary>
 public ReflectionsTest(ITestOutputHelper output) : base(output)
 {
     _sample = new Sample();
 }