Example #1
0
        public void Equals_TypesAreNotSame_ReturnsFalse()
        {
            var none1 = new None<string>();
            var none2 = new None<object>();

            Assert.IsFalse(none1.Equals(none2));
        }
Example #2
0
        public void Equals_TypesAreSame_ReturnsTrue()
        {
            var none1 = new None<string>();
            var none2 = new None<string>();

            Assert.IsTrue(none1.Equals(none2));
        }
 public void NoneIsAlwaysEqualToNone()
 {
     var none1 = new None<int>();
     var none2 = new None<string>();
     Assert.True(none1.Equals(none2));
     Assert.True(none2.Equals(none1));
 }
Example #4
0
        public Map(XmlElement map)
        {
            Row = int.Parse(map.GetAttribute("row"));
            Col = int.Parse(map.GetAttribute("col"));
            Places = new Place[Row, Col];
            PlaceIdToCoordinate = new Dictionary<int, Tuple<int, int>>();
            _MaxId = 0;

            for (int r = 0; r < Row; r++)
            {
                for (int c = 0; c < Col; c++)
                {
                    Places[r, c] = new None(0);
                }
            }

            foreach (XmlNode item in map.ChildNodes)
            {
                int r = int.Parse((item as XmlElement).GetAttribute("row"));
                int c = int.Parse((item as XmlElement).GetAttribute("col"));
                int id = int.Parse((item as XmlElement).GetAttribute("id"));
                NewInstanceFromXml(item, ref Places[r, c], id);
                PlaceIdToCoordinate.Add(id, new Tuple<int, int>(r, c));
                if (id > _MaxId)
                {
                    _MaxId = id;
                }
            }
        }
Example #5
0
 public TrackingResult()
 {
     RightHandRelPos = new None<Vector3D>();
       RightHandAngle = new None<Vector3D>();
       RightHandAbsPos = new None<window.Point>();
       DepthBoundingBoxes = new List<Rectangle>();
       ColorBoundingBoxes = new List<Rectangle>();
 }
        public void GetOrElse_OptionIsNone_DefaultValueReturned()
        {
            var option = new None<string>();

            var result = option.GetOrElse(() => "default value");

            Assert.AreEqual("default value", result);
        }
 public void NoneIsNotEqualToSome()
 {
     var none = new None<int>();
     var some = new Some<int>(42);
     Assert.False(none == some);
     Assert.False(some == none);
     Assert.True(none != some);
     Assert.True(some != none);
 }
 public void NoneEqualsNoneOperatorTest()
 {
     var none1 = new None<int>();
     var none2 = new None<string>();
     Assert.True(none1 == none2);
     Assert.True(none2 == none1);
     Assert.False(none1 != none2);
     Assert.False(none2 != none1);
 }
        public IOption<string> GetString(int id)
        {
            IOption<string> value = new None<string>();
            var convertedId = this.converter.Convert(id);

            if(convertedId > 0) {
                value = new Some<string>(loader.Load(convertedId));
            }

            return value;
        }
Example #10
0
        public void can_add_a_file_with_build_action_none()
        {
            var project = CsProjFile.CreateAtSolutionDirectory("MyProj", "myproj");
            var content = new None("packages.config");

            project.Add(content);

            project.Save();

            var project2 = CsProjFile.LoadFrom(project.FileName);
            project2.Find<None>("packages.config")
                .CopyToOutputDirectory.ShouldEqual(ContentCopy.Never);
        }
        public IMaybe<SequencedEvent> GetSequencedEvent()
        {
            IMaybe<SequencedEvent> result = new None<SequencedEvent>();

            _transactor.ApplyTransactionForLambda(() =>
            {
                var @event = from seq in _handlerSequenceRespository.GetEventSequence("Dispatcher")
                             from evt in _eventStore.GetNextEvent(seq)
                             select evt;

                result = from evt in @event
                         let t = evt.As<EventDescriptor>()
                         select new SequencedEvent(t);
            });

            return result;
        }
Example #12
0
        public TrackingResult(Option<Vector3D> relPos, Option<Vector3D> angle, 
        Image<Gray, Byte> smoothedDepth, List<Rectangle> depthBox, 
        Image<Gray, Byte> skin = null, List<Rectangle> colorBox = null)
        {
            RightHandRelPos = relPos;
              RightHandAngle = angle;
              DepthImage = smoothedDepth;
              DepthBoundingBoxes = depthBox;

              if (DepthBoundingBoxes.Count > 0) {
            var rect = DepthBoundingBoxes.Last();
            RightHandAbsPos = new Some<window.Point>(rect.Center());
              } else {
            RightHandAbsPos = new None<window.Point>();
              }

              ColorImage = skin;

              if (colorBox == null)
            colorBox = new List<Rectangle>();
              ColorBoundingBoxes = colorBox;
        }
 public override FilterNode <TValue>?Visit(CompareFilter <TValue> nodeIn, None args)
 {
     return(nodeIn with {
         Path = nodeIn.Path.ToFirstPascalCase()
     });
 }
Example #14
0
		public static bool op_GreaterThan (bool x, None y)
		{
			throw new NotImplementedException ();
		}
Example #15
0
		public static double op_Addition (bool x, None y)
		{
			throw new NotImplementedException ();
		}
Example #16
0
		public static double op_Addition ([NotNull] BooleanObject x, None y)
		{
			throw new NotImplementedException ();
		}
Example #17
0
 public void None_should_equal_none() =>
 True(None.Equals(None));
Example #18
0
        public void HasValue_ReturnsFalse()
        {
            var none = new None<object>();

            Assert.IsFalse(none.HasValue);
        }
Example #19
0
 public static bool op_Inequality(None x, double y)
 {
     throw new NotImplementedException();
 }
Example #20
0
        public void GetHashCode_ReturnsNegativeOne()
        {
            var none = new None<object>();

            Assert.AreEqual(-1, none.GetHashCode());
        }
 public static Maybe <TResult> ToSome <TResult>(this None none, Func <TResult> some)
 {
     return(Maybe <TResult> .Some(some()));
 }
Example #22
0
 static bool ruleDelegate(None component, None output)
 {
     Console.WriteLine("ruleDelegate called");
     return(false);
 }
 protected void reset(IList <IValue> Args, out IValue result)
 {
     result = new None();
     stream.Seek(0, System.IO.SeekOrigin.Begin);
 }
 public void Visit(None dataFormat, byte data)
 {
 }
Example #25
0
 public static bool op_LessThanOrEqual(ConcatString x, None y)
 {
     throw new NotImplementedException();
 }
Example #26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="detphFrame">raw detph data.</param>
        /// <param name="skeleton">skeleton object from Kinect SDK. The skeleton coordinate space has 
        /// the x-axis pointing rightwards, the y-axis pointing upwards, and the z-axis poining outwards
        /// relative to the image.</param>
        /// <returns>The position of the best bounding box relative to the shoulder joint in skeleton 
        /// coordinates if the bounding box is valid. Otherwise returns None.</returns>
        public TrackingResult Update(short[] depthFrame, byte[] colorFrame, Skeleton skeleton)
        {
            t++;

              Option<Vector3D> relPos = new None<Vector3D>();
              Option<Vector3D> angle = new None<Vector3D>();

              if (skeleton == null || depthFrame == null)
            return new TrackingResult();

              playerDetector.FilterPlayerContourSkin(depthFrame, colorFrame);
              var depthImage = playerDetector.DepthImage;
              smoothedDepth.CopyTo(prevSmoothedDepth);
              // Median smoothing cannot be in place.
              CvInvoke.cvSmooth(depthImage.Ptr, smoothedDepth.Ptr, SMOOTH_TYPE.CV_MEDIAN, 5, 5,
                        0, 0);

              if (t > 1) {
            CvInvoke.cvAbsDiff(smoothedDepth.Ptr, prevSmoothedDepth.Ptr, Diff0.Ptr);
            //CvInvoke.cvErode(Diff0.Ptr, Diff0.Ptr, StructuringElement.Ptr, 1);
            DiffMask0.CopyTo(DiffMask1);
            CvInvoke.cvThreshold(Diff0.Ptr, DiffMask0.Ptr, 2, 255, THRESH.CV_THRESH_BINARY);

            if (t > 2) {
              // Makes diffMask1 the motion mask at t - 1.
              CvInvoke.cvAnd(DiffMask0.Ptr, DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero);
              if (bufferSize <= 1) {
            // Makes diffMask1 the motion mask at t - 0.
            CvInvoke.cvXor(DiffMask0.Ptr, DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero);
              }
              CvInvoke.cvMorphologyEx(DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero, IntPtr.Zero,
                                  CV_MORPH_OP.CV_MOP_OPEN, 1);
              ComputeCumulativeDist(Diff0, diffCumulativeDist);
              ComputeCumulativeDist(TrackedDepthFrame, depthCumulativeDist);
              CvInvoke.cvZero(SaliencyProb);
              var diffMaskData = DiffMask1.Data;
              var diffData = Diff0.Data;
              var depthData = TrackedDepthFrame.Data;
              var probData = SaliencyProb.Data;
              for (int i = 0; i < DiffMask1.Height; i++)
            for (int j = 0; j < DiffMask1.Width; j++) {
              if (diffMaskData[i, j, 0] > 0) {
                var diffBin = diffData[i, j, 0];
                var depthBin = depthData[i, j, 0];
                probData[i, j, 0] = diffCumulativeDist[diffBin] * depthCumulativeDist[depthBin];
              }
            }
              PrevBoundingBoxes = FindBestBoundingBox(depthFrame, skeleton);
              if (PrevBoundingBoxes.LastOrDefault().Width > 0) {
            var handSkeletonPoint = SkeletonUtil.DepthToSkeleton(PrevBoundingBoxes.Last(),
                TrackedDepthFrame.Data, width, height, mapper);
            relPos = new Some<Vector3D>(SkeletonUtil.RelativePosToShoulder(handSkeletonPoint,
                                                                           skeleton));
            angle = new Some<Vector3D>(SkeletonUtil.PointDirection(handSkeletonPoint,
                SkeletonUtil.GetJoint(skeleton, JointType.ElbowRight).Position));
              } }
              }
              List<Rectangle> colorBBs = new List<Rectangle>();
              foreach (var bb in PrevBoundingBoxes) {
            var colorBox = mapper.MapDepthRectToColorRect(bb, depthFrame, width, height);
            playerDetector.SmoothSkin(colorBox);
            colorBBs.Add(colorBox);
              }
              return new TrackingResult(relPos, angle, TrackedDepthFrame, PrevBoundingBoxes,
              playerDetector.SkinImage, colorBBs);
        }
Example #27
0
        public void TestMethodNone()
        {
            var n = new None <int>();

            Assert.AreNotEqual(n, null);
        }
Example #28
0
 public static double op_BitwiseOr(None x, [NotNull] string y)
 {
     throw new NotImplementedException();
 }
Example #29
0
 public override FilterDefinition <T> Visit(NegateFilter <ClrValue> nodeIn, None args)
 {
     return(Filter.Not(nodeIn.Filter.Accept(this, args)));
 }
        public void An_Undefined_Value_Should_Have_Zero_Length()
        {
            // Arrange
            var strVal = new None<IExpressionConstant>();
            var filter = new SizeFilter();

            // Act
            var result = filter.ApplyToNil(new TemplateContext()).SuccessValue<NumericValue>();

            // Assert
            Assert.That(result.Value, Is.EqualTo(0));

        }
Example #31
0
 public static double op_BitwiseAnd(None x, [NotNull] UnDefined y)
 {
     throw new NotImplementedException();
 }
 public static IEnumerable <T> ToEnumerable <T>(this None source)
 {
     return(Enumerable.Empty <T>());
 }
Example #33
0
 public static double op_Division(None x, [NotNull] UnDefined y)
 {
     throw new NotImplementedException();
 }
        private static void DigestBuildItems(Project project, ProjectDigest projectDigest, string projectBasePath, ICollection <ProjectReference> projectReferences, ICollection <Reference> references, ICollection <Compile> compiles, ICollection <None> nones, ICollection <WebReferenceUrl> webReferenceUrls, ICollection <Content> contents, ICollection <Folder> folders, ICollection <WebReferences> webReferencesList, ICollection <EmbeddedResource> embeddedResources, ICollection <BootstrapperPackage> bootstrapperPackages, ICollection <string> globalNamespaceImports, IList <ComReference> comReferenceList)
        {
            string targetFramework = projectDigest.TargetFramework != null?projectDigest.TargetFramework.Substring(0, 3) : "2.0";

            RspUtility rsp = new RspUtility();

            foreach (BuildItemGroup buildItemGroup in project.ItemGroups)
            {
                foreach (BuildItem buildItem in buildItemGroup)
                {
                    if (!buildItem.IsImported)
                    {
                        switch (buildItem.Name)
                        {
                        case "ProjectReference":
                            ProjectReference prjRef = new ProjectReference(projectBasePath);
                            prjRef.ProjectPath = buildItem.Include;
                            prjRef.Name        = GetProjectAssemblyName(Path.GetFullPath(prjRef.ProjectFullPath));
                            prjRef.RoleType    = buildItem.GetMetadata("RoleType");
                            projectReferences.Add(prjRef);
                            break;

                        case "Reference":
                            Reference reference = new Reference(projectBasePath);
                            //set processorArchitecture property to platform, it will be used by GacUtility in
                            // order to resolve artifact to right processor architecture
                            if (!string.IsNullOrEmpty(projectDigest.Platform))
                            {
                                reference.ProcessorArchitecture = projectDigest.Platform;
                            }
                            string hintPath = buildItem.GetMetadata("HintPath");
                            if (!string.IsNullOrEmpty(hintPath))
                            {
                                string fullHint = Path.Combine(projectBasePath, hintPath);
                                if (File.Exists(fullHint))
                                {
                                    reference.HintPath = Path.GetFullPath(fullHint);
                                }
                                else
                                {
                                    reference.HintPath = fullHint;
                                }
                                SetReferenceFromFile(new FileInfo(fullHint), reference);
                            }
                            if (string.IsNullOrEmpty(reference.HintPath) || !(new FileInfo(reference.HintPath).Exists))
                            {
                                if (buildItem.Include.Contains(","))
                                {
                                    // complete name
                                    reference.SetAssemblyInfoValues(buildItem.Include);
                                }
                                else if (!rsp.IsRspIncluded(buildItem.Include, projectDigest.Language))
                                {
                                    // simple name needs to be resolved
                                    List <string> refs = GacUtility.GetInstance().GetAssemblyInfo(buildItem.Include, null, null);
                                    if (refs.Count == 0)
                                    {
                                        Console.WriteLine("Unable to find reference '" + buildItem.Include + "' in " + string.Join("; ", refs.ToArray()));
                                    }
                                    else if (refs.Count > 1)
                                    {
                                        string best          = null;
                                        string bestFramework = "0.0";
                                        foreach (string s in refs)
                                        {
                                            try
                                            {
                                                Assembly a         = Assembly.ReflectionOnlyLoad(s);
                                                string   framework = a.ImageRuntimeVersion.Substring(1, 3);
                                                if (framework.CompareTo(targetFramework) <= 0 && framework.CompareTo(bestFramework) > 0)
                                                {
                                                    best          = s;
                                                    bestFramework = framework;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                // skip this assembly
                                                Console.WriteLine("An error occurred loading assembly '" + s + "' - check that your PATH to gacutil matches your runtime environment: " + e.Message);
                                            }
                                        }
                                        reference.SetAssemblyInfoValues(best);
                                    }
                                    else
                                    {
                                        reference.SetAssemblyInfoValues(refs[0]);
                                    }
                                }
                            }
                            if ("NUnit.Framework".Equals(reference.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                reference.Name         = "NUnit.Framework";
                                projectDigest.UnitTest = true;
                            }
                            if (!string.IsNullOrEmpty(reference.Name))
                            {
                                references.Add(reference);
                            }
                            break;

                        case "Compile":
                            Compile compile = new Compile(projectBasePath);
                            compile.IncludePath           = buildItem.Include;
                            compile.AutoGen               = buildItem.GetMetadata("AutoGen");
                            compile.DesignTimeSharedInput = buildItem.GetMetadata("DesignTimeSharedInput");
                            compile.DependentUpon         = buildItem.GetMetadata("DependentUpon");
                            compile.DesignTime            = buildItem.GetMetadata("DesignTime");
                            compile.SubType               = buildItem.GetMetadata("SubType");
                            compiles.Add(compile);
                            break;

                        case "None":
                            None none = new None(projectBasePath);
                            none.IncludePath = buildItem.Include;

                            none.Link = buildItem.GetMetadata("Link");

                            none.Generator     = buildItem.GetMetadata("Generator");
                            none.LastGenOutput = buildItem.GetMetadata("LastGenOutput");
                            none.DependentUpon = buildItem.GetMetadata("DependentUpon");

                            nones.Add(none);

                            //add included web reference when reimporting
                            if (buildItem.Include.Contains(".wsdl"))
                            {
                                string path = Path.GetDirectoryName(buildItem.Include) + "\\";

                                WebReferenceUrl webUrl = new WebReferenceUrl();
                                webUrl.UrlBehavior = "Dynamic";
                                webUrl.RelPath     = path;

                                if (!webRefExists(webUrl, webReferenceUrls))
                                {
                                    webReferenceUrls.Add(webUrl);
                                }
                            }
                            break;

                        case "WebReferenceUrl":
                            WebReferenceUrl web = new WebReferenceUrl();
                            web.UrlBehavior                 = buildItem.GetMetadata("UrlBehavior");
                            web.RelPath                     = buildItem.GetMetadata("RelPath");
                            web.UpdateFromURL               = buildItem.GetMetadata("UpdateFromURL");
                            web.ServiceLocationURL          = buildItem.GetMetadata("ServiceLocationURL");
                            web.CachedDynamicPropName       = buildItem.GetMetadata("CachedDynamicPropName");
                            web.CachedAppSettingsObjectName = buildItem.GetMetadata("CachedAppSettingsObjectName");
                            web.CachedSettingsPropName      = buildItem.GetMetadata("CachedSettingsPropName");

                            if (!webRefExists(web, webReferenceUrls))
                            {
                                webReferenceUrls.Add(web);
                            }
                            break;

                        case "COMReference":
                            ComReference comRef = new ComReference();
                            comRef.Include      = buildItem.Include;
                            comRef.Guid         = buildItem.GetMetadata("Guid");
                            comRef.VersionMajor = buildItem.GetMetadata("VersionMajor");
                            comRef.VersionMinor = buildItem.GetMetadata("VersionMinor");
                            comRef.Lcid         = buildItem.GetMetadata("Lcid");
                            comRef.Isolated     = buildItem.GetMetadata("Isolated");
                            comRef.WrapperTool  = buildItem.GetMetadata("WrapperTool");
                            comReferenceList.Add(comRef);
                            break;

                        case "Content":
                            Content content = new Content(projectBasePath);
                            content.IncludePath = buildItem.Include;
                            contents.Add(content);

                            //add web reference in <includes> tag of compile-plugin
                            if (content.IncludePath.Contains("Web References"))
                            {
                                Compile compileWebRef = new Compile(projectBasePath);
                                compileWebRef.IncludePath = buildItem.Include;
                                compiles.Add(compileWebRef);
                            }
                            break;

                        case "Folder":
                            Folder folder = new Folder(projectBasePath);
                            folder.IncludePath = buildItem.Include;
                            folders.Add(folder);
                            break;

                        case "WebReferences":
                            WebReferences webReferences = new WebReferences(projectBasePath);
                            webReferences.IncludePath = buildItem.Include;
                            webReferencesList.Add(webReferences);
                            break;

                        case "EmbeddedResource":
                            EmbeddedResource embeddedResource = new EmbeddedResource(projectBasePath);
                            embeddedResource.IncludePath = buildItem.Include;

                            embeddedResource.DependentUpon = buildItem.GetMetadata("DependentUpon");
                            embeddedResource.SubType       = buildItem.GetMetadata("SubType");
                            embeddedResource.Generator     = buildItem.GetMetadata("Generator");
                            embeddedResource.LastGenOutput = buildItem.GetMetadata("LastGenOutput");

                            embeddedResources.Add(embeddedResource);
                            break;

                        case "BootstrapperPackage":
                            BootstrapperPackage bootstrapperPackage = new BootstrapperPackage(projectBasePath);
                            bootstrapperPackage.IncludePath = buildItem.Include;
                            bootstrapperPackage.Visible     = buildItem.GetMetadata("Visible");
                            bootstrapperPackage.ProductName = buildItem.GetMetadata("ProductName");
                            bootstrapperPackage.Install     = buildItem.GetMetadata("Install");


                            bootstrapperPackages.Add(bootstrapperPackage);
                            break;

                        case "Import":
                            globalNamespaceImports.Add(buildItem.Include);
                            break;

                        case "BaseApplicationManifest":
                            projectDigest.BaseApplicationManifest = buildItem.Include;
                            break;

                        default:
                            Console.WriteLine("Unhandled ItemGroup: " + buildItem.Name);
                            break;
                        }
                    }
                }
            }
        }
Example #35
0
        public void Value_ThrowsException()
        {
            var none = new None<object>();

            var value = none.Value;
        }
Example #36
0
        public void GetEnumerator_CountIsZero()
        {
            var none = new None<object>();

            Assert.AreEqual(0, none.Count());
        }
        public async Task <AttestationVerificationSuccess> VerifyAsync(CredentialCreateOptions originalOptions, Fido2Configuration config, IsCredentialIdUniqueToUserAsyncDelegate isCredentialIdUniqueToUser, IMetadataService metadataService, byte[] requestTokenBindingId)
        {
            // https://www.w3.org/TR/webauthn/#registering-a-new-credential
            // 1. Let JSONtext be the result of running UTF-8 decode on the value of response.clientDataJSON.
            // 2. Let C, the client data claimed as collected during the credential creation, be the result of running an implementation-specific JSON parser on JSONtext.
            // Note: C may be any implementation-specific data structure representation, as long as C’s components are referenceable, as required by this algorithm.
            // Above handled in base class constructor

            // 3. Verify that the value of C.type is webauthn.create
            if (Type != "webauthn.create")
            {
                throw new VerificationException("AttestationResponse is not type webauthn.create");
            }

            // 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call.
            // 5. Verify that the value of C.origin matches the Relying Party's origin.
            // 6. Verify that the value of C.tokenBinding.status matches the state of Token Binding for the TLS connection over which the assertion was obtained.
            // If Token Binding was used on that TLS connection, also verify that C.tokenBinding.id matches the base64url encoding of the Token Binding ID for the connection.
            BaseVerify(config.Origin, originalOptions.Challenge, requestTokenBindingId);

            if (Raw.Id == null || Raw.Id.Length == 0)
            {
                throw new VerificationException("AttestationResponse is missing Id");
            }

            if (Raw.Type != PublicKeyCredentialType.PublicKey)
            {
                throw new VerificationException("AttestationResponse is missing type with value 'public-key'");
            }

            var authData = new AuthenticatorData(AttestationObject.AuthData);

            // 7. Compute the hash of response.clientDataJSON using SHA-256.
            byte[] clientDataHash, rpIdHash;
            using (var sha = CryptoUtils.GetHasher(HashAlgorithmName.SHA256))
            {
                clientDataHash = sha.ComputeHash(Raw.Response.ClientDataJson);
                rpIdHash       = sha.ComputeHash(Encoding.UTF8.GetBytes(originalOptions.Rp.Id));
            }

            // 8. Perform CBOR decoding on the attestationObject field of the AuthenticatorAttestationResponse structure to obtain the attestation statement format fmt, the authenticator data authData, and the attestation statement attStmt.
            // Handled in AuthenticatorAttestationResponse::Parse()

            // 9. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party
            if (false == authData.RpIdHash.SequenceEqual(rpIdHash))
            {
                throw new VerificationException("Hash mismatch RPID");
            }

            // 10. Verify that the User Present bit of the flags in authData is set.
            if (false == authData.UserPresent)
            {
                throw new VerificationException("User Present flag not set in authenticator data");
            }

            // 11. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
            // see authData.UserVerified
            // TODO: Make this a configurable option and add check to require

            // 12. Verify that the values of the client extension outputs in clientExtensionResults and the authenticator extension outputs in the extensions in authData are as expected,
            // considering the client extension input values that were given as the extensions option in the create() call.  In particular, any extension identifier values
            // in the clientExtensionResults and the extensions in authData MUST be also be present as extension identifier values in the extensions member of options, i.e.,
            // no extensions are present that were not requested. In the general case, the meaning of "are as expected" is specific to the Relying Party and which extensions are in use.

            // TODO?: Implement sort of like this: ClientExtensions.Keys.Any(x => options.extensions.contains(x);

            if (false == authData.HasAttestedCredentialData)
            {
                throw new VerificationException("Attestation flag not set on attestation data");
            }

            // 13. Determine the attestation statement format by performing a USASCII case-sensitive match on fmt against the set of supported WebAuthn Attestation Statement Format Identifier values.
            // An up-to-date list of registered WebAuthn Attestation Statement Format Identifier values is maintained in the IANA registry of the same name
            // https://www.w3.org/TR/webauthn/#defined-attestation-formats
            AttestationVerifier verifier = default;

            switch (AttestationObject.Fmt)
            {
            case "none":
                verifier = new None();                  // https://www.w3.org/TR/webauthn/#none-attestation
                break;

            case "tpm":
                verifier = new Tpm();                   // https://www.w3.org/TR/webauthn/#tpm-attestation
                break;

            case "android-key":
                verifier = new AndroidKey();            // https://www.w3.org/TR/webauthn/#android-key-attestation
                break;

            case "android-safetynet":
                verifier = new AndroidSafetyNet(metadataService.TimestampDriftTolerance);      // https://www.w3.org/TR/webauthn/#android-safetynet-attestation
                break;

            case "fido-u2f":
                verifier = new FidoU2f();               // https://www.w3.org/TR/webauthn/#fido-u2f-attestation
                break;

            case "packed":
                verifier = new Packed();                // https://www.w3.org/TR/webauthn/#packed-attestation
                break;

            case "apple":
                verifier = new Apple();                 // https://www.w3.org/TR/webauthn/#apple-anonymous-attestation
                break;

            default:
                throw new VerificationException("Missing or unknown attestation type");
            }
            ;

            // 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature,
            // by using the attestation statement format fmt’s verification procedure given attStmt, authData and the hash of the serialized client data computed in step 7
            (var attType, var trustPath) = verifier.Verify(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash);

            // 15. If validation is successful, obtain a list of acceptable trust anchors (attestation root certificates or ECDAA-Issuer public keys) for that attestation type and attestation statement format fmt, from a trusted source or from policy.
            // For example, the FIDO Metadata Service [FIDOMetadataService] provides one way to obtain such information, using the aaguid in the attestedCredentialData in authData.
            var entry = metadataService?.GetEntry(authData.AttestedCredentialData.AaGuid);

            // while conformance testing, we must reject any authenticator that we cannot get metadata for
            if (metadataService?.ConformanceTesting() == true && null == entry && AttestationType.None != attType && "fido-u2f" != AttestationObject.Fmt)
            {
                throw new VerificationException("AAGUID not found in MDS test metadata");
            }

            if (null != trustPath)
            {
                // If the authenticator is listed as in the metadata as one that should produce a basic full attestation, build and verify the chain
                if ((entry?.MetadataStatement?.AttestationTypes.Contains(MetadataAttestationType.ATTESTATION_BASIC_FULL.ToEnumMemberValue()) ?? false) ||
                    (entry?.MetadataStatement?.AttestationTypes.Contains(MetadataAttestationType.ATTESTATION_PRIVACY_CA.ToEnumMemberValue()) ?? false))
                {
                    var attestationRootCertificates = entry.MetadataStatement.AttestationRootCertificates
                                                      .Select(x => new X509Certificate2(Convert.FromBase64String(x)))
                                                      .ToArray();

                    if (false == CryptoUtils.ValidateTrustChain(trustPath, attestationRootCertificates))
                    {
                        throw new VerificationException("Invalid certificate chain");
                    }
                }

                // If the authenticator is not listed as one that should produce a basic full attestation, the certificate should be self signed
                if ((!entry?.MetadataStatement?.AttestationTypes.Contains(MetadataAttestationType.ATTESTATION_BASIC_FULL.ToEnumMemberValue()) ?? false) &&
                    (!entry?.MetadataStatement?.AttestationTypes.Contains(MetadataAttestationType.ATTESTATION_PRIVACY_CA.ToEnumMemberValue()) ?? false) &&
                    (!entry?.MetadataStatement?.AttestationTypes.Contains(MetadataAttestationType.ATTESTATION_ANONCA.ToEnumMemberValue()) ?? false))
                {
                    if (trustPath.FirstOrDefault().Subject != trustPath.FirstOrDefault().Issuer)
                    {
                        throw new VerificationException("Attestation with full attestation from authenticator that does not support full attestation");
                    }
                }
            }

            // Check status resports for authenticator with undesirable status
            foreach (var report in entry?.StatusReports ?? Enumerable.Empty <StatusReport>())
            {
                if (true == Enum.IsDefined(typeof(UndesiredAuthenticatorStatus), (UndesiredAuthenticatorStatus)report.Status))
                {
                    throw new VerificationException("Authenticator found with undesirable status");
                }
            }

            // 16. Assess the attestation trustworthiness using the outputs of the verification procedure in step 14, as follows:
            // If self attestation was used, check if self attestation is acceptable under Relying Party policy.
            // If ECDAA was used, verify that the identifier of the ECDAA-Issuer public key used is included in the set of acceptable trust anchors obtained in step 15.
            // Otherwise, use the X.509 certificates returned by the verification procedure to verify that the attestation public key correctly chains up to an acceptable root certificate.

            // 17. Check that the credentialId is not yet registered to any other user.
            // If registration is requested for a credential that is already registered to a different user, the Relying Party SHOULD fail this registration ceremony, or it MAY decide to accept the registration, e.g. while deleting the older registration
            if (false == await isCredentialIdUniqueToUser(new IsCredentialIdUniqueToUserParams(authData.AttestedCredentialData.CredentialID, originalOptions.User)))
            {
                throw new VerificationException("CredentialId is not unique to this user");
            }

            // 18. If the attestation statement attStmt verified successfully and is found to be trustworthy, then register the new credential with the account that was denoted in the options.user passed to create(),
            // by associating it with the credentialId and credentialPublicKey in the attestedCredentialData in authData, as appropriate for the Relying Party's system.
            var result = new AttestationVerificationSuccess()
            {
                CredentialId = authData.AttestedCredentialData.CredentialID,
                PublicKey    = authData.AttestedCredentialData.CredentialPublicKey.GetBytes(),
                User         = originalOptions.User,
                Counter      = authData.SignCount,
                CredType     = AttestationObject.Fmt,
                Aaguid       = authData.AttestedCredentialData.AaGuid,
            };

            return(result);
            // 19. If the attestation statement attStmt successfully verified but is not trustworthy per step 16 above, the Relying Party SHOULD fail the registration ceremony.
            // This implementation throws if the outputs are not trustworthy for a particular attestation type.
        }
Example #38
0
 private IMaybe<SequencedEvent> GetSequencedEvent()
 {
     IMaybe<SequencedEvent> sequencedEvent = new None<SequencedEvent>();
     _errorReporter.ReportErrorForScope(() => sequencedEvent = _sequencedEventSelector.GetSequencedEvent());
     return sequencedEvent;
 }
 public static void doDone(None ra)
 {
     ra.dump();
 }
 public void Visit(None dataFormat, byte data) => currentChange.ChangeData(buffer, index, 0xFF);
Example #41
0
		public static bool op_LessThanOrEqual (bool x, None y)
		{
			throw new NotImplementedException ();
		}
Example #42
0
        public Tuple<AST.Env, AST.ExprType, Option<AST.Initr>, String> GetInitDeclr(AST.Env env, AST.ExprType type) {
            String name;
            Option<AST.Initr> initr_opt;

            // Get the initializer list.
            Option<Tuple<AST.Env, AST.Initr>> r_initr = this.initr.Map(_ => _.GetInitr(env));
            if (r_initr.IsSome) {
                env = r_initr.Value.Item1;
                initr_opt = new Some<AST.Initr>(r_initr.Value.Item2);
            } else {
                initr_opt = new None<AST.Initr>();
            }

            // Get the declarator.
            Tuple<String, AST.ExprType> r_declr = declr.GetNameAndType(env, type);
            name = r_declr.Item1;
            type = r_declr.Item2;

            // Implicit cast the initializer.
            initr_opt = initr_opt.Map(_ => _.ConformType(type));

            // If the object is an incomplete list, we must determine the length based on the initializer.
            if (type.kind == AST.ExprType.Kind.INCOMPLETE_ARRAY) {
                if (initr_opt.IsNone) {
                    throw new InvalidOperationException("Cannot determine the length of the array.");
                }

                // Now we need to determine the length.
                // Find the last element in the init list.
                Int32 last_offset = -1;
                initr_opt.Value.Iterate(type, (offset, _) => { last_offset = offset; });

                if (last_offset == -1) {
                    throw new InvalidOperationException("Cannot determine the length of the array based on an empty initializer list.");
                }

                AST.ExprType elem_type = ((AST.TIncompleteArray)type).elem_type;

                Int32 num_elems = 1 + last_offset / ((AST.TIncompleteArray)type).elem_type.SizeOf;

                type = new AST.TArray(elem_type, num_elems, type.is_const, type.is_volatile);
            }

            return new Tuple<AST.Env, AST.ExprType, Option<AST.Initr>, String>(env, type, initr_opt, name);
        }
Example #43
0
		public static bool op_Inequality (bool x, None y)
		{
			throw new NotImplementedException ();
		}
        public void PropertyTests()
        {
            string[]  array  = { "abc", "bca", "xyz", "qrs" };
            string[]  array2 = { "a", "ab", "abc" };
            ArrayList list   = new ArrayList(array);

            // Not available using the classic syntax

            // Helper syntax
            Assert.That(list, Has.Property("Count"));
            Assert.That(list, Has.No.Property("Length"));

            Assert.That("Hello", Has.Property("Length", 5));
            Assert.That("Hello", Has.Length(5));
            Assert.That("Hello", Has.Property("Length").EqualTo(5));
            Assert.That("Hello", Has.Property("Length").GreaterThan(3));

            Assert.That(array, Has.Property("Length", 4));
            Assert.That(array, Has.Length(4));
            Assert.That(array, Has.Property("Length").LessThan(10));

            Assert.That(array, Has.All.Property("Length", 3));
            Assert.That(array, Has.All.Length(3));
            Assert.That(array, Is.All.Length(3));
            Assert.That(array, Has.All.Property("Length").EqualTo(3));
            Assert.That(array, Is.All.Property("Length").EqualTo(3));

            Assert.That(array2, Has.Some.Property("Length", 2));
            Assert.That(array2, Has.Some.Length(2));
            Assert.That(array2, Has.Some.Property("Length").GreaterThan(2));

            Assert.That(array2, Is.Not.Property("Length", 4));
            Assert.That(array2, Is.Not.Length(4));
            Assert.That(array2, Has.No.Property("Length").GreaterThan(3));

            Assert.That(List.Map(array2).Property("Length"), Is.EqualTo(new int[] { 1, 2, 3 }));
            Assert.That(List.Map(array2).Property("Length"), Is.EquivalentTo(new int[] { 3, 2, 1 }));
            Assert.That(List.Map(array2).Property("Length"), Is.SubsetOf(new int[] { 1, 2, 3, 4, 5 }));
            Assert.That(List.Map(array2).Property("Length"), Is.Unique);

            Assert.That(list, Has.Count(4));

            // Inherited syntax
            Expect(list, Property("Count"));
            Expect(list, Not.Property("Nada"));

            Expect("Hello", Property("Length", 5));
            Expect("Hello", Length(5));
            Expect("Hello", Property("Length").EqualTo(5));
            Expect("Hello", Property("Length").GreaterThan(0));

            Expect(array, Property("Length", 4));
            Expect(array, Length(4));
            Expect(array, Property("Length").LessThan(10));

            Expect(array, All.Property("Length", 3));
            Expect(array, All.Length(3));
            Expect(array, All.Property("Length").EqualTo(3));

            Expect(array2, Some.Property("Length", 2));
            Expect(array2, Some.Length(2));
            Expect(array2, Some.Property("Length").GreaterThan(2));

            Expect(array2, None.Property("Length", 4));
            Expect(array2, None.Length(4));
            Expect(array2, None.Property("Length").GreaterThan(3));

            Expect(Map(array2).Property("Length"), EqualTo(new int[] { 1, 2, 3 }));
            Expect(Map(array2).Property("Length"), EquivalentTo(new int[] { 3, 2, 1 }));
            Expect(Map(array2).Property("Length"), SubsetOf(new int[] { 1, 2, 3, 4, 5 }));
            Expect(Map(array2).Property("Length"), Unique);

            Expect(list, Count(4));
        }
        public AttestationVerificationSuccess VerifyCredentialCreateOptions(RegisterCredentialOptions originalOptions, Fido2Configuration config, IsCredentialIdUniqueToUserDelegate isCredentialIdUniqueToUser, IMetadataService metadataService, byte[] requestTokenBindingId)
        {
            BaseVerify(config.Origin, originalOptions.Challenge, requestTokenBindingId);
            // verify challenge is same as we expected
            // verify origin
            // done in baseclass

            if (Type != "webauthn.create")
            {
                throw new VerificationException("AttestationResponse is not type webauthn.create");
            }

            if (Raw.Id == null || Raw.Id.Length == 0)
            {
                throw new VerificationException("AttestationResponse is missing Id");
            }

            if (Raw.Type != PublicKeyCredentialType.PublicKey)
            {
                throw new VerificationException("AttestationResponse is missing type with value 'public-key'");
            }

            if (null == AttestationObject.AuthData || 0 == AttestationObject.AuthData.Length)
            {
                throw new VerificationException("Missing or malformed authData");
            }

            var authData = new AuthenticatorData(AttestationObject.AuthData);

            // 6
            //todo:  Verify that the value of C.tokenBinding.status matches the state of Token Binding for the TLS connection
            // over which the assertion was obtained.If Token Binding was used on that TLS connection,
            // also verify that C.tokenBinding.id matches the base64url encoding of the Token Binding ID for the connection.
            // This is done in BaseVerify.
            // TODO: test that implmentation

            // 7
            // Compute the hash of response.clientDataJSON using SHA - 256.
            byte[] clientDataHash, rpIdHash;
            using (var sha = CryptoUtils.GetHasher(HashAlgorithmName.SHA256))
            {
                clientDataHash = sha.ComputeHash(Raw.Response.ClientDataJson);
                rpIdHash       = sha.ComputeHash(Encoding.UTF8.GetBytes(originalOptions.Rp.Id));
            }

            // 9
            // Verify that the RP ID hash in authData is indeed the SHA - 256 hash of the RP ID expected by the RP.
            if (false == authData.RpIdHash.SequenceEqual(rpIdHash))
            {
                throw new VerificationException("Hash mismatch RPID");
            }

            // 10
            // Verify that the User Present bit of the flags in authData is set.
            if (false == authData.UserPresent)
            {
                throw new VerificationException("User Present flag not set in authenticator data");
            }

            // 11
            // If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
            // see authData.UserVerified

            // 12
            // Verify that the values of the client extension outputs in clientExtensionResults and the authenticator extension outputs in the extensions in authData are as expected
            // todo: Implement sort of like this: ClientExtensions.Keys.Any(x => options.extensions.contains(x);

            if (false == authData.HasAttestedCredentialData)
            {
                throw new VerificationException("Attestation flag not set on attestation data");
            }

            // 13
            // Determine the attestation statement format by performing a US ASCII case-sensitive match on fmt against the set of supported WebAuthn Attestation Statement Format Identifier values. The up-to-date list of registered WebAuthn Attestation Statement Format Identifier values is maintained in the in the IANA registry of the same name [WebAuthn-Registries].
            // https://www.w3.org/TR/webauthn/#defined-attestation-formats
            AttestationFormat.AttestationFormat verifier;
            switch (AttestationObject.Fmt)
            {
            // 14
            // validate the attStmt
            case "none":
                // https://www.w3.org/TR/webauthn/#none-attestation
                verifier = new None(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash);
                break;

            case "tpm":
                // https://www.w3.org/TR/webauthn/#tpm-attestation
                verifier = new Tpm(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash, config.RequireValidAttestationRoot);
                break;

            case "android-key":
                // https://www.w3.org/TR/webauthn/#android-key-attestation
                verifier = new AndroidKey(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash);
                break;

            case "android-safetynet":
                // https://www.w3.org/TR/webauthn/#android-safetynet-attestation
                verifier = new AndroidSafetyNet(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash, config.TimestampDriftTolerance);
                break;

            case "fido-u2f":
                // https://www.w3.org/TR/webauthn/#fido-u2f-attestation
                verifier = new FidoU2f(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash, metadataService, config.RequireValidAttestationRoot);
                break;

            case "packed":
                // https://www.w3.org/TR/webauthn/#packed-attestation
                verifier = new Packed(AttestationObject.AttStmt, AttestationObject.AuthData, clientDataHash, metadataService, config.RequireValidAttestationRoot);
                break;

            default: throw new VerificationException("Missing or unknown attestation type");
            }

            verifier.Verify();

            /*
             * 15
             * If validation is successful, obtain a list of acceptable trust anchors (attestation root certificates or ECDAA-Issuer public keys)
             * for that attestation type and attestation statement format fmt, from a trusted source or from policy.
             * For example, the FIDO Metadata Service [FIDOMetadataService] provides one way to obtain such information,
             * using the aaguid in the attestedCredentialData in authData.
             * */

            /*
             * 16
             * Assess the attestation trustworthiness using the outputs of the verification procedure in step 14, as follows: https://www.w3.org/TR/webauthn/#registering-a-new-credential
             * */
            // use aaguid (authData.AttData.Aaguid) to find root certs in metadata
            // use root plus trustPath to build trust chain
            // implemented for AttestationObject.Fmt == "packed" in packed specific verifier

            /*
             * 17
             * Check that the credentialId is not yet registered to any other user.
             * If registration is requested for a credential that is already registered to a different user, the Relying Party SHOULD fail this registration ceremony, or it MAY decide to accept the registration, e.g. while deleting the older registration.
             * */
            if (false == isCredentialIdUniqueToUser(new IsCredentialIdUniqueToUserParams(authData.AttestedCredentialData.CredentialID, originalOptions.User)))
            {
                throw new VerificationException("CredentialId is not unique to this user");
            }

            /*
             * 18
             * If the attestation statement attStmt verified successfully and is found to be trustworthy, then register the new credential with the account that was denoted in the options.user passed to create(), by associating it with the credentialId and credentialPublicKey in the attestedCredentialData in authData, as appropriate for the Relying Party's system.
             * */
            // This is handled by code att call site and result object.


            /*
             * 19
             * If the attestation statement attStmt successfully verified but is not trustworthy per step 16 above, the Relying Party SHOULD fail the registration ceremony.
             * NOTE: However, if permitted by policy, the Relying Party MAY register the credential ID and credential public key but treat the credential as one with self attestation (see §6.3.3 Attestation Types). If doing so, the Relying Party is asserting there is no cryptographic proof that the public key credential has been generated by a particular authenticator model. See [FIDOSecRef] and [UAFProtocol] for a more detailed discussion.
             * */

            var result = new AttestationVerificationSuccess()
            {
                CredentialId = authData.AttestedCredentialData.CredentialID,
                PublicKey    = authData.AttestedCredentialData.CredentialPublicKey.GetBytes(),
                User         = originalOptions.User,
                Counter      = authData.SignCount,
                CredType     = AttestationObject.Fmt,
                Aaguid       = authData.AttestedCredentialData.AaGuid,
            };

            return(result);
        }
 public AssemblySpecification(Predicate<string> filter)
 {
     This = new None<Assembly>();
     Filter = filter;
 }
Example #47
0
        // ReSharper disable once UnusedParameter.Local - unit param used to
        // prevent JSON serializer from using this constructor to create an invalid maybe.
        private Maybe(None _)
        {
            Option = Option <T> .None();

            CorrectlyLoad = true;
        }
 public override FilterNode <TValue>?Visit(CompareFilter <TValue> nodeIn, None args)
 {
     return(new CompareFilter <TValue>(nodeIn.Path.Select(x => x.ToPascalCase()).ToList(), nodeIn.Operator, nodeIn.Value));
 }
Example #49
0
        private static void Main(string[] args)
        {
            #region Exercise 1

            Console.WriteLine("Exercise1");

            INumberVisitor Vis = new NumberVisitor();
            INumber Barry = new MyFloat(2);
            INumber Henk = new MyFloat(3);

            Barry.Visit(Vis);
            Console.WriteLine("");

            #endregion Exercise 1

            #region Exercise 2

            Console.WriteLine("Exercise2");

            IMusicLibraryVisitor MusicLibraryVisitor = new MusicLibraryVisitor();

            ISong HMSong1 = new HeavyMetal("Super Kill");
            ISong JSong1 = new Jazz("Frank Sinatra: The Very Best Of");

            List<ISong> SongList = new List<ISong>();
            SongList.Add(HMSong1);
            SongList.Add(JSong1);

            foreach (ISong Song in SongList)
            {
                Song.Visit(MusicLibraryVisitor);
            }

            Console.WriteLine("");

            #endregion Exercise 2

            #region Exercise 3

            Console.WriteLine("Exercise3");

            IOption<int> TestInt1 = new Some<int>(5);
            IOption<int> TestInt2 = new None<int>();
            I_IntPrettyPrinterIOptionVisitor IntPrint = new IntPrettyPrinterIOptionVisitor();

            string TestString1 = TestInt1.Visit(IntPrint);
            Console.WriteLine(TestString1);

            Console.WriteLine("");

            #endregion Exercise 3

            #region Exercise 4

            Console.WriteLine("Exercise4");

            IOptionLambda<MyFloat> f1 = new NoneLambda<MyFloat>();
            string new_number1 = f1.Visit(x => x.value.ToString(), () => "Nothing here, b0ss.");
            Console.WriteLine(new_number1);

            IOptionLambda<MyFloat> f2 = new SomeLambda<MyFloat>(new MyFloat(5));
            string new_number2 = f2.Visit(x => "The number is " + x.value.ToString() + "! :D", () => "Nothing here, b0ss.");
            Console.WriteLine(new_number2);

            #endregion Exercise 4

            Console.ReadKey();
        }
Example #50
0
File: Any.cs Project: gavin-zyi/Rin
 static Any()
 {
     None = new None();
 }
 public static Maybe <T> ToMaybe <T>(this None none)
 {
     return(Maybe <T> .None());
 }
Example #52
0
        public void Write(TProtocol oprot)
        {
            TStruct struc = new TStruct("Grouping");

            oprot.WriteStructBegin(struc);
            TField field = new TField();

            if (Fields != null && __isset.fields)
            {
                field.Name = "fields";
                field.Type = TType.List;
                field.ID   = 1;
                oprot.WriteFieldBegin(field);
                {
                    oprot.WriteListBegin(new TList(TType.String, Fields.Count));
                    foreach (string _iter7 in Fields)
                    {
                        oprot.WriteString(_iter7);
                    }
                    oprot.WriteListEnd();
                }
                oprot.WriteFieldEnd();
            }
            if (Shuffle != null && __isset.shuffle)
            {
                field.Name = "shuffle";
                field.Type = TType.Struct;
                field.ID   = 2;
                oprot.WriteFieldBegin(field);
                Shuffle.Write(oprot);
                oprot.WriteFieldEnd();
            }
            if (All != null && __isset.all)
            {
                field.Name = "all";
                field.Type = TType.Struct;
                field.ID   = 3;
                oprot.WriteFieldBegin(field);
                All.Write(oprot);
                oprot.WriteFieldEnd();
            }
            if (None != null && __isset.none)
            {
                field.Name = "none";
                field.Type = TType.Struct;
                field.ID   = 4;
                oprot.WriteFieldBegin(field);
                None.Write(oprot);
                oprot.WriteFieldEnd();
            }
            if (Direct != null && __isset.direct)
            {
                field.Name = "direct";
                field.Type = TType.Struct;
                field.ID   = 5;
                oprot.WriteFieldBegin(field);
                Direct.Write(oprot);
                oprot.WriteFieldEnd();
            }
            if (Custom_object != null && __isset.custom_object)
            {
                field.Name = "custom_object";
                field.Type = TType.Struct;
                field.ID   = 6;
                oprot.WriteFieldBegin(field);
                Custom_object.Write(oprot);
                oprot.WriteFieldEnd();
            }
            if (Custom_serialized != null && __isset.custom_serialized)
            {
                field.Name = "custom_serialized";
                field.Type = TType.String;
                field.ID   = 7;
                oprot.WriteFieldBegin(field);
                oprot.WriteBinary(Custom_serialized);
                oprot.WriteFieldEnd();
            }
            if (Local_or_shuffle != null && __isset.local_or_shuffle)
            {
                field.Name = "local_or_shuffle";
                field.Type = TType.Struct;
                field.ID   = 8;
                oprot.WriteFieldBegin(field);
                Local_or_shuffle.Write(oprot);
                oprot.WriteFieldEnd();
            }
            oprot.WriteFieldStop();
            oprot.WriteStructEnd();
        }
Example #53
0
 public static double op_BitwiseOr(None x, JSObject y)
 {
     throw new NotImplementedException();
 }
Example #54
0
    /// <summary>
    /// array_modifier
    ///   : '[' [constant_expression]? ']'
    /// </summary>
    public static Int32 ParseArrayModifier(List<Token> src, Int32 begin, out ArrayModifier modifier)
    {
        // match '['
        if (!Parser.EatOperator(src, ref begin, OperatorVal.LBRACKET)) {
            modifier = null;
            return -1;
        }

        // match constant_expression, if fail, just put null
        Expr num_elems;
        Option<Expr> num_elems_opt;
        Int32 saved = begin;
        if ((begin = _constant_expression.Parse(src, begin, out num_elems)) == -1) {
            num_elems_opt = new None<Expr>();
            begin = saved;
        } else {
            num_elems_opt = new Some<Expr>(num_elems);
        }

        // match ']'
        if (!Parser.EatOperator(src, ref begin, OperatorVal.RBRACKET)) {
            modifier = null;
            return -1;
        }

        modifier = new ArrayModifier(num_elems_opt);
        return begin;
    }
Example #55
0
 public static double op_Division(None x, JSObject y)
 {
     throw new NotImplementedException();
 }
Example #56
0
File: Any.cs Project: gavin-zyi/Rin
 static Any()
 {
     None = new None();
 }
Example #57
0
 public static double op_Division(None x, [NotNull] string y)
 {
     throw new NotImplementedException();
 }
Example #58
0
 public static double op_Addition([NotNull] BooleanObject x, None y)
 {
     throw new NotImplementedException();
 }
Example #59
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="detphFrame">raw detph data.</param>
        /// <param name="skeleton">skeleton object from Kinect SDK. The skeleton coordinate space has
        /// the x-axis pointing rightwards, the y-axis pointing upwards, and the z-axis poining outwards
        /// relative to the image.</param>
        /// <returns>The position of the best bounding box relative to the shoulder joint in skeleton
        /// coordinates if the bounding box is valid. Otherwise returns None.</returns>
        public TrackingResult Update(short[] depthFrame, byte[] colorFrame, Skeleton skeleton)
        {
            t++;

            Option <Vector3D> relPos = new None <Vector3D>();
            Option <Vector3D> angle  = new None <Vector3D>();

            if (skeleton == null || depthFrame == null)
            {
                return(new TrackingResult());
            }

            playerDetector.FilterPlayerContourSkin(depthFrame, colorFrame);
            var depthImage = playerDetector.DepthImage;

            smoothedDepth.CopyTo(prevSmoothedDepth);
            // Median smoothing cannot be in place.
            CvInvoke.cvSmooth(depthImage.Ptr, smoothedDepth.Ptr, SMOOTH_TYPE.CV_MEDIAN, 5, 5,
                              0, 0);

            if (t > 1)
            {
                CvInvoke.cvAbsDiff(smoothedDepth.Ptr, prevSmoothedDepth.Ptr, Diff0.Ptr);
                //CvInvoke.cvErode(Diff0.Ptr, Diff0.Ptr, StructuringElement.Ptr, 1);
                DiffMask0.CopyTo(DiffMask1);
                CvInvoke.cvThreshold(Diff0.Ptr, DiffMask0.Ptr, 2, 255, THRESH.CV_THRESH_BINARY);

                if (t > 2)
                {
                    // Makes diffMask1 the motion mask at t - 1.
                    CvInvoke.cvAnd(DiffMask0.Ptr, DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero);
                    if (bufferSize <= 1)
                    {
                        // Makes diffMask1 the motion mask at t - 0.
                        CvInvoke.cvXor(DiffMask0.Ptr, DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero);
                    }
                    CvInvoke.cvMorphologyEx(DiffMask1.Ptr, DiffMask1.Ptr, IntPtr.Zero, IntPtr.Zero,
                                            CV_MORPH_OP.CV_MOP_OPEN, 1);
                    ComputeCumulativeDist(Diff0, diffCumulativeDist);
                    ComputeCumulativeDist(TrackedDepthFrame, depthCumulativeDist);
                    CvInvoke.cvZero(SaliencyProb);
                    var diffMaskData = DiffMask1.Data;
                    var diffData     = Diff0.Data;
                    var depthData    = TrackedDepthFrame.Data;
                    var probData     = SaliencyProb.Data;
                    for (int i = 0; i < DiffMask1.Height; i++)
                    {
                        for (int j = 0; j < DiffMask1.Width; j++)
                        {
                            if (diffMaskData[i, j, 0] > 0)
                            {
                                var diffBin  = diffData[i, j, 0];
                                var depthBin = depthData[i, j, 0];
                                probData[i, j, 0] = diffCumulativeDist[diffBin] * depthCumulativeDist[depthBin];
                            }
                        }
                    }
                    PrevBoundingBoxes = FindBestBoundingBox(depthFrame, skeleton);
                    if (PrevBoundingBoxes.LastOrDefault().Width > 0)
                    {
                        var handSkeletonPoint = SkeletonUtil.DepthToSkeleton(PrevBoundingBoxes.Last(),
                                                                             TrackedDepthFrame.Data, width, height, mapper);
                        relPos = new Some <Vector3D>(SkeletonUtil.RelativePosToShoulder(handSkeletonPoint,
                                                                                        skeleton));
                        angle = new Some <Vector3D>(SkeletonUtil.PointDirection(handSkeletonPoint,
                                                                                SkeletonUtil.GetJoint(skeleton, JointType.ElbowRight).Position));
                    }
                }
            }
            List <Rectangle> colorBBs = new List <Rectangle>();

            foreach (var bb in PrevBoundingBoxes)
            {
                var colorBox = mapper.MapDepthRectToColorRect(bb, depthFrame, width, height);
                playerDetector.SmoothSkin(colorBox);
                colorBBs.Add(colorBox);
            }
            return(new TrackingResult(relPos, angle, TrackedDepthFrame, PrevBoundingBoxes,
                                      playerDetector.SkinImage, colorBBs));
        }
Example #60
0
        public void IEquatableEquals_ReturnsFalse()
        {
            var none = new None<object>();

            Assert.IsFalse(((IEquatable<object>)none).Equals(new object()));
        }