public LocationMonitorImpl(Accuracy accuracy)
 {
     DesiredAccuracy = accuracy;
 }
Exemple #2
0
 /// <summary>
 ///   Initialize a new OCR Object.
 /// 
 ///   This object is a wrapper for the Emgu Tesseract Wrapper to give a level of abstraction
 ///   necessary for scanning shreds
 /// </summary>
 /// <param name="accuracy"> Desired Accuracy setting </param>
 /// <param name="language"> Language of text on image used for OCR model </param>
 /// <param name="enableTimer"> Set enable Timer to true to measure scan time for diagnostic purposes </param>
 public OCR(Accuracy accuracy = Accuracy.High, string language = "eng", bool enableTimer = false)
 {
     _timer = new Stopwatch();
     if (enableTimer)
     {
         _timer.Start();
     }
     Tesseract.OcrEngineMode mode = Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED;
     switch (accuracy)
     {
         case Accuracy.Low:
             mode = Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY;
             break;
         case Accuracy.Medium:
             mode = Tesseract.OcrEngineMode.OEM_CUBE_ONLY;
             break;
         case Accuracy.High:
             mode = Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED;
             break;
     }
     _tesseract = new Tesseract("tessdata", language, mode);
     //"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
     _tesseract.SetVariable("tessedit_unrej_any_wd", "T");
     //_tesseract.SetVariable("tessedit_char_whitelist","abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZ0123456789.,");
     _text = null;
     _chars = null;
     _confidence = -1;
 }
Exemple #3
0
        public void TestData()
        {
            var trainingData = ReadTestData("../../../../Data/train_sensor.txt", "../../../../Data/train_category.txt");

            var floatPrecision = 50;

            var cl = Create();

            foreach (var frame in trainingData)
            {
                var bits = AsBitArray(BitMapper.Map(frame.Columns, -0.6f, 2.21f, floatPrecision), frame.Columns.Length * floatPrecision);
                cl.Train(frame.Category.ToString(), bits);
            }

            var testData = ReadTestData("../../../../Data/test_sensor.txt", "../../../../Data/test_category.txt");

            var acurate = 0;
            var total = 0;

            var accuracy = new Dictionary<string, Accuracy>();

            foreach (var frame in testData)
            {
                var bits = AsBitArray(BitMapper.Map(frame.Columns, -0.6f, 2.21f, floatPrecision), frame.Columns.Length * floatPrecision);

                var matches = cl.FindMatches(bits)
                    .OrderByDescending(c => c.Strength)
                    .Take(2)
                    .ToArray();

                var cat = frame.Category.ToString();
                if (matches[0].Identifier == cat) acurate++;
                total++;

                Accuracy v;
                if (!accuracy.TryGetValue(cat, out v))
                    accuracy.Add(cat, v = new Accuracy());

                if (matches[0].Identifier == frame.Category.ToString()) v.acurate++;
                v.total++;

                Console.WriteLine("Expected: {0}  Matched: {1} ({3:p})  Runner Up: {2} ({4:p})", frame.Category, matches[0].Identifier, matches[1].Identifier, matches[0].Strength, matches[1].Strength);
            }
            Console.WriteLine("Accuracy: {0:p}", ((float)acurate) / ((float)total));

            foreach (var pair in accuracy)
                Console.WriteLine("Accuracy {1}: {0:p}", ((float)pair.Value.acurate) / ((float)pair.Value.total), pair.Key);
        }
Exemple #4
0
        public override void WriteTo(ArcXmlWriter writer)
        {
            try
            {
                writer.WriteStartElement(XmlName);

                if (Accuracy > 0)
                {
                    writer.WriteAttributeString("accuracy", Accuracy.ToString());
                }

                if (FeatureLimit > 0)
                {
                    writer.WriteAttributeString("featurelimit", FeatureLimit.ToString());
                }

                if (!String.IsNullOrEmpty(JoinExpression))
                {
                    writer.WriteAttributeString("joinexpression", JoinExpression);
                }

                if (!String.IsNullOrEmpty(JoinTables))
                {
                    writer.WriteAttributeString("jointables", JoinTables);
                }

                if (!String.IsNullOrEmpty(OrderBy))
                {
                    writer.WriteAttributeString("order_by", OrderBy);
                }

                if (!String.IsNullOrEmpty(Subfields))
                {
                    writer.WriteAttributeString("subfields", Subfields);
                }

                if (!String.IsNullOrEmpty(Where))
                {
                    writer.WriteAttributeString("where", Where);
                }

                if (Buffer != null)
                {
                    Buffer.WriteTo(writer);
                }

                if (FeatureCoordSys != null)
                {
                    FeatureCoordSys.WriteTo(writer);
                }

                if (FilterCoordSys != null)
                {
                    FilterCoordSys.WriteTo(writer);
                }

                if (SpatialFilter != null)
                {
                    SpatialFilter.WriteTo(writer);
                }

                writer.WriteEndElement();
            }
            catch (Exception ex)
            {
                if (ex is ArcXmlException)
                {
                    throw ex;
                }
                else
                {
                    throw new ArcXmlException(String.Format("Could not write {0} object.", GetType().Name), ex);
                }
            }
        }
 /// <summary>
 /// Takes the various properties of this instance and adds them to a <see cref="Dictionary{K,V}"/> instanced passed in, ready for sending to Flickr.
 /// </summary>
 /// <param name="parameters">The <see cref="Dictionary{K,V}"/> to add the options to.</param>
 public void AddToDictionary(Dictionary <string, string> parameters)
 {
     if (!string.IsNullOrEmpty(UserId))
     {
         parameters.Add("user_id", UserId);
     }
     if (!string.IsNullOrEmpty(GroupId))
     {
         parameters.Add("group_id", GroupId);
     }
     if (!string.IsNullOrEmpty(Text))
     {
         parameters.Add("text", Text);
     }
     if (!string.IsNullOrEmpty(Tags))
     {
         parameters.Add("tags", Tags);
     }
     if (TagMode != TagMode.None)
     {
         parameters.Add("tag_mode", UtilityMethods.TagModeToString(TagMode));
     }
     if (!string.IsNullOrEmpty(MachineTags))
     {
         parameters.Add("machine_tags", MachineTags);
     }
     if (MachineTagMode != MachineTagMode.None)
     {
         parameters.Add("machine_tag_mode", UtilityMethods.MachineTagModeToString(MachineTagMode));
     }
     if (MinUploadDate != DateTime.MinValue)
     {
         parameters.Add("min_upload_date", UtilityMethods.DateToUnixTimestamp(MinUploadDate).ToString());
     }
     if (MaxUploadDate != DateTime.MinValue)
     {
         parameters.Add("max_upload_date", UtilityMethods.DateToUnixTimestamp(MaxUploadDate).ToString());
     }
     if (MinTakenDate != DateTime.MinValue)
     {
         parameters.Add("min_taken_date", UtilityMethods.DateToMySql(MinTakenDate));
     }
     if (MaxTakenDate != DateTime.MinValue)
     {
         parameters.Add("max_taken_date", UtilityMethods.DateToMySql(MaxTakenDate));
     }
     if (Licenses.Count != 0)
     {
         var licenseArray = new List <string>();
         foreach (var license in Licenses)
         {
             licenseArray.Add(license.ToString("d"));
         }
         parameters.Add("license", string.Join(",", licenseArray.ToArray()));
     }
     if (PerPage != 0)
     {
         parameters.Add("per_page", PerPage.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (Page != 0)
     {
         parameters.Add("page", Page.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (Extras != PhotoSearchExtras.None)
     {
         parameters.Add("extras", ExtrasString);
     }
     if (SortOrder != PhotoSearchSortOrder.None)
     {
         parameters.Add("sort", SortOrderString);
     }
     if (PrivacyFilter != PrivacyFilter.None)
     {
         parameters.Add("privacy_filter", PrivacyFilter.ToString("d"));
     }
     if (BoundaryBox != null && BoundaryBox.IsSet)
     {
         parameters.Add("bbox", BoundaryBox.ToString());
     }
     if (Accuracy != GeoAccuracy.None)
     {
         parameters.Add("accuracy", Accuracy.ToString("d"));
     }
     if (SafeSearch != SafetyLevel.None)
     {
         parameters.Add("safe_search", SafeSearch.ToString("d"));
     }
     if (ContentType != ContentTypeSearch.None)
     {
         parameters.Add("content_type", ContentType.ToString("d"));
     }
     if (HasGeo != null)
     {
         parameters.Add("has_geo", HasGeo.Value ? "1" : "0");
     }
     if (Latitude != null)
     {
         parameters.Add("lat", Latitude.Value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (Longitude != null)
     {
         parameters.Add("lon", Longitude.Value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (Radius != null)
     {
         parameters.Add("radius", Radius.Value.ToString("0.00000", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (RadiusUnits != RadiusUnit.None)
     {
         parameters.Add("radius_units", (RadiusUnits == RadiusUnit.Miles ? "mi" : "km"));
     }
     if (Contacts != ContactSearch.None)
     {
         parameters.Add("contacts", (Contacts == ContactSearch.AllContacts ? "all" : "ff"));
     }
     if (WoeId != null)
     {
         parameters.Add("woe_id", WoeId);
     }
     if (PlaceId != null)
     {
         parameters.Add("place_id", PlaceId);
     }
     if (IsCommons)
     {
         parameters.Add("is_commons", "1");
     }
     if (InGallery)
     {
         parameters.Add("in_gallery", "1");
     }
     if (IsGetty)
     {
         parameters.Add("is_getty", "1");
     }
     if (MediaType != MediaType.None)
     {
         parameters.Add("media", UtilityMethods.MediaTypeToString(MediaType));
     }
     if (GeoContext != GeoContext.NotDefined)
     {
         parameters.Add("geo_context", GeoContext.ToString("d"));
     }
     if (Faves)
     {
         parameters.Add("faves", "1");
     }
     if (PersonId != null)
     {
         parameters.Add("person_id", PersonId);
     }
     if (Camera != null)
     {
         parameters.Add("camera", Camera);
     }
     if (JumpTo != null)
     {
         parameters.Add("jump_to", JumpTo);
     }
     if (!string.IsNullOrEmpty(Username))
     {
         parameters.Add("username", Username);
     }
     if (ExifMinExposure != null)
     {
         parameters.Add("exif_min_exposure", ExifMinExposure.Value.ToString("0.00000", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExifMaxExposure != null)
     {
         parameters.Add("exif_max_exposure", ExifMaxExposure.Value.ToString("0.00000", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExifMinAperture != null)
     {
         parameters.Add("exif_min_aperture", ExifMinAperture.Value.ToString("0.00000", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExifMaxAperture != null)
     {
         parameters.Add("exif_max_aperture", ExifMaxAperture.Value.ToString("0.00000", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExifMinFocalLength != null)
     {
         parameters.Add("exif_min_focallen", ExifMinFocalLength.Value.ToString("0", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExifMaxFocalLength != null)
     {
         parameters.Add("exif_max_focallen", ExifMaxFocalLength.Value.ToString("0", System.Globalization.NumberFormatInfo.InvariantInfo));
     }
     if (ExcludeUserID != null)
     {
         parameters.Add("exclude_user_id", ExcludeUserID);
     }
     if (FoursquareVenueID != null)
     {
         parameters.Add("foursquare_venueid", FoursquareVenueID);
     }
     if (FoursquareWoeID != null)
     {
         parameters.Add("foursquare_woeid", FoursquareWoeID);
     }
     if (GroupPathAlias != null)
     {
         parameters.Add("group_path_alias", GroupPathAlias);
     }
     if (ColorCodes != null && ColorCodes.Count != 0)
     {
         parameters.Add("color_codes", ColorCodeString);
     }
 }
Exemple #6
0
        public async Task <IActionResult> PostSubmitModular()
        {
            string score  = Request.Form["score"];
            string iv     = Request.Form["iv"];
            string osuver = Request.Form["osuver"];
            string pass   = Request.Form["pass"];

            var(b, scores) = ScoreSubmissionParser.ParseScore(_factory, score, iv, osuver);

            if (scores.UserId == -1)
            {
                return(Ok("error: pass"));
            }

            if (scores.ScoreOwner == null)
            {
                scores.ScoreOwner = Users.GetUser(_factory, scores.UserId);
            }

            if (scores.ScoreOwner == null)
            {
                return(Ok("error: pass"));
            }

            if (!scores.ScoreOwner.IsPassword(pass))
            {
                return(Ok("error: pass"));
            }

            var isRelaxing = (scores.Mods & Mod.Relax) != 0;
            var pr         = _ps.GetPresence(scores.ScoreOwner.Id);

            if (!b || !RankedMods.IsRanked(scores.Mods))
            {
                if (isRelaxing)
                {
                    var rx = LeaderboardRx.GetLeaderboard(_factory, scores.ScoreOwner);
                    rx.IncreasePlaycount(_factory, scores.PlayMode);
                    rx.IncreaseScore(_factory, (ulong)scores.TotalScore, false, scores.PlayMode);
                }
                else
                {
                    var std = LeaderboardStd.GetLeaderboard(_factory, scores.ScoreOwner);
                    std.IncreasePlaycount(_factory, scores.PlayMode);
                    std.IncreaseScore(_factory, (ulong)scores.TotalScore, false, scores.PlayMode);
                }

                await _ev.RunEvent(
                    EventType.BanchoUserStatsRequest,
                    new BanchoUserStatsRequestArgs { userIds = new List <int> {
                                                         scores.ScoreOwner.Id
                                                     }, pr = pr }
                    );

                return(Ok("Thanks for your hard work!"));
            }

            /*
             * switch (scores.PlayMode)
             * {
             *  case PlayMode.Osu:
             *      oppai op = new oppai(BeatmapDownloader.GetBeatmap(scores.FileMd5, _config));
             *      op.SetAcc((int) scores.Count300, (int) scores.Count50, (int) scores.CountMiss);
             *      op.SetCombo(scores.MaxCombo);
             *      op.SetMods(scores.Mods);
             *      op.Calculate();
             *
             *      scores.PeppyPoints = op.GetPP();
             *      Logger.Info("Peppy Points:", scores.PeppyPoints);
             *      break;
             * }
             */

            var ReplayFile = Request.Form.Files.GetFile("score");

            if (!Directory.Exists("data/replays"))
            {
                Directory.CreateDirectory("data/replays");
            }

            await using (var m = new MemoryStream())
            {
                ReplayFile.CopyTo(m);
                m.Position       = 0;
                scores.ReplayMd5 = Hex.ToHex(Crypto.GetMd5(m)) ?? string.Empty;
                if (!string.IsNullOrEmpty(scores.ReplayMd5))
                {
                    await using (var replayFile = System.IO.File.Create($"data/replays/{scores.ReplayMd5}"))
                    {
                        m.Position = 0;
                        m.WriteTo(replayFile);
                        m.Close();
                        replayFile.Close();
                    }
                }
            }

            BeatmapDownloader.GetBeatmap(scores.FileMd5, _config);

            if (isRelaxing)
            {
                scores.Mods -= Mod.Relax;
            }
            scores.PeppyPoints = PerformancePointsProcessor.Compute(scores);
            if (isRelaxing)
            {
                scores.Mods |= Mod.Relax;
            }

            var oldScore = Scores.GetScores(
                _factory,
                scores.FileMd5,
                scores.ScoreOwner,
                scores.PlayMode,
                isRelaxing,
                false,
                false,
                false,
                scores.Mods,
                true
                ).FirstOrDefault();

            var oldStd    = LeaderboardStd.GetLeaderboard(_factory, scores.ScoreOwner);
            var oldStdPos = oldStd.GetPosition(_factory, scores.PlayMode);

            if (oldScore != null && oldScore.TotalScore <= scores.TotalScore)
            {
                using var db = _factory.GetForWrite();
                db.Context.Scores.Remove(oldScore);
                System.IO.File.Delete($"data/replays/{oldScore.ReplayMd5}");

                Scores.InsertScore(_factory, scores);
            }
            else if (oldScore == null)
            {
                Scores.InsertScore(_factory, scores);
            }
            else
            {
                System.IO.File.Delete($"data/replays/{scores.ReplayMd5}");
            }

            if (isRelaxing)
            {
                var rx = LeaderboardRx.GetLeaderboard(_factory, scores.ScoreOwner);
                rx.IncreasePlaycount(_factory, scores.PlayMode);
                rx.IncreaseCount300(_factory, scores.Count300, scores.PlayMode);
                rx.IncreaseCount100(_factory, scores.Count100, scores.PlayMode);
                rx.IncreaseCount50(_factory, scores.Count50, scores.PlayMode);
                rx.IncreaseCountMiss(_factory, scores.CountMiss, scores.PlayMode);
                rx.IncreaseScore(_factory, (ulong)scores.TotalScore, true, scores.PlayMode);
                rx.IncreaseScore(_factory, (ulong)scores.TotalScore, false, scores.PlayMode);

                rx.UpdatePP(_factory, scores.PlayMode);

                pr.LeaderboardRx = rx;
                await _ev.RunEvent(
                    EventType.BanchoUserStatsRequest,
                    new BanchoUserStatsRequestArgs { userIds = new List <int> {
                                                         scores.ScoreOwner.Id
                                                     }, pr = pr }
                    );
            }
            else
            {
                var std = LeaderboardStd.GetLeaderboard(_factory, scores.ScoreOwner);
                std.IncreasePlaycount(_factory, scores.PlayMode);
                std.IncreaseCount300(_factory, scores.Count300, scores.PlayMode);
                std.IncreaseCount100(_factory, scores.Count100, scores.PlayMode);
                std.IncreaseCount50(_factory, scores.Count50, scores.PlayMode);
                std.IncreaseCountMiss(_factory, scores.CountMiss, scores.PlayMode);
                std.IncreaseScore(_factory, (ulong)scores.TotalScore, true, scores.PlayMode);
                std.IncreaseScore(_factory, (ulong)scores.TotalScore, false, scores.PlayMode);

                std.UpdatePP(_factory, scores.PlayMode);
            }

            var newStd    = LeaderboardStd.GetLeaderboard(_factory, scores.ScoreOwner);
            var newStdPos = newStd.GetPosition(_factory, scores.PlayMode);


            var NewScore = Scores.GetScores(
                _factory,
                scores.FileMd5,
                scores.ScoreOwner,
                scores.PlayMode,
                isRelaxing,
                false,
                false,
                false,
                scores.Mods,
                true
                ).FirstOrDefault();

            var cg = new Cheesegull(_config);

            cg.SetBM(scores.FileMd5);

            var sets = cg.GetSets();
            var bm   = sets?[0].ChildrenBeatmaps.First(x => x.FileMD5 == scores.FileMd5) ?? new CheesegullBeatmap();

            double oldAcc;
            double newAcc;

            ulong oldRankedScore;
            ulong newRankedScore;

            double oldPP;
            double newPP;

            switch (scores.PlayMode)
            {
            case PlayMode.Osu:
                oldAcc = Accuracy.GetAccuracy(
                    oldStd.Count300Osu,
                    oldStd.Count100Osu,
                    oldStd.Count50Osu,
                    oldStd.Count300Osu, 0, 0,
                    PlayMode.Osu
                    );

                newAcc = Accuracy.GetAccuracy(
                    newStd.Count300Osu,
                    newStd.Count100Osu,
                    newStd.Count50Osu,
                    newStd.Count300Osu, 0, 0,
                    PlayMode.Osu
                    );

                oldRankedScore = oldStd.RankedScoreOsu;
                newRankedScore = newStd.RankedScoreOsu;

                oldPP = oldStd.PerformancePointsOsu;
                newPP = newStd.PerformancePointsOsu;
                break;

            case PlayMode.Taiko:
                oldAcc = Accuracy.GetAccuracy(
                    oldStd.Count300Taiko,
                    oldStd.Count100Taiko,
                    oldStd.Count50Taiko,
                    oldStd.Count300Taiko, 0, 0,
                    PlayMode.Taiko
                    );

                newAcc = Accuracy.GetAccuracy(
                    newStd.Count300Taiko,
                    newStd.Count100Taiko,
                    newStd.Count50Taiko,
                    newStd.Count300Taiko, 0, 0,
                    PlayMode.Taiko
                    );

                oldRankedScore = oldStd.RankedScoreTaiko;
                newRankedScore = newStd.RankedScoreTaiko;

                oldPP = oldStd.PerformancePointsTaiko;
                newPP = newStd.PerformancePointsTaiko;
                break;

            case PlayMode.Ctb:
                oldAcc = Accuracy.GetAccuracy(
                    oldStd.Count300Ctb,
                    oldStd.Count100Ctb,
                    oldStd.Count50Ctb,
                    oldStd.Count300Ctb, 0, 0,
                    PlayMode.Ctb
                    );

                newAcc = Accuracy.GetAccuracy(
                    newStd.Count300Ctb,
                    newStd.Count100Ctb,
                    newStd.Count50Ctb,
                    newStd.Count300Ctb, 0, 0,
                    PlayMode.Ctb
                    );

                oldRankedScore = oldStd.RankedScoreCtb;
                newRankedScore = newStd.RankedScoreCtb;

                oldPP = oldStd.PerformancePointsCtb;
                newPP = newStd.PerformancePointsCtb;
                break;

            case PlayMode.Mania:
                oldAcc = Accuracy.GetAccuracy(
                    oldStd.Count300Mania,
                    oldStd.Count100Mania,
                    oldStd.Count50Mania,
                    oldStd.Count300Mania, 0, 0,
                    PlayMode.Mania
                    );

                newAcc = Accuracy.GetAccuracy(
                    newStd.Count300Mania,
                    newStd.Count100Mania,
                    newStd.Count50Mania,
                    newStd.Count300Mania, 0, 0,
                    PlayMode.Mania
                    );

                oldRankedScore = oldStd.RankedScoreMania;
                newRankedScore = newStd.RankedScoreMania;

                oldPP = oldStd.PerformancePointsMania;
                newPP = newStd.PerformancePointsMania;
                break;

            default:
                return(Ok(""));
            }

            if (NewScore?.Position == 1 && (oldScore == null || oldScore.TotalScore < NewScore.TotalScore))
            {
                _sora.SendMessage(
                    $"[http://{_config.Server.Hostname}/{scores.ScoreOwner.Id} {scores.ScoreOwner.Username}] " +
                    $"has reached #1 on [https://osu.ppy.sh/b/{bm.BeatmapID} {sets?[0].Title} [{bm.DiffName}]] " +
                    $"using {ModUtil.ToString(NewScore.Mods)} " +
                    $"Good job! +{NewScore.PeppyPoints:F}PP",
                    "#announce",
                    false
                    );
            }

            Logger.Info(
                $"{L_COL.RED}{scores.ScoreOwner.Username}",
                $"{L_COL.PURPLE}( {scores.ScoreOwner.Id} ){L_COL.WHITE}",
                $"has just submitted a Score! he earned {L_COL.BLUE}{NewScore?.PeppyPoints:F}PP",
                $"{L_COL.WHITE}with an Accuracy of {L_COL.RED}{NewScore?.Accuracy * 100:F}",
                $"{L_COL.WHITE}on {L_COL.YELLOW}{sets?[0].Title} [{bm.DiffName}]",
                $"{L_COL.WHITE}using {L_COL.BLUE}{ModUtil.ToString(NewScore?.Mods ?? Mod.None)}"
                );

            var bmChart = new Chart(
                "beatmap",
                "Beatmap Ranking",
                $"https://osu.ppy.sh/b/{bm.BeatmapID}",
                oldScore?.Position ?? 0,
                NewScore?.Position ?? 0,
                oldScore?.MaxCombo ?? 0,
                NewScore?.MaxCombo ?? 0,
                oldScore?.Accuracy * 100 ?? 0,
                NewScore?.Accuracy * 100 ?? 0,
                (ulong)(oldScore?.TotalScore ?? 0),
                (ulong)(NewScore?.TotalScore ?? 0),
                oldScore?.PeppyPoints ?? 0,
                NewScore?.PeppyPoints ?? 0,
                NewScore?.Id ?? 0
                );

            cg.SetBMSet(bm.ParentSetID);

            var overallChart = new Chart(
                "overall",
                "Global Ranking",
                $"https://osu.ppy.sh/u/{scores.ScoreOwner.Id}",
                (int)oldStdPos,
                (int)newStdPos,
                0,
                0,
                oldAcc * 100,
                newAcc * 100,
                oldRankedScore,
                newRankedScore,
                oldPP,
                newPP,
                NewScore?.Id ?? 0,
                AchievementProcessor.ProcessAchievements(
                    _factory, scores.ScoreOwner, scores, bm, cg.GetSets()[0], oldStd, newStd
                    )
                );

            pr.LeaderboardStd = newStd;
            await _ev.RunEvent(
                EventType.BanchoUserStatsRequest,
                new BanchoUserStatsRequestArgs { userIds = new List <int> {
                                                     scores.ScoreOwner.Id
                                                 }, pr = pr }
                );

            return(Ok(
                       $"beatmapId:{bm.BeatmapID}|beatmapSetId:{bm.ParentSetID}|beatmapPlaycount:0|beatmapPasscount:0|approvedDate:\n\n" +
                       bmChart.ToOsuString() + "\n" + overallChart.ToOsuString()
                       ));
        }
Exemple #7
0
        public override int GetHashCode()
        {
            var hashCode = -1002157333;

            hashCode = hashCode * -1521134295 + Index.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(FullName);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(GroupName);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(SetName);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Name);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Display);

            hashCode = hashCode * -1521134295 + Available.GetHashCode();
            hashCode = hashCode * -1521134295 + ModesRequired.GetHashCode();
            hashCode = hashCode * -1521134295 + ModesDisallowed.GetHashCode();
            hashCode = hashCode * -1521134295 + PowerType.GetHashCode();
            hashCode = hashCode * -1521134295 + Accuracy.GetHashCode();
            hashCode = hashCode * -1521134295 + AttackTypes.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string[]> .Default.GetHashCode(GroupMemberships);

            hashCode = hashCode * -1521134295 + EntitiesAffected.GetHashCode();
            hashCode = hashCode * -1521134295 + EntitiesAutoHit.GetHashCode();
            hashCode = hashCode * -1521134295 + Target.GetHashCode();
            hashCode = hashCode * -1521134295 + TargetLineOfSight.GetHashCode();
            hashCode = hashCode * -1521134295 + Range.GetHashCode();
            hashCode = hashCode * -1521134295 + TargetSecondary.GetHashCode();
            hashCode = hashCode * -1521134295 + RangeSecondary.GetHashCode();
            hashCode = hashCode * -1521134295 + EnduranceCost.GetHashCode();
            hashCode = hashCode * -1521134295 + InterruptTime.GetHashCode();
            hashCode = hashCode * -1521134295 + CastTime.GetHashCode();
            hashCode = hashCode * -1521134295 + RechargeTime.GetHashCode();
            hashCode = hashCode * -1521134295 + BaseRechargeTime.GetHashCode();
            hashCode = hashCode * -1521134295 + ActivatePeriod.GetHashCode();
            hashCode = hashCode * -1521134295 + EffectArea.GetHashCode();
            hashCode = hashCode * -1521134295 + Radius.GetHashCode();
            hashCode = hashCode * -1521134295 + Arc.GetHashCode();
            hashCode = hashCode * -1521134295 + MaxTargets.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(MaxBoosts);

            hashCode = hashCode * -1521134295 + CastFlags.GetHashCode();
            hashCode = hashCode * -1521134295 + ArtificalIntelligenceReport.GetHashCode();
            hashCode = hashCode * -1521134295 + NumberOfCharges.GetHashCode();
            hashCode = hashCode * -1521134295 + UsageTime.GetHashCode();
            hashCode = hashCode * -1521134295 + LifeTime.GetHashCode();
            hashCode = hashCode * -1521134295 + LifeTimeInGame.GetHashCode();
            hashCode = hashCode * -1521134295 + NumberAllowed.GetHashCode();
            hashCode = hashCode * -1521134295 + DoNotSave.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string[]> .Default.GetHashCode(BoostsAllowed);

            hashCode = hashCode * -1521134295 + CastThroughHold.GetHashCode();
            hashCode = hashCode * -1521134295 + IgnoreStrength.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(DescriptionShort);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(DescriptionLong);

            hashCode = hashCode * -1521134295 + EqualityComparer <int[]> .Default.GetHashCode(SetTypes);

            hashCode = hashCode * -1521134295 + ClickBuff.GetHashCode();
            hashCode = hashCode * -1521134295 + AlwaysToggle.GetHashCode();
            hashCode = hashCode * -1521134295 + Level.GetHashCode();
            hashCode = hashCode * -1521134295 + AllowFrontLoading.GetHashCode();
            hashCode = hashCode * -1521134295 + VariableEnabled.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(VariableName);

            hashCode = hashCode * -1521134295 + VariableMin.GetHashCode();
            hashCode = hashCode * -1521134295 + VariableMax.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string[]> .Default.GetHashCode(SubPowers);

            hashCode = hashCode * -1521134295 + EqualityComparer <int[]> .Default.GetHashCode(IgnoreEnhancements);

            hashCode = hashCode * -1521134295 + EqualityComparer <int[]> .Default.GetHashCode(IgnoreBuffs);

            hashCode = hashCode * -1521134295 + SkipMax.GetHashCode();
            hashCode = hashCode * -1521134295 + DisplayLocation.GetHashCode();
            hashCode = hashCode * -1521134295 + MutuallyExclusiveAuto.GetHashCode();
            hashCode = hashCode * -1521134295 + MutuallyExclusiveIgnore.GetHashCode();
            hashCode = hashCode * -1521134295 + AbsorbSummonEffects.GetHashCode();
            hashCode = hashCode * -1521134295 + AbsorbSummonAttributes.GetHashCode();
            hashCode = hashCode * -1521134295 + ShowSummonAnyway.GetHashCode();
            hashCode = hashCode * -1521134295 + NeverAutoUpdate.GetHashCode();
            hashCode = hashCode * -1521134295 + NeverAutoUpdateRequirements.GetHashCode();
            hashCode = hashCode * -1521134295 + IncludeFlag.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(ForcedClass);

            hashCode = hashCode * -1521134295 + SortOverride.GetHashCode();
            hashCode = hashCode * -1521134295 + BoostBoostable.GetHashCode();
            hashCode = hashCode * -1521134295 + BoostUsePlayerLevel.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <Effect[]> .Default.GetHashCode(Effects);

            hashCode = hashCode * -1521134295 + HiddenPower.GetHashCode();
            return(hashCode);
        }
Exemple #8
0
 public void Read_WithInvalidAsn1_Throws()
 {
     Assert.Throws <CryptographicException>(
         () => Accuracy.Read(new byte[] { 0x30, 0x0b }));
 }
 public RegularTimeFormatter(Accuracy accuracy = Accuracy.Seconds)
 {
     this.Accuracy = accuracy;
 }
Exemple #10
0
        public static void RunSimple()
        {
            var mnist      = TestUtils.GetMNIST(); //Get the MNIST dataset, it will download if not found
            var batch_size = 100;                  //Set training batch size
            var train_data = new NDArrayIter(mnist["train_data"], mnist["train_label"], batch_size, true);
            var val_data   = new NDArrayIter(mnist["test_data"], mnist["test_label"], batch_size);

            // Define simple network with dense layers
            var net = new Sequential();

            net.Add(new Dense(128, ActivationType.Relu, in_units: 784));
            net.Add(new Dense(64, ActivationType.Relu, in_units: 128));
            net.Add(new Dense(10, in_units: 64));

            //Set context, multi-gpu supported
            var gpus = TestUtils.ListGpus();
            var ctx  = gpus.Count > 0 ? gpus.Select(x => Context.Gpu(x)).ToArray() : new[] { Context.Cpu(0) };

            //Initialize the weights
            net.Initialize(new Xavier(magnitude: 2.24f), ctx);

            //Create the trainer with all the network parameters and set the optimizer
            var trainer = new Trainer(net.CollectParams(), new SGD(learning_rate: 0.1f));

            var   epoch  = 100;
            var   metric = new Accuracy(); //Use Accuracy as the evaluation metric.
            var   softmax_cross_entropy_loss = new SoftmaxCrossEntropyLoss();
            float lossVal = 0;             //For loss calculation

            for (var iter = 0; iter < epoch; iter++)
            {
                var tic = DateTime.Now;
                // Reset the train data iterator.
                train_data.Reset();
                lossVal = 0;

                // Loop over the train data iterator.
                while (!train_data.End())
                {
                    var batch = train_data.Next();

                    // Splits train data into multiple slices along batch_axis
                    // and copy each slice into a context.
                    var data = Utils.SplitAndLoad(batch.Data[0], ctx, batch_axis: 0);

                    // Splits train labels into multiple slices along batch_axis
                    // and copy each slice into a context.
                    var label = Utils.SplitAndLoad(batch.Label[0], ctx, batch_axis: 0);

                    var outputs = new NDArrayList();

                    // Inside training scope
                    NDArray loss = null;
                    for (int i = 0; i < data.Length; i++)
                    {
                        using (var ag = Autograd.Record())
                        {
                            var x = data[i];
                            var y = label[i];
                            var z = net.Call(x);
                            loss = softmax_cross_entropy_loss.Call(z, y);
                            outputs.Add(z);
                        }

                        // Computes softmax cross entropy loss.


                        // Backpropagate the error for one iteration.
                        loss.Backward();
                        lossVal += loss.Mean();
                    }
                    //outputs = Enumerable.Zip(data, label, (x, y) =>
                    //{
                    //    var z = net.Call(x);

                    //    // Computes softmax cross entropy loss.
                    //    NDArray loss = softmax_cross_entropy_loss.Call(z, y);

                    //    // Backpropagate the error for one iteration.
                    //    loss.Backward();
                    //    lossVal += loss.Mean();
                    //    return z;
                    //}).ToList();

                    // Updates internal evaluation
                    metric.Update(label, outputs.ToArray());

                    // Make one step of parameter update. Trainer needs to know the
                    // batch size of data to normalize the gradient by 1/batch_size.
                    trainer.Step(batch.Data[0].Shape[0]);
                }

                var toc = DateTime.Now;

                // Gets the evaluation result.
                var(name, acc) = metric.Get();

                // Reset evaluation result to initial state.
                metric.Reset();
                Console.Write($"Loss: {lossVal} ");
                Console.WriteLine($"Training acc at epoch {iter}: {name}={(acc * 100).ToString("0.##")}%, Duration: {(toc - tic).TotalSeconds.ToString("0.#")}s");
            }
        }
Exemple #11
0
        protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect)
        {
            double lengthConversion = ActiveWindow.Units.Length.ConversionFactor;

            int  numberOfTeethL = (int)Values[Resources.NumberOfTeethLText].Value;
            int  numberOfTeethR = (int)Values[Resources.NumberOfTeethRText].Value;
            bool isInternalL    = numberOfTeethL < 0;
            bool isInternalR    = numberOfTeethR < 0;

            numberOfTeethL = Math.Abs(numberOfTeethL);
            numberOfTeethR = Math.Abs(numberOfTeethR);

            double pressureAngle     = Values[Resources.PressureAngleText].Value * Math.PI / 180;
            double module            = Values[Resources.ModuleText].Value / lengthConversion;
            double dedendumClearance = Values[Resources.DedendumClearanceText].Value;
            double depth             = Values[Resources.DepthText].Value / lengthConversion;

            bool useTrochoidalInterferenceRemoval = Booleans[Resources.UseTrochoidalText].Value;
            bool addDedendumClearance             = Booleans[Resources.AddDedendumClearance].Value;

            if (!addDedendumClearance)
            {
                dedendumClearance = 0;
            }

            bool   isBevel        = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].IsEnabledCommandBoolean.Value;
            double bevelAngle     = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].Values[Resources.BevelAngleText].Value * Math.PI / 180;
            double bevelKneeRatio = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].Values[Resources.BevelKneeRatioText].Value;

            bool   isHelical    = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHelicalText].IsEnabledCommandBoolean.Value;
            double helicalAngle = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHelicalText].Values[Resources.HelicalAngleText].Value * Math.PI / 180;

            if (!isHelical)
            {
                helicalAngle = 0;
            }

            bool   isScrew          = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].IsEnabledCommandBoolean.Value;
            double screwAngle       = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].Values[Resources.ScrewAngleText].Value * Math.PI / 180;
            double screwAngleOffset = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].Values[Resources.ScrewAngleBiasText].Value * Math.PI / 180;

            if (!isScrew)
            {
                screwAngle       = 0;
                screwAngleOffset = 0;
            }

            double screwAngleAverage = screwAngle / 2;
            double screwAngleL       = screwAngleAverage + screwAngleOffset;
            double screwAngleR       = screwAngleAverage - screwAngleOffset;

            bool   isHypoid     = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].IsEnabledCommandBoolean.Value;
            double hypoidAngle  = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].Values[Resources.HypoidAngleText].Value * Math.PI / 180;
            double hypoidOffset = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].Values[Resources.HypoidOffsetText].Value / lengthConversion;

            if (!isHypoid)
            {
                hypoidAngle  = 0;
                hypoidOffset = 0;
            }

            Frame frame = Frame.World;
            //Circle circle = SelectedCircle(ActiveWindow);
            //if (circle != null)
            //    frame = circle.Frame;

            List <ITrimmedCurve> selectedCurves = ActiveWindow.GetAllSelectedITrimmedCurves().ToList();

            if (selectedCurves.Count == 2 && selectedCurves[0].Geometry is Circle && selectedCurves[0].Geometry is Circle)
            {
                Circle     circle0    = (Circle)selectedCurves[0].Geometry;
                Circle     circle1    = (Circle)selectedCurves[1].Geometry;
                Separation separation = circle0.Axis.GetClosestSeparation(circle1.Axis);

                if (Accuracy.LengthIsZero(separation.Distance))
                {
                    throw new NotImplementedException("Distance between axes is zero; only hypoid implemented.");
                }

                isHypoid     = true;
                hypoidAngle  = AddInHelper.AngleBetween(circle0.Axis.Direction, circle1.Axis.Direction);
                hypoidOffset = ((circle0.Frame.Origin - separation.PointA).Magnitude - depth / 2) / Math.Cos(hypoidAngle / 2);

                double radiusAApprox = separation.Distance * circle0.Radius / (circle0.Radius + circle1.Radius);
                double radiusBApprox = separation.Distance - radiusAApprox;
                numberOfTeethR = (int)Math.Round((double)numberOfTeethL / radiusAApprox * radiusBApprox);
                module         = radiusAApprox * 2 / numberOfTeethL;

                Point     midpoint = separation.PointA + (separation.PointA - separation.PointB) * numberOfTeethL / numberOfTeethR;
                Direction sideSide = (circle0.Frame.Origin - circle1.Frame.Origin).Direction;
                frame = Frame.Create(midpoint, Direction.Cross(sideSide, -(midpoint - circle0.GetClosestSeparation(circle1).PointA).Direction), sideSide);
            }

            double hypoidAngleL = Math.Atan(Math.Sin(hypoidAngle) / (Math.Cos(hypoidAngle) + (double)numberOfTeethR / numberOfTeethL));
            double hypoidAngleR = Math.Atan(Math.Sin(hypoidAngle) / (Math.Cos(hypoidAngle) + (double)numberOfTeethL / numberOfTeethR));

            Gear gearL = null;
            Gear gearR = null;

            var          gearDataL     = new GearData(numberOfTeethL, pressureAngle, module, dedendumClearance, isInternalL, screwAngleL);
            var          gearDataR     = new GearData(numberOfTeethR, pressureAngle, module, dedendumClearance, isInternalR, screwAngleR);
            ToothProfile toothProfileL = GetGearProfileFromOptions(gearDataL, gearDataR, useTrochoidalInterferenceRemoval, addDedendumClearance);
            ToothProfile toothProfileR = GetGearProfileFromOptions(gearDataR, gearDataL, useTrochoidalInterferenceRemoval, addDedendumClearance);

            if (isBevel)
            {
                gearL = BevelGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, bevelAngle, bevelKneeRatio, depth);
                gearR = BevelGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, bevelAngle, bevelKneeRatio, depth);
            }
            else if (isHypoid)
            {
                gearL = HypoidGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, hypoidAngleL, hypoidOffset, bevelKneeRatio, depth);
                gearR = HypoidGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, hypoidAngleR, hypoidOffset, bevelKneeRatio, depth);
            }
            else
            {
                gearL = StraightGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, screwAngleL, depth);
                gearR = StraightGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, screwAngleR, depth);
            }

            Line zAxis = Line.Create(Point.Origin, Direction.DirZ);

            gearL.Component.Transform(
                Matrix.CreateMapping(frame) *
                Matrix.CreateRotation(zAxis, Math.PI) *
                gearL.TransformToTangent *
                Matrix.CreateRotation(zAxis, gearDataL.PitchAngle * ((double)1 / 2 + (gearDataL.NumberOfTeeth % 2 == 0 && !isHypoid ? -1 : 0)))
                );

            gearR.Component.Transform(
                Matrix.CreateMapping(frame) *
                gearR.TransformToTangent *
                Matrix.CreateRotation(zAxis, gearDataR.PitchAngle * ((double)1 / 2 + (gearDataR.NumberOfTeeth % 2 == 0 && !isHypoid ? -1 : 0)))
                );


            //		if (gearDataR.NumberOfTeeth % 2 == 0)
            //			gearR.Component.Transform(Matrix.CreateRotation(Line.Create(Point.Origin, Direction.DirZ), gearDataR.PitchAngle));

            //gearR.Component.Transform(gearR.TransformToTangent);

            Part        parent       = ActiveIPart.Master;
            IDesignFace pitchCircleL = gearL.Component.Content.Bodies.Where(b => b.Master == gearL.PitchCircleDesBody).First().Faces.First();
            IDesignFace pitchCircleR = gearR.Component.Content.Bodies.Where(b => b.Master == gearR.PitchCircleDesBody).First().Faces.First();

            Part        gearMountPart      = Part.Create(parent.Document, String.Format(Resources.GearMountPartName, gearDataL.NumberOfTeeth, gearDataR.NumberOfTeeth));
            Component   gearMountComponent = Component.Create(parent, gearMountPart);
            DesignBody  mountBodyL         = DesignBody.Create(gearMountPart, string.Format(Resources.MountBodyName, gearDataL.NumberOfTeeth), pitchCircleL.Master.Shape.Body.CreateTransformedCopy(pitchCircleL.TransformToMaster.Inverse));
            DesignBody  mountBodyR         = DesignBody.Create(gearMountPart, string.Format(Resources.MountBodyName, gearDataR.NumberOfTeeth), pitchCircleR.Master.Shape.Body.CreateTransformedCopy(pitchCircleR.TransformToMaster.Inverse));
            IDesignFace mountCircleL       = gearMountComponent.Content.Bodies.Where(b => b.Master == mountBodyL).First().Faces.First();
            IDesignFace mountCircleR       = gearMountComponent.Content.Bodies.Where(b => b.Master == mountBodyR).First().Faces.First();

            Layer mountLayer = NoteHelper.CreateOrGetLayer(ActiveDocument, Resources.GearMountAlignmentCircleLayer, System.Drawing.Color.LightGray);

            mountLayer.SetVisible(null, false);
            mountBodyL.Layer = mountLayer;
            mountBodyR.Layer = mountLayer;

            MatingCondition matingCondition;

            matingCondition = AnchorCondition.Create(parent, gearMountComponent);
            matingCondition = AlignCondition.Create(parent, mountCircleL, pitchCircleL);
            matingCondition = AlignCondition.Create(parent, mountCircleR, pitchCircleR);
            //		matingCondition = TangentCondition.Create(parent, pitchCircleL, pitchCircleR);
            GearCondition gearCondition = GearCondition.Create(parent, pitchCircleL, pitchCircleR);

            if (gearDataL.IsInternal ^ gearDataR.IsInternal)
            {
                gearCondition.IsBelt = true;
            }

            ActiveWindow.InteractionMode = InteractionMode.Solid;

            Settings.Default.NumberOfTeethL       = numberOfTeethL;
            Settings.Default.NumberOfTeethR       = numberOfTeethR;
            Settings.Default.PressureAngleDegrees = pressureAngle * 180 / Math.PI;
            Settings.Default.Module            = module;
            Settings.Default.Depth             = depth;
            Settings.Default.DedendumClearance = dedendumClearance;

            Settings.Default.UseTrochoidalInterferenceRemoval = useTrochoidalInterferenceRemoval;
            Settings.Default.AddDedendumClearace = addDedendumClearance;

            Settings.Default.IsBevel = isBevel;
            if (isBevel)
            {
                Settings.Default.BevelAngle     = bevelAngle * 180 / Math.PI;
                Settings.Default.BevelKneeRatio = bevelKneeRatio;
            }

            Settings.Default.IsHelical    = isHelical;
            Settings.Default.HelicalAngle = helicalAngle * 180 / Math.PI;

            Settings.Default.IsScrew          = isScrew;
            Settings.Default.ScrewAngle       = screwAngle * 180 / Math.PI;
            Settings.Default.ScrewAngleOffset = screwAngleOffset * 180 / Math.PI;

            Settings.Default.IsHypoid     = isHypoid;
            Settings.Default.HypoidAngle  = hypoidAngle * 180 / Math.PI;
            Settings.Default.HypoidOffset = hypoidOffset * lengthConversion;

            Settings.Default.Save();
        }
Exemple #12
0
        //Method returning the FitConfig instance (i.e., including the basic rules determining when a fit is valid) associated with the given input conditions
        private FitConfig getAssociatedFitConfig(Accuracy expectedAccuracy)
        {
            FitConfig curFitConfig = new FitConfig();

            if (expectedAccuracy == Accuracy.High)
            {
                curFitConfig.averLimit = 0.05;
                curFitConfig.minPercBelowLimit = 0.85;
                curFitConfig.globalAver = 0.10;
                curFitConfig.minNoCases = 50;
            }
            else if (expectedAccuracy == Accuracy.Medium)
            {
                curFitConfig.averLimit = 0.15;
                curFitConfig.minPercBelowLimit = 0.8;
                curFitConfig.globalAver = 0.25;
                curFitConfig.minNoCases = 35;
            }
            else if (expectedAccuracy == Accuracy.Low)
            {
                curFitConfig.averLimit = 0.3;
                curFitConfig.minPercBelowLimit = 0.7;
                curFitConfig.globalAver = 0.35;
                curFitConfig.minNoCases = 20;
            }
            curFitConfig.expectedAccuracy = expectedAccuracy;

            return curFitConfig;
        }
Exemple #13
0
        //Method returning the color associated with the input accuracy (e.g., Green for High)
        private Color getAccuracyColor(Accuracy curAccuracy)
        {
            Color curColor = Color.DarkGreen;
            if (curAccuracy == Accuracy.Medium)
            {
                curColor = Color.DarkOrange;
            }
            else if (curAccuracy == Accuracy.Low)
            {
                curColor = Color.DarkRed;
            }

            return curColor;
        }
Exemple #14
0
 private double GetPp(Beatmap beatmap, double acc, Mods mods = Mods.NoMod)
 {
     _accCalculator = new Accuracy(acc, beatmap.Objects.Count, 0);
     _ppCalculator  = new PPv2(new PPv2Parameters(beatmap, _accCalculator.Count100, _accCalculator.Count50, _accCalculator.CountMiss, -1, _accCalculator.Count300, mods));
     return(Math.Round(_ppCalculator.Total, 2));
 }
 public ComputeJobOptimizationAttribute(Accuracy accuracy, Support support) : base(accuracy, support)
 {
 }
 public BurstCompileAttribute(Accuracy accuracy, Support support)
 {
     Support  = support;
     Accuracy = accuracy;
 }
Exemple #17
0
 public static void setAccuracy(this Criteria criteria, Accuracy value)
 {
     criteria.Accuracy = value;
 }
Exemple #18
0
        /// <summary>
        /// Parallelized OCR Orientation Confidence Detector, this method will run ocr on 
        /// an image and its corresponding reversed images and return the confidence and 
        /// both the ocrdata objects
        /// </summary>
        /// <param name="regs">Images with default regular orientation</param>
        /// <param name="revs">Images with reversed orientation to default</param>
        /// <param name="mode">OCR accuracy mode</param>
        /// <param name="lang">OCR languages</param>
        /// <param name="enableTimer">Enable timer for diagnostic purposes</param>
        /// <returns>Tuple containing confidence, regular ocrdata and reversed ocrdata.
        ///  Positive confidence is for Regular where as negative 
        ///  confidences is for Reversed</returns>
        public static Tuple<long, OcrData, OcrData>[] ParallelDetectOrientation(
            Bitmap[] regs,
            Bitmap[] revs,
            Accuracy mode = Accuracy.High,
            string lang = "eng",
            bool enableTimer = false)
        {
            if (regs.Length != revs.Length)
            {
                throw new ArgumentException("Input Arrays must be same length!");
            }

            // create new array and copy over image references
            int pivot = regs.Length;
            Bitmap[] images = new Bitmap[regs.Length + revs.Length];
            Array.Copy(regs, images, pivot);
            Array.Copy(revs, 0, images, pivot, pivot);

            // Run Parallel Recognition on the arrays
            OcrData[] datas = ParallelRecognize(images, pivot + pivot, mode, lang, enableTimer);

            // Extract results and calculate confidence
            Tuple<long, OcrData, OcrData>[] results = new Tuple<long, OcrData, OcrData>[pivot];
            for (int ii = 0; ii < pivot; ii++)
            {
                OcrData reg = datas[ii];
                OcrData rev = datas[ii + pivot];

                // If postive we are confident about the current orientation
                // if negative we are not confident about the current orientation
                long confidence = rev.Cost - reg.Cost;
                results[ii] = new Tuple<long, OcrData, OcrData>(confidence, reg, rev);
            }
            return results;
        }
Exemple #19
0
 /// <summary>
 ///   Execute OCR on a given image, this static member will process the image,
 ///   Safely open, execute and dispose a Tesseract Object and store the result
 ///   in a new OcrData object.
 /// </summary>
 /// <param name="original"> Image to be OCR-ed </param>
 /// <param name="mode"> Accuracy setting </param>
 /// <param name="lang"> Language of text for OCR Language Model </param>
 /// <param name="enableTimer"> Measure the Scantime for Diagnostic purposes </param>
 /// <returns> </returns>
 public static OcrData Recognize(Bitmap original,
     Accuracy mode = Accuracy.High,
     string lang = "eng",
     bool enableTimer = false)
 {
     Image<Bgra, byte> img = new Image<Bgra, byte>(original);
     Image<Gray, byte> processed;
     Tesseract.Charactor[] chars;
     String text;
     long confidence;
     long scantime = Int64.MinValue;
     using (OCR ocr = new OCR(mode, lang, enableTimer))
     {
         processed = ocr.Preprocess(img);
         ocr.Scan(processed);
         confidence = ocr.OverallCost();
         chars = ocr.Charactors();
         text = ocr.Text();
         if (enableTimer)
         {
             scantime = ocr.Elapsed();
             ocr.Stop();
         }
     }
     img.Dispose();
     if (scantime == Int64.MinValue)
     {
         return new OcrData(processed, chars, text, confidence);
     }
     return new OcrData(processed, chars, text, confidence, scantime);
 }
 /// <summary>
 ///     Search by coordinates.
 /// </summary>
 /// <param name="coordinates">The coordinates.</param>
 /// <param name="metric">     The metric.</param>
 /// <param name="language">   The language.</param>
 /// <param name="count">      The count.</param>
 /// <param name="accuracy">   The accuracy.</param>
 /// <returns>
 ///     Task {SearchResponse}.
 /// </returns>
 /// <seealso cref="M:OpenWeatherMap.ISearchClient.GetByCoordinates(Coordinates,MetricSystem,OpenWeatherMapLanguage,int?,Accuracy?)"/>
 public Task<SearchResponse> GetByCoordinates(Coordinates coordinates, MetricSystem metric = MetricSystem.Internal, OpenWeatherMapLanguage language = OpenWeatherMapLanguage.EN, int? count = null, Accuracy? accuracy = null)
 {
     return this.GetByCoordinates<SearchResponse>(coordinates, metric, language, count, accuracy);
 }
Exemple #21
0
        private static void Main()
        {
            const int imageSize = 28;

            int[]       layers       = { 128, 64, 10 };
            const int   batchSize    = 100;
            const int   maxEpoch     = 10;
            const float learningRate = 0.1f;
            const float weightDecay  = 1e-2f;

            var trainIter = new MXDataIter("MNISTIter")
                            .SetParam("image", "./mnist_data/train-images-idx3-ubyte")
                            .SetParam("label", "./mnist_data/train-labels-idx1-ubyte")
                            .SetParam("batch_size", batchSize)
                            .SetParam("flat", 1)
                            .CreateDataIter();
            var valIter = new MXDataIter("MNISTIter")
                          .SetParam("image", "./mnist_data/t10k-images-idx3-ubyte")
                          .SetParam("label", "./mnist_data/t10k-labels-idx1-ubyte")
                          .SetParam("batch_size", batchSize)
                          .SetParam("flat", 1)
                          .CreateDataIter();

            var net = Mlp(layers);

            Context ctx = Context.Gpu();  // Use GPU for training

            var args = new SortedDictionary <string, NDArray>();

            args["X"]     = new NDArray(new Shape(batchSize, imageSize * imageSize), ctx);
            args["label"] = new NDArray(new Shape(batchSize), ctx);
            // Let MXNet infer shapes of other parameters such as weights
            net.InferArgsMap(ctx, args, args);

            // Initialize all parameters with uniform distribution U(-0.01, 0.01)
            var initializer = new Uniform(0.01f);

            foreach (var arg in args)
            {
                // arg.first is parameter name, and arg.second is the value
                initializer.Operator(arg.Key, arg.Value);
            }

            // Create sgd optimizer
            var opt = OptimizerRegistry.Find("sgd");

            opt.SetParam("rescale_grad", 1.0 / batchSize)
            .SetParam("lr", learningRate)
            .SetParam("wd", weightDecay);
            var lrSch = new UniquePtr <LRScheduler>(new FactorScheduler(5000, 0.1f));

            opt.SetLearningRateScheduler(lrSch);

            // Create executor by binding parameters to the model
            using (var exec = net.SimpleBind(ctx, args))
            {
                var argNames = net.ListArguments();

                // Create metrics
                Accuracy trainAcc = new Accuracy();
                Accuracy valAcc   = new Accuracy();

                // Start training
                var sw = new Stopwatch();
                for (var iter = 0; iter < maxEpoch; ++iter)
                {
                    var samples = 0;
                    trainIter.Reset();
                    trainAcc.Reset();

                    sw.Restart();

                    while (trainIter.Next())
                    {
                        samples += batchSize;
                        var dataBatch = trainIter.GetDataBatch();
                        // Data provided by DataIter are stored in memory, should be copied to GPU first.
                        dataBatch.Data.CopyTo(args["X"]);
                        dataBatch.Label.CopyTo(args["label"]);
                        // CopyTo is imperative, need to wait for it to complete.
                        NDArray.WaitAll();

                        // Compute gradients
                        exec.Forward(true);
                        exec.Backward();

                        // Update parameters
                        for (var i = 0; i < argNames.Count; ++i)
                        {
                            if (argNames[i] == "X" || argNames[i] == "label")
                            {
                                continue;
                            }

                            opt.Update(i, exec.ArgmentArrays[i], exec.GradientArrays[i]);
                        }
                        // Update metric
                        trainAcc.Update(dataBatch.Label, exec.Outputs[0]);
                    }
                    // one epoch of training is finished
                    sw.Stop();

                    var duration = sw.ElapsedMilliseconds / 1000.0;
                    Logging.LG($"Epoch[{iter}] {samples / duration} samples/sec Train-Accuracy={trainAcc.Get()}");

                    valIter.Reset();
                    valAcc.Reset();
                    while (valIter.Next())
                    {
                        var dataBatch = valIter.GetDataBatch();
                        dataBatch.Data.CopyTo(args["X"]);
                        dataBatch.Label.CopyTo(args["label"]);
                        NDArray.WaitAll();

                        // Only forward pass is enough as no gradient is needed when evaluating
                        exec.Forward(false);
                        valAcc.Update(dataBatch.Label, exec.Outputs[0]);
                    }
                    Logging.LG($"Epoch[{iter}] Val-Accuracy={valAcc.Get()}");
                }
            }

            MXNet.MXNotifyShutdown();
        }
 /// <summary>
 ///     Search by city name.
 /// </summary>
 /// <param name="cityName">Name of the city.</param>
 /// <param name="metric">  The metric.</param>
 /// <param name="language">The language.</param>
 /// <param name="count">   The count.</param>
 /// <param name="accuracy">The accuracy.</param>
 /// <returns>
 ///     Task {SearchResponse}.
 /// </returns>
 /// <seealso cref="M:OpenWeatherMap.ISearchClient.GetByName(string,MetricSystem,OpenWeatherMapLanguage,int?,Accuracy?)"/>
 public Task<SearchResponse> GetByName(string cityName, MetricSystem metric = MetricSystem.Internal, OpenWeatherMapLanguage language = OpenWeatherMapLanguage.EN, int? count = null, Accuracy? accuracy = null)
 {
     return this.GetByName<SearchResponse>(cityName, metric, language, count, accuracy);
 }
        /// <summary>
        /// Returns a detailed <see cref="System.String"/> that represents this confusion matrix.
        /// </summary>
        /// <returns>A <see cref="System.String"/> that represents this confusion matrix.</returns>
        /// <remarks></remarks>
        public override string ToString()
        {
            // Write the summary values

            string summary = "";

            summary += "Correct: " + Correct;
            summary += "  Incorrect: " + Incorrect;
            summary += "  Total: " + Observations;
            summary += "  Accuracy: " + Accuracy.ToString("F4");
            summary += "  Error: " + Error.ToString("F4");
            summary += "  Confidence: +/- " + ConfidenceInterval.ToString("F4");
            summary += "  Variance: " + Variance.ToString("F4");
            summary += "\n\n\n";

            // Calculate padding values

            int[] padding = new int[values.Count + 1];
            int   i;
            int   sp = 2;

            foreach (KeyValuePair <string, SortedDictionary <string, int> > pair in values)
            {
                if (pair.Key.Length > padding[0])
                {
                    padding[0] = pair.Key.Length;
                }

                i = 1;
                foreach (KeyValuePair <string, int> pair2 in pair.Value)
                {
                    if (pair2.Value.ToString().Length > padding[i])
                    {
                        padding[i] = pair2.Value.ToString().Length;
                    }
                    i += 1;
                }
            }

            // Write the header
            string output = "";

            output += "".PadRight(padding[0] + 3);

            i = 1;
            foreach (KeyValuePair <string, SortedDictionary <string, int> > pair in values)
            {
                output += pair.Key.PadRight(padding[i] + sp);
                i      += 1;
            }
            output += "\n   ".PadRight(output.Length, '-') + "\n";

            // Write each horizontal line

            foreach (KeyValuePair <string, SortedDictionary <string, int> > pair in values)
            {
                output += pair.Key.PadRight(padding[0]) + " | ";

                i = 1;
                foreach (KeyValuePair <string, int> pair2 in pair.Value)
                {
                    output += pair2.Value.ToString().PadRight(padding[i] + sp);
                    i      += 1;
                }
                output += "\n";
            }

            output += "\n\nConfusions:\n\n" + Confusions(-1);

            return(summary + output + "\n");
        }
Exemple #24
0
 public override Effect GetEffect()
 {
     PassiveEffect = new Accuracy(Level);
     return(PassiveEffect);
 }
Exemple #25
0
        /// <summary>
        /// Saves the data into a <see cref="XmlDocument"/> and returns it. It's up to caller to actually save the XML into a file. Optionally a closure can be assigned that will be called with the main project node - in case additional data needs to be saved.
        /// </summary>
        public XmlDocument Save(Action <XmlNode> projectNodeHandler = null)
        {
            var document = new XmlDocument();

            // Root node
            var rootNode = document.CreateElement("", "XML", "");

            document.AppendChild(rootNode);

            // Project root node
            var projectNode = rootNode.AddNode("Project");

            // Project name node
            var nameNode = projectNode.AddNode("Name");

            nameNode.AddAttribute("Projectname", Name);

            // Filenames
            foreach (var image in Images)
            {
                var fileNode = projectNode.AddNode("File");
                fileNode.AddAttribute("Path", image.Filename);
            }

            // Settings
            var settingsNode = projectNode.AddNode("Settings");

            switch (OutputType)
            {
            case OutputType.Sprites: settingsNode.AddAttribute("sprites", "true"); break;

            case OutputType.Tiles: settingsNode.AddAttribute("blocks", "true"); break;
            }
            settingsNode.AddAttribute("comments", (int)CommentType);
            settingsNode.AddAttribute("center", CenterPosition);
            settingsNode.AddAttribute("xSize", GridWidth);
            settingsNode.AddAttribute("ySize", GridHeight);
            settingsNode.AddAttribute("fourBit", FourBit);
            settingsNode.AddAttribute("binary", BinaryOutput);
            settingsNode.AddAttribute("binaryBlocks", BinaryBlocksOutput);
            settingsNode.AddAttribute("Repeats", IgnoreCopies);
            settingsNode.AddAttribute("MirrorX", IgnoreMirroredX);
            settingsNode.AddAttribute("MirrorY", IgnoreMirroredY);
            settingsNode.AddAttribute("Rotations", IgnoreRotated);
            settingsNode.AddAttribute("Transparent", IgnoreTransparentPixels);
            settingsNode.AddAttribute("Sort", TransparentFirst);
            settingsNode.AddAttribute("blocksImage", BlocksAsImage);
            settingsNode.AddAttribute("tilesImage", TilesAsImage);
            settingsNode.AddAttribute("transBlock", TransparentBlocks);
            settingsNode.AddAttribute("transTile", TransparentTiles);
            settingsNode.AddAttribute("across", BlocsAcross.ToString());
            settingsNode.AddAttribute("accurate", Accuracy.ToString());
            settingsNode.AddAttribute("format", (int)ImageFormat);
            settingsNode.AddAttribute("textFlips", TextFlips);
            settingsNode.AddAttribute("reduce", Reduced);

            // Palette
            var paletteNode = projectNode.AddNode("Palette");

            paletteNode.AddAttribute("Mapping", Enum.GetName(typeof(PaletteType), Palette.Type));
            paletteNode.AddAttribute("Transparent", Palette.TransparentIndex.ToString());
            paletteNode.AddAttribute("Used", Palette.UsedCount.ToString());
            for (int i = 0; i < Palette.Colours.Count; i++)
            {
                var colourNode = paletteNode.AddNode($"Colour{i}");
                var colour     = Palette.Colours[i];
                colourNode.AddAttribute("Red", colour.Red.ToString());
                colourNode.AddAttribute("Green", colour.Green.ToString());
                colourNode.AddAttribute("Blue", colour.Blue.ToString());
            }

            // Dialogs
            var dialogsNode = projectNode.AddNode("Dialogs");

            dialogsNode.AddAttribute("OutputIndex", OutputFilesFilterIndex.ToString());
            dialogsNode.AddAttribute("ImageIndex", AddImagesFilterIndex.ToString());

            // After all data is saved, pass project node to closure so additional data can be appended.
            if (projectNodeHandler != null)
            {
                projectNodeHandler(projectNode);
            }

            return(document);
        }
Exemple #26
0
 public SilencedPistol()
 {
     AccuracyChart = Accuracy.GetAccuracyChart(this);
 }
Exemple #27
0
 public GenTimeAccuracy(Accuracy accuracy)
 {
     this.accuracy = accuracy;
 }
Exemple #28
0
 public Rifle()
 {
     AccuracyChart = Accuracy.GetAccuracyChart(this);
 }
Exemple #29
0
        //------------------------------------------------------------------------------

        public TimeStampToken Generate(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime genTime)
        {
            DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid);

            AlgorithmIdentifier algID          = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest());

            Accuracy accuracy = null;

            if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
            {
                DerInteger seconds = null;
                if (accuracySeconds > 0)
                {
                    seconds = new DerInteger(accuracySeconds);
                }

                DerInteger millis = null;
                if (accuracyMillis > 0)
                {
                    millis = new DerInteger(accuracyMillis);
                }

                DerInteger micros = null;
                if (accuracyMicros > 0)
                {
                    micros = new DerInteger(accuracyMicros);
                }

                accuracy = new Accuracy(seconds, millis, micros);
            }

            DerBoolean derOrdering = null;

            if (ordering)
            {
                derOrdering = DerBoolean.GetInstance(ordering);
            }

            DerInteger nonce = null;

            if (request.Nonce != null)
            {
                nonce = new DerInteger(request.Nonce);
            }

            DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID);

            if (request.ReqPolicy != null)
            {
                tsaPolicy = new DerObjectIdentifier(request.ReqPolicy);
            }

            TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint,
                                          new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy,
                                          derOrdering, nonce, tsa, request.Extensions);

            try
            {
                CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();

                byte[] derEncodedTstInfo = tstInfo.GetDerEncoded();

                if (request.CertReq)
                {
                    signedDataGenerator.AddCertificates(x509Certs);
                }

                signedDataGenerator.AddCrls(x509Crls);
                signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr);

                CmsSignedData signedData = signedDataGenerator.Generate(
                    PkcsObjectIdentifiers.IdCTTstInfo.Id,
                    new CmsProcessableByteArray(derEncodedTstInfo),
                    true);

                return(new TimeStampToken(signedData));
            }
            catch (CmsException cmsEx)
            {
                throw new TspException("Error generating time-stamp token", cmsEx);
            }
            catch (IOException e)
            {
                throw new TspException("Exception encoding info", e);
            }
            catch (X509StoreException e)
            {
                throw new TspException("Exception handling CertStore", e);
            }
//			catch (InvalidAlgorithmParameterException e)
//			{
//				throw new TspException("Exception handling CertStore CRLs", e);
//			}
        }
Exemple #30
0
 public Pistol()
 {
     AccuracyChart = Accuracy.GetAccuracyChart(this);
 }
Exemple #31
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (MoveId != 0)
            {
                hash ^= MoveId.GetHashCode();
            }
            if (Category != global::ReMastersLib.Category.NoCategory)
            {
                hash ^= Category.GetHashCode();
            }
            if (U3 != 0)
            {
                hash ^= U3.GetHashCode();
            }
            if (User != global::ReMastersLib.User.Pokemon)
            {
                hash ^= User.GetHashCode();
            }
            if (Group != global::ReMastersLib.Group.None)
            {
                hash ^= Group.GetHashCode();
            }
            if (Type != 0)
            {
                hash ^= Type.GetHashCode();
            }
            if (Target != global::ReMastersLib.Target.AllySingle)
            {
                hash ^= Target.GetHashCode();
            }
            if (U8 != 0)
            {
                hash ^= U8.GetHashCode();
            }
            if (GaugeDrain != 0)
            {
                hash ^= GaugeDrain.GetHashCode();
            }
            if (Power != 0)
            {
                hash ^= Power.GetHashCode();
            }
            if (Accuracy != 0)
            {
                hash ^= Accuracy.GetHashCode();
            }
            if (Uses != 0)
            {
                hash ^= Uses.GetHashCode();
            }
            if (Tags != global::ReMastersLib.Tag.None)
            {
                hash ^= Tags.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemple #32
0
        public static Body CreatePolygon(IList <Point> inputPoints, Plane plane, double thickness)
        {
            List <ITrimmedCurve> profile = new List <ITrimmedCurve>();

            if (plane == null)
            {
                if (!AddInHelper.TryCreatePlaneFromPoints(inputPoints, out plane))
                {
                    return(null);
                }
            }

            Point        newPoint;
            Point        lastPoint = inputPoints[inputPoints.Count - 1].ProjectToPlane(plane);
            List <Point> points    = new List <Point>();

            foreach (Point point in inputPoints)
            {
                newPoint = point.ProjectToPlane(plane);
                if (!Accuracy.Equals(newPoint, lastPoint))
                {
                    points.Add(newPoint);
                    lastPoint = newPoint;
                }
            }

            for (int i = 0; i < points.Count; i++)
            {
                if (i < points.Count - 1)
                {
                    profile.Add(CurveSegment.Create(points[i], points[i + 1]));
                }
                else
                {
                    profile.Add(CurveSegment.Create(points[i], points[0]));
                }
            }

            Body body = null;

            try {
                if (thickness == 0)
                {
                    body = Body.CreatePlanarBody(plane, profile);
                }
                else
                {
                    body = Body.ExtrudeProfile(plane, profile, thickness);
                }
            }
            catch {
                string error = "Exception thrown creating planar body:\n";
                foreach (Point point in inputPoints)
                {
                    error += string.Format("{0}, {1}, {2}\n", point.X, point.Y, point.Z);
                }

                Debug.Assert(false, error);
            }

            if (body == null)
            {
                Debug.Fail("Profile was not connected, not closed, or not in order.");
                return(null);
            }

            return(body);
        }
Exemple #33
0
        public void Save(int moveNum)
        {
            if (!Directory.Exists(Paths.DataPath + "Move"))
            {
                Directory.CreateDirectory(Paths.DataPath + "Move");
            }
            using (XmlWriter writer = XmlWriter.Create(Paths.DataPath + "Move\\" + moveNum + ".xml", Logger.XmlWriterSettings)) {
                writer.WriteStartDocument();
                writer.WriteStartElement("MoveEntry");

                #region Basic data
                writer.WriteStartElement("General");
                writer.WriteElementString("Name", Name);
                writer.WriteElementString("Description", Desc);
                writer.WriteElementString("PP", PP.ToString());
                writer.WriteElementString("Type", Type.ToString());
                writer.WriteElementString("Category", Category.ToString());
                writer.WriteElementString("Contact", Contact.ToString());
                writer.WriteElementString("SoundBased", SoundBased.ToString());
                writer.WriteElementString("FistBased", FistBased.ToString());
                writer.WriteElementString("PulseBased", PulseBased.ToString());
                writer.WriteElementString("BulletBased", BulletBased.ToString());
                writer.WriteElementString("JawBased", BulletBased.ToString());
                writer.WriteElementString("Power", Power.ToString());
                writer.WriteElementString("Accuracy", Accuracy.ToString());
                writer.WriteElementString("Effect", Effect.ToString());
                writer.WriteElementString("Effect1", Effect1.ToString());
                writer.WriteElementString("Effect2", Effect2.ToString());
                writer.WriteElementString("Effect3", Effect3.ToString());
                writer.WriteElementString("HitsSelf", Range.HitsSelf.ToString());
                writer.WriteElementString("HitsFriend", Range.HitsFriend.ToString());
                writer.WriteElementString("HitsFoe", Range.HitsFoe.ToString());
                writer.WriteElementString("Range", Range.RangeType.ToString());
                writer.WriteElementString("Mobility", Range.Mobility.ToString());
                writer.WriteElementString("CutsCorners", Range.CutsCorners.ToString());
                writer.WriteElementString("Distance", Range.Distance.ToString());
                writer.WriteStartElement("StartAnim");
                StartAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteStartElement("StartUserAnim");
                StartUserAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteElementString("StartSound", StartSound.ToString());
                writer.WriteStartElement("MidAnim");
                MidAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteStartElement("MidUserAnim");
                MidUserAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteStartElement("MidTargetAnim");
                MidTargetAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteElementString("MidSound", MidSound.ToString());
                writer.WriteStartElement("EndAnim");
                EndAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteStartElement("EndUserAnim");
                EndUserAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteStartElement("EndTargetAnim");
                EndTargetAnim.Save(writer);
                writer.WriteEndElement();
                writer.WriteElementString("EndSound", EndSound.ToString());
                writer.WriteEndElement();
                #endregion

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Exemple #34
0
 public LocationMonitorImpl(Accuracy accuracy)
 {
     DesiredAccuracy = accuracy;
 }
Exemple #35
0
        /// <summary>
        ///   Parallelized Recognize Function takes in a list or array of images,
        ///   A specified length and for each image returns an OCRData object
        /// </summary>
        /// <param name="images"> Array or List of Bitmaps </param>
        /// <param name="length"> Number of items to be Recognized from the array </param>
        /// <param name="mode"> Accuracy Mode </param>
        /// <param name="lang"> Desired OCR Language </param>
        /// <param name="enableTimer"> Enables OCR Scan Timer if true </param>
        /// <returns> </returns>
        public static OcrData[] ParallelRecognize(IEnumerable<Bitmap> images,
            int length,
            Accuracy mode = Accuracy.High,
            string lang = "eng",
            bool enableTimer = false)
        {
            Tuple<int, Bitmap>[] indexedImages = new Tuple<int, Bitmap>[length];
            int index = 0;
            foreach (Bitmap image in images)
            {
                if (index >= length)
                {
                    break;
                }
                indexedImages[index] = new Tuple<int, Bitmap>(index, image);

                index += 1;
            }

            ConcurrentDictionary<int, OcrData> safeMap = new ConcurrentDictionary<int, OcrData>();

            Parallel.ForEach(indexedImages, pair =>
                {
                    int position = pair.Item1;
                    Bitmap image = pair.Item2;
                    safeMap[position] = Recognize(image, mode, lang, enableTimer);
                });

            OcrData[] data = new OcrData[length];
            foreach (KeyValuePair<int, OcrData> kvpair in safeMap)
            {
                data[kvpair.Key] = kvpair.Value;
            }

            return data;
        }
Exemple #36
0
        public void TestData()
        {
            var trainingData = ReadTestData("../../../../Data/train_sensor.txt", "../../../../Data/train_category.txt");

            var columnCount = 300;
            var cellsPerColumn = 1;

            var floatPrecision = 50;

            var node = new Node(
                inputCount: 32 * floatPrecision,
                columnCount: columnCount,
                cellsPerColumn: cellsPerColumn,
                desiredLocalActivity: 10,
                minOverlap: 2,
                maxSynapsesPerColumn: 20,
                newSynapseCount: 2
            );

            var cl = new AlsingClassifier();

            foreach (var frame in trainingData)
                node.Feed(BitMapper.Map(frame.Columns, -0.6f, 2.21f, floatPrecision));

            using (var log = new StreamWriter("../../../../Data/train_result.txt", false, Encoding.ASCII))
            foreach (var frame in trainingData)
            {
                node.Feed(BitMapper.Map(frame.Columns, -0.6f, 2.21f, floatPrecision));
                cl.Train(frame.Category.ToString(), node.ToArray());
                log.WriteLine(node.Select(v => v ? '1' : '0').ToArray());
            }

            node.Learning = false;

            var testData = ReadTestData("../../../../Data/test_sensor.txt", "../../../../Data/test_category.txt");

            var acurate = 0;
            var total = 0;

            var accuracy = new Dictionary<string, Accuracy>();

            using (var log = new StreamWriter("../../../../Data/test_result.txt", false, Encoding.ASCII))
            foreach (var frame in testData)
            {
                var activeCount = 0;

                Func<int, bool> input = BitMapper.Map(frame.Columns, -0.6f, 2.21f, floatPrecision);
                node.Feed(input);

                foreach (var b in node)
                    if (b)
                        activeCount++;

                var matches = cl.FindMatches(node.ToArray())
                    .OrderByDescending(c => c.Strength)
                    .Take(2)
                    .ToArray();

                log.WriteLine(node.Select(d => d ? '1' : '0').ToArray());

                /*for (var i = 0; i < 32 * 50; i++)
                    Console.Write(input(i) ? "1" : "0");
                Console.WriteLine();

                Console.WriteLine(String.Join("", outputData.Select(v => v ? "1" : "0")));*/

                var cat = frame.Category.ToString();
                if (matches[0].Identifier == cat) acurate++;
                total++;

                Accuracy v;
                if (!accuracy.TryGetValue(cat, out v))
                    accuracy.Add(cat, v = new Accuracy());

                if (matches[0].Identifier == frame.Category.ToString()) v.acurate++;
                v.total++;

                Console.WriteLine("Expected: {0}  Matched: {1} ({3:p})  Runner Up: {2} ({4:p})  Activity Count: {5}", frame.Category, matches[0].Identifier, matches[1].Identifier, matches[0].Strength, matches[1].Strength, activeCount);
            }
            Console.WriteLine("Accuracy: {0:p}", ((float)acurate) / ((float)total));

            foreach (var pair in accuracy)
                Console.WriteLine("Accuracy {1}: {0:p}", ((float)pair.Value.acurate) / ((float)pair.Value.total), pair.Key);
        }
Exemple #37
0
 private static extern short NOVAS_SiderealTime(double jdHigh, double jdLow, double detlaT, GstType gstType, Method method, Accuracy accuracy, ref double gst);
Exemple #38
0
        public static void RunConv()
        {
            var mnist      = TestUtils.GetMNIST();
            var batch_size = 128;
            var train_data = new NDArrayIter(mnist["train_data"], mnist["train_label"], batch_size, true);
            var val_data   = new NDArrayIter(mnist["test_data"], mnist["test_label"], batch_size);

            var net = new Sequential();

            net.Add(new Conv2D(20, kernel_size: (5, 5), activation: ActivationType.Tanh));
            net.Add(new MaxPool2D(pool_size: (2, 2), strides: (2, 2)));
            net.Add(new Conv2D(50, kernel_size: (5, 5), activation: ActivationType.Tanh));
            net.Add(new MaxPool2D(pool_size: (2, 2), strides: (2, 2)));
            net.Add(new Flatten());
            net.Add(new Dense(500, ActivationType.Tanh));
            net.Add(new Dense(10));

            var gpus = TestUtils.ListGpus();
            var ctx  = gpus.Count > 0 ? gpus.Select(x => Context.Gpu(x)).ToArray() : new[] { Context.Cpu(0) };

            net.Initialize(new Xavier(magnitude: 2.24f), ctx);
            var trainer = new Trainer(net.CollectParams(), new SGD(learning_rate: 0.02f));

            var   epoch  = 10;
            var   metric = new Accuracy();
            var   softmax_cross_entropy_loss = new SoftmaxCELoss();
            float lossVal = 0;

            for (var iter = 0; iter < epoch; iter++)
            {
                var tic = DateTime.Now;
                train_data.Reset();
                lossVal = 0;
                while (!train_data.End())
                {
                    var batch = train_data.Next();
                    var data  = Utils.SplitAndLoad(batch.Data[0], ctx, batch_axis: 0);
                    var label = Utils.SplitAndLoad(batch.Label[0], ctx, batch_axis: 0);

                    var outputs = new NDArrayList();
                    using (var ag = Autograd.Record())
                    {
                        for (var i = 0; i < data.Length; i++)
                        {
                            var x = data[i];
                            var y = label[i];

                            var     z    = net.Call(x);
                            NDArray loss = softmax_cross_entropy_loss.Call(z, y);
                            loss.Backward();
                            lossVal += loss.Mean();
                            outputs.Add(z);
                        }

                        //outputs = Enumerable.Zip(data, label, (x, y) =>
                        //{
                        //    var z = net.Call(x);
                        //    NDArray loss = softmax_cross_entropy_loss.Call(z, y);
                        //    loss.Backward();
                        //    lossVal += loss.Mean();
                        //    return z;
                        //}).ToList();
                    }

                    metric.Update(label, outputs.ToArray());
                    trainer.Step(batch.Data[0].Shape[0]);
                }

                var toc = DateTime.Now;

                var(name, acc) = metric.Get();
                metric.Reset();
                Console.Write($"Loss: {lossVal} ");
                Console.WriteLine($"Training acc at epoch {iter}: {name}={(acc * 100).ToString("0.##")}%, Duration: {(toc - tic).TotalSeconds.ToString("0.#")}s");
            }
        }
Exemple #39
0
        static void TestData(dynamic node, IEnumerable<TestFrame> trainingData, IEnumerable<TestFrame> testData, int warmUps, string trainingLog, string testLog, Func<float[], Func<int, bool>> floatMapper)
        {
            var enode = node as IEnumerable<bool>;

            var cl = new AlsingClassifier();

            var warmupStart = DateTime.Now;

            for (var w = 0; w < warmUps; w++)
                foreach (var frame in trainingData)
                    node.Feed(floatMapper(frame.Columns));

            var warmupEnd = DateTime.Now;

            var trainingStart = DateTime.Now;

            using (var log = trainingLog == null ? null : new StreamWriter(trainingLog, false, Encoding.ASCII))
                foreach (var frame in trainingData)
                {
                    node.Feed(floatMapper(frame.Columns));
                    cl.Train(frame.Category.ToString(), enode.ToArray());

                    if (log != null) log.WriteLine(String.Join(" ", enode.Select(d => d ? '1' : '0')));
                }

            var trainingEnd = DateTime.Now;

            node.Learning = false;

            var acurate = 0;
            var total = 0;

            var accuracy = new Dictionary<string, Accuracy>();

            var testStart = DateTime.Now;

            using (var log = testLog == null ? null : new StreamWriter(testLog, false, Encoding.ASCII))
                foreach (var frame in testData)
                {
                    var activeCount = 0;

                    Func<int, bool> input = floatMapper(frame.Columns);
                    node.Feed(input);

                    foreach (var b in enode)
                        if (b)
                            activeCount++;

                    var matches = cl.FindMatches(enode.ToArray())
                        .OrderByDescending(c => c.Strength)
                        .Take(2)
                        .ToArray();

                    if (log != null) log.WriteLine(String.Join(" ", enode.Select(d => d ? '1' : '0')));

                    var cat = frame.Category.ToString();
                    if (matches[0].Identifier == cat) acurate++;
                    total++;

                    Accuracy v;
                    if (!accuracy.TryGetValue(cat, out v))
                        accuracy.Add(cat, v = new Accuracy());

                    if (matches[0].Identifier == frame.Category.ToString()) v.acurate++;
                    v.total++;

                    Console.WriteLine("Expected: {0}  Matched: {1} ({3:p})  Runner Up: {2} ({4:p})  Activity Count: {5}", frame.Category, matches[0].Identifier, matches[1].Identifier, matches[0].Strength, matches[1].Strength, activeCount);
                }

            var testEnd = DateTime.Now;

            Console.WriteLine("Accuracy: {0:p}", ((float)acurate) / ((float)total));

            foreach (var pair in accuracy)
                Console.WriteLine("Accuracy {1}: {0:p}", ((float)pair.Value.acurate) / ((float)pair.Value.total), pair.Key);

            Console.WriteLine();
            Console.WriteLine("Warm up:\t{0:g}", warmupEnd - warmupStart);
            Console.WriteLine("Training:\t{0:g}", trainingEnd - trainingStart);
            Console.WriteLine("Test:\t{0:g}", testEnd - testStart);
        }
Exemple #40
0
 public static short SiderealTime(double jdHigh, double jdLow, double deltaT, GstType gstType, Method method, Accuracy accuracy, ref double gst)
 {
     return(NOVAS_SiderealTime(jdHigh, jdLow, deltaT, gstType, method, accuracy, ref gst));
 }
Exemple #41
0
 /// <summary>
 /// This function computes the apparent direction of a star or solar
 /// system body at a specified time and in a specified coordinate system
 /// </summary>
 /// <param name="jdTt"></param>
 /// <param name="celestialObject"></param>
 /// <param name="observer"></param>
 /// <param name="deltaT"></param>
 /// <param name="coordinateSystem"></param>
 /// <param name="accuracy"></param>
 /// <param name="position"></param>
 /// <returns></returns>
 public static short Place(double jdTt, CelestialObject celestialObject, Observer observer, double deltaT, CoordinateSystem coordinateSystem, Accuracy accuracy, ref SkyPosition position)
 {
     lock (lockObj) {
         var err = NOVAS_Place(jdTt, ref celestialObject, ref observer, deltaT, (short)coordinateSystem, (short)accuracy, ref position);
         return(err);
     }
 }
Exemple #42
0
 private void UpdateAccuracy(double accuracy)
 {
     Accuracy.Text += Environment.NewLine + accuracy;
     Accuracy.Refresh();
 }