Пример #1
0
        /// <summary>
        /// reads the testdata in and predicts them.
        /// </summary>
        /// <param name="rm">Readmethod e.g JSON or .CSV</param>
        /// <param name="evalr">An IEvaluator</param>
        /// <param name="filename">Where to read from</param>
        /// <returns>IEnumerable of predicted testdata</returns>

        public static IEnumerable <Result> ConvertTestData(IOReadTestMethod rm, IEvaluator evalr, string filename)
        {
            var cBag = new ConcurrentBag <Result>();

            using (var finished = new CountdownEvent(1))
            {
                foreach ((string rating, string original) in rm(filename))
                {
                    finished.AddCount();
                    ThreadPool.QueueUserWorkItem(
                        (state) =>
                    {
                        try
                        {
                            cBag.Add(new Result((new TUID(Thread.CurrentThread.ManagedThreadId + DateTime.Today.Millisecond, original)), Program.InternConcurrentSafe(evalr.Evaluation(float.Parse(rating)).Item1), float.Parse(rating)));
                        }
                        finally
                        {
                            finished.Signal();
                        }
                    }, null);
                }
                finished.Signal();
                finished.Wait();
            }
            return(cBag);
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        public Rule Validate(QueryProvider qp)
        {
            if (null == DateTimeMathParser.ToDuration(Frequency, TimeUnit.Second))
            {
                AlertValidationException.ThrowBadParseFrequency();
            }

            if (!string.IsNullOrEmpty(For) && !DateTimeMathParser.ToDuration(For, TimeUnit.Second).HasValue)
            {
                AlertValidationException.ThrowBadParseFor();
            }

            if (null == Conditions || 0 == Conditions.Length)
            {
                AlertValidationException.ThrowNoCondtitions();
            }

            if (!Enum.IsDefined(typeof(NoDataOptions), NoDataOption))
            {
                AlertValidationException.ThrowBadParseNoDataOption();
            }

            if (!Enum.IsDefined(typeof(ErrorOptions), ErrorOption))
            {
                AlertValidationException.ThrowBadParseErrorOption();
            }

            Conditions
            .ToList()
            .ForEach(c => c.Validate(qp));

            return(this);
        }
Пример #3
0
 public void One_Pair_At_The_Same_Position_Is_Returned(PairSelector implementation)
 => TestWithPairSelect(implementation, () =>
 {
     _left.Add("A");
     _right.Add("A");
     ExpectNumberOfPairs(1);
     ExpectExactlyOnePairOf(("A", "A"));
Пример #4
0
        private async Task LoadMultipleValues(LoadItems fetchingFunc)
        {
            IsLoading = true;
            var location = await LocationProvider.GetLocation();

            await DisplayValues(fetchingFunc(location));

            IsLoading = false;
        }
Пример #5
0
        public PaginatedMessage(BotCommandContext context, IUserMessage message, int count, int initial, PageAction action) : base(context, message, new Dictionary <string, ReactionAction>(), true)
        {
            if (count < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            if (initial < 1 || initial > count)
            {
                throw new ArgumentOutOfRangeException(nameof(initial));
            }

            PageCount   = count;
            CurrentPage = initial;
            OnChage     = action;
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        public void Validate(QueryProvider qp)
        {
            if (null == Query)
            {
                AlertValidationException.ThrowBadQuery();
            }

            if (null == Evaluator)
            {
                AlertValidationException.ThrowBadEvaluator();
            }

            Query.Validate(qp);
            Evaluator.Validate();
        }
Пример #7
0
        public static void CreatePaginatedMessage(BotCommandContext context, IUserMessage message, int pageCount, int initialPage, PageAction action, int timeout = 300000, Action onTimeout = null)
        {
            if (pageCount == 1)
            {
                return;
            }
            message.AddReactionsAsync(new[] { new Emoji(PaginatedMessage.FirstPage), new Emoji(PaginatedMessage.PreviousPage), new Emoji(PaginatedMessage.NextPage), new Emoji(PaginatedMessage.LastPage) });

            var paginatedMessage = new PaginatedMessage(context, message, pageCount, initialPage, action);

            ReactionMessageCache.Add(message.Id.ToString(), paginatedMessage, new CacheItemPolicy {
                SlidingExpiration = TimeSpan.FromMilliseconds(timeout), RemovedCallback = onTimeout == null ? null : (CacheEntryRemovedCallback)(_ => onTimeout())
            });
        }
Пример #8
0
 public void If_One_List_Is_Empty_The_Result_Is_Empty(PairSelector implementation)
 => TestWithImplementationAndWithSymmetricalSetups(implementation, (first, second) =>
 {
     second.Add("A");
     ExpectNumberOfPairs(0);
 });
Пример #9
0
 public ResponderChannel(RSocket socket, int channelId, ReadOnlySequence <byte> metadata, ReadOnlySequence <byte> data, int initialRequest, Channeler channeler) : base(socket, channelId, initialRequest)
 {
     this.Metadata   = metadata;
     this.Data       = data;
     this._channeler = channeler;
 }
Пример #10
0
 public Lazy(System.Func <T> constructor)
 {
     this.constructor = constructor;
 }
Пример #11
0
    void ParseNextMp4Header()
    {
        //	check if there's more data to be read
        var KnownFileSize = GetKnownFileSize();

        if (Mp4BytesRead >= KnownFileSize)
        {
            return;
        }


        int TimeOffset = 0;

        System.Action <PopX.Mpeg4.TTrack> EnumTrack = (Track) =>
        {
            System.Action <byte[], int> PushPacket;

            byte[] Sps_AnnexB;
            byte[] Pps_AnnexB;

            //	track has header (so if we have moov and moof's, this only comes up once, and that's when we need to decode SPS/PPS
            if (Track.SampleDescriptions != null)
            {
                if (Track.SampleDescriptions[0].Fourcc != "avc1")
                {
                    throw new System.Exception("Expecting fourcc avc1, got " + Track.SampleDescriptions[0].Fourcc);
                }

                H264.AvccHeader Header;
                Header = PopX.H264.ParseAvccHeader(Track.SampleDescriptions[0].AvccAtomData);

                //	wrong place to assign this! should be when we assign the track index
                H264TrackHeader = Header;

                var Pps = new List <byte>(new byte[] { 0, 0, 0, 1 });
                Pps.AddRange(Header.PPSs[0]);
                Pps_AnnexB = Pps.ToArray();

                var Sps = new List <byte>(new byte[] { 0, 0, 0, 1 });
                Sps.AddRange(Header.SPSs[0]);
                Sps_AnnexB = Sps.ToArray();

                PushPacket = (Packet, FrameNumber) =>
                {
                    H264.AvccToAnnexb4(Header, Packet, (Bytes) => { PushFrame_AnnexB(Bytes, FrameNumber); });
                };
            }
            else if (Preconfigured_SPS_Bytes != null && Preconfigured_SPS_Bytes.Length > 0)
            {
                throw new System.Exception("Need to refactor to process preconfigured SPS before handling tracks");
                //	split this header
                Sps_AnnexB = Preconfigured_SPS_Bytes;
                Pps_AnnexB = null;

                //	gr: turns out these are AVCC, not annexb
                //	gr: should be able to auto detect without header
                //PushPacket = PushAnnexB;
                H264.AvccHeader Header = new H264.AvccHeader();
                Header.NaluLength = 2;
                PushPacket        = (Packet, FrameNumber) =>
                {
                    H264.AvccToAnnexb4(Header, Packet, (Bytes) => { PushFrame_AnnexB(Bytes, FrameNumber); });
                };
            }
            else
            {
                //	track without header, assume it's already come via moov and this is a moof
                Sps_AnnexB = null;
                Pps_AnnexB = null;
                PushPacket = null;
            }


            //	load h264 header
            if (Sps_AnnexB != null)
            {
                H264.Profile Profile;
                float        Level;
                PopX.H264.GetProfileLevel(Sps_AnnexB, out Profile, out Level);
                if (Profile != H264.Profile.Baseline)
                {
                    Debug.LogWarning("PopH264 currently only supports baseline profile. This is " + Profile + " level=" + Level);
                }

                PushFrame_AnnexB(Sps_AnnexB, 0);
                PushFrame_AnnexB(Pps_AnnexB, 0);
            }

            //	load samples
            if (Track.Samples == null)
            {
                if (VerboseDebug)
                {
                    Debug.Log("Mp4 Track with null samples (next mdat=" + NextMdat + ")");
                }
            }
            else
            {
                //	gr: is there a better mdat ident? don't think so, it's just the upcoming one in mpeg sequence
                //	gr: sometimes, the mdat is before the tracks...
                //	gr: the sample offset also needs correcting
                var MdatIndex = MDatBeforeTrack ? NextMdat - 1 : 0;

                if (VerboseDebug)
                {
                    Debug.Log("Found mp4 track " + Track.Samples.Count + " for next mdat: " + MdatIndex);
                }

                if (Track.Samples.Count > 0)
                {
                    var LastSampleTime = Track.Samples[Track.Samples.Count - 1].PresentationTimeMs;
                    if (!LastFrameTime.HasValue)
                    {
                        LastFrameTime = LastSampleTime;
                    }
                    LastFrameTime = Mathf.Max(LastFrameTime.Value, LastSampleTime);
                }

                foreach (var Sample in Track.Samples)
                {
                    try
                    {
                        var NewSample = new TPendingSample();
                        if (PendingInputSamples == null)
                        {
                            PendingInputSamples = new List <TPendingSample>();
                        }

                        NewSample.Sample    = Sample;
                        NewSample.MdatIndex = MdatIndex;
                        //NewSample.DataPosition = Sample.DataPosition;
                        //NewSample.DataFilePosition = Sample.DataFilePosition;
                        //NewSample.DataSize = Sample.DataSize;
                        var TimeOffsetMs = (int)(TimeOffset / 10000.0f);
                        //NewSample.PresentationTime = Sample.PresentationTimeMs + TimeOffsetMs;
                        NewSample.Format = PacketFormat.Avcc;
                        PendingInputSamples.Add(NewSample);
                    }
                    catch (System.Exception e)
                    {
                        Debug.LogException(e);
                        break;
                    }
                }
            }
        };

        System.Action <List <PopX.Mpeg4.TTrack> > EnumTracks = (Tracks) =>
        {
            //	moof headers don't have track headers, so we should have our track by now
            //	this track may be the original though, so hunt down the h264 one
            if (!H264TrackIndex.HasValue)
            {
                for (int t = 0; t < Tracks.Count; t++)
                {
                    var Track = Tracks[t];
                    if (Track.SampleDescriptions == null)
                    {
                        continue;
                    }

                    if (Track.SampleDescriptions[0].Fourcc != "avc1")
                    {
                        Debug.Log("Skipping track codec: " + Track.SampleDescriptions[0].Fourcc);
                        continue;
                    }

                    H264TrackIndex = t;
                }
            }

            if (!H264TrackIndex.HasValue)
            {
                throw new System.Exception("Couldn't find avc1 track");
            }

            EnumTrack(Tracks[H264TrackIndex.Value]);
        };

        System.Action <PopX.TAtom> EnumMdat = (MdatAtom) =>
        {
            if (VerboseDebug)
            {
                Debug.Log("EnumMdat( NextMdat=" + NextMdat);
            }

            if (!H264TrackIndex.HasValue)
            {
                MDatBeforeTrack = true;
            }

            //	this is the meta for the pending mdat
            var MdatIndex = NextMdat;

            if (Mdats == null)
            {
                Mdats = new Dictionary <uint, MdatBlock>();
            }

            var Mdat = new MdatBlock();
            Mdat.Atom       = MdatAtom;
            Mdat.FileOffset = Mdat.Atom.AtomDataFilePosition;                   //	need a better way to do this

            if (VerboseDebug)
            {
                Debug.Log("Got MDat " + MdatIndex + " x" + Mdat.Bytes.Length + " bytes");
            }
            Mdats.Add(MdatIndex, Mdat);

            //	increment once everything succeeds
            NextMdat++;
        };

        //	ideally only once we've verified we have an mp4, but before moov. Maybe just if an ftyp is found
        if (Decoder == null)
        {
            Decoder = new PopH264.Decoder(DecoderParams, DecodeOnSeperateThread);
        }


        System.Func <long, byte[]> PopData = (long DataSize) =>
        {
            var Data = ReadFileFunction(Mp4BytesRead, DataSize);
            Mp4BytesRead += DataSize;
            return(Data);
        };

        try
        {
            PopX.Mpeg4.ParseNextAtom(PopData, Mp4BytesRead, EnumTracks, EnumMdat);
        }
        catch (System.Exception e)
        {
            Debug.LogException(e);
        }
    }
Пример #12
0
    public void SendRadarData()
    {
        if (Bridge == null || Bridge.Status != Ros.Status.Connected)
        {
            return;
        }

        var apolloHeader = new Ros.ApolloHeader()
        {
            timestamp_sec = (System.DateTime.UtcNow - originTime).TotalSeconds,
            module_name = "conti_radar",
            sequence_num = seqId
        };

        var radarPos = transform.position;
        var radarAim = transform.forward;
        var radarRight = transform.right;

        radarObjList.Clear();

        utilColList.Clear();
        utilColList.AddRange(radarDetectedColliders.Keys);
        utilColList.RemoveAll(c => c == null);

        //Debug.Log("radarDetectedColliders.Count: " + radarDetectedColliders.Count);

        System.Func<Collider, int> GetDynPropInt = ((col) => {
            var trafAiMtr = col.GetComponentInParent<TrafAIMotor>();
            if (trafAiMtr != null)
                return trafAiMtr.currentSpeed > 1.0f ? 0 : 1;
            return 1;
        });

        System.Func<Collider, Vector3> GetLinVel = ((col) => {
            var trafAiMtr = col.GetComponentInParent<TrafAIMotor>();
            if (trafAiMtr != null)
                return trafAiMtr.currentVelocity;
            else            
                return col.attachedRigidbody == null ? Vector3.zero : col.attachedRigidbody.velocity;            
        });

        for (int i = 0; i < utilColList.Count; i++)
        {
            Collider col = utilColList[i];
            Vector3 point = radarDetectedColliders[col].point;
            Vector3 relPos = point - radarPos;
            Vector3 carVel = gameObject.GetComponentInParent<Rigidbody>().velocity;
            Vector3 relVel = carVel - GetLinVel(col);

            //Debug.Log("id to be assigned to obstacle_id is " + radarDetectedColliders[col].id);
            Vector3 size = col.bounds.size;

            // angle is orientation of the obstacle in degrees as seen by radar, counterclockwise is positive
            double angle = -Vector3.SignedAngle(transform.forward, col.transform.forward, transform.up);
            if (angle > 90) {
                angle -= 180;
            } else if (angle < -90) {
                angle += 180;
            }

            radarObjList.Add(new Ros.Apollo.Drivers.ContiRadarObs()
            {
                header = apolloHeader,
                clusterortrack = false,
                obstacle_id = radarDetectedColliders[col].id,
                longitude_dist = Vector3.Project(relPos, radarAim).magnitude,
                lateral_dist = Vector3.Project(relPos, radarRight).magnitude * (Vector3.Dot(relPos, radarRight) > 0 ? -1 : 1),
                longitude_vel = Vector3.Project(relVel, radarAim).magnitude * (Vector3.Dot(relVel, radarAim) > 0 ? -1 : 1),
                lateral_vel = Vector3.Project(relVel, radarRight).magnitude * (Vector3.Dot(relVel, radarRight) > 0 ? -1 : 1),
                rcs = 11.0, //
                dynprop = GetDynPropInt(col), // seem to be constant
                longitude_dist_rms = 0,
                lateral_dist_rms = 0,
                longitude_vel_rms = 0,
                lateral_vel_rms = 0,
                probexist = 1.0, //prob confidence
                meas_state = radarDetectedColliders[col].newDetection ? 1 : 2, //1 new 2 exist
                longitude_accel = 0,
                lateral_accel = 0,
                oritation_angle = angle,
                longitude_accel_rms = 0,
                lateral_accel_rms = 0,
                oritation_angle_rms = 0,
                length = size.z,
                width = size.x,
                obstacle_class = size.z > 5 ? 2 : 1, // 0: point; 1: car; 2: truck; 3: pedestrian; 4: motorcycle; 5: bicycle; 6: wide; 7: unknown
            });

        }

        var msg = new Ros.Apollo.Drivers.ContiRadar
        {
            header = apolloHeader,
            contiobs = radarObjList,
            object_list_status = new Ros.Apollo.Drivers.ObjectListStatus_60A
            {
                nof_objects = utilColList.Count,
                meas_counter = 22800,
                interface_version = 0
            }
        };

        Bridge.Publish(ApolloTopicName, msg);

        ++seqId;
    }
Пример #13
0
    public static List <Node> Provide(Grid grid, Node startNode, System.Func <Node, bool> endNodePredicate)
    {
        if (endNodePredicate(startNode))
        {
            return(new List <Node>()
            {
                startNode
            });
        }

        if (grid.NodesInGrid == null || grid.NodesInGrid.Count == 0)
        {
            return(new List <Node>(0));
        }

        Dictionary <int, NodeData> relevantNodes = new Dictionary <int, NodeData>();
        List <NodeData>            openNodes     = new List <NodeData>();
        List <NodeData>            closedNodes   = new List <NodeData>();

        Node possibleEndNode = grid.NodesInGrid.Values.Where(endNodePredicate).OrderBy(node => Vector3.Distance(node.transform.position, startNode.transform.position)).FirstOrDefault();

        NodeData nodeData = new NodeData(startNode)
        {
            gCost = 0, hCost = Node.OptimisticDistance(startNode, possibleEndNode)
        };

        relevantNodes.Add(startNode.X * 100 + startNode.Z, nodeData);
        openNodes.Add(nodeData);

        while (openNodes.Count > 0)
        {
            NodeData currentNode = openNodes.First();

            IEnumerable <Node> neighbours = currentNode.Node.Neighbours;

            foreach (var neighbour in neighbours)
            {
                if (neighbour.State == NodeState.Unwalkable)
                {
                    continue;
                }

                int newGCost = 0;

                if (neighbour.X != currentNode.X && neighbour.Z != currentNode.Z)
                {
                    newGCost = currentNode.gCost + 14;
                }
                else
                {
                    newGCost = currentNode.gCost + 10;
                }

                if (relevantNodes.TryGetValue((neighbour.X * 100 + neighbour.Z), out NodeData neighbourNodeData))
                {
                    if (neighbourNodeData.gCost > newGCost)
                    {
                        neighbourNodeData.gCost = newGCost;
                    }
                }
                else
                {
                    nodeData = new NodeData(neighbour)
                    {
                        gCost = newGCost, hCost = Node.OptimisticDistance(neighbour, possibleEndNode)
                    };
                    relevantNodes.Add(neighbour.X * 100 + neighbour.Z, nodeData);
                    openNodes.Add(nodeData);

                    if (endNodePredicate(neighbour))
                    {
                        foreach (var relevantNode in relevantNodes)
                        {
                            relevantNode.Value.Node.text.text = "_" + relevantNode.Value.FCost.ToString() + "_";
                        }

                        return(RecreatePath(openNodes, closedNodes, neighbour, startNode));
                    }
                }
            }

            openNodes.RemoveAt(0);
            openNodes = openNodes.OrderBy(node => node.hCost).ToList();
            closedNodes.Add(currentNode);
        }

        return(new List <Node>(0));
    }