Esempio n. 1
0
        public Bgr ColorChooser(PredictionResult pr)
        {
            if (pr.Distance > threshold)
            {
                return(new Bgr(Color.Black));
            }
            switch ((GenderEnum)pr.Label)
            {
            case GenderEnum.MALE:
                return(new Bgr(Color.Blue));

            case GenderEnum.FEMALE:
                return(new Bgr(Color.Crimson));

            default:
                return(new Bgr(Color.Black));
            }
        }
Esempio n. 2
0
        public void castETarget(AIHeroClient target)
        {
            if (!E.IsReady())
            {
                return;
            }
            if (player.HealthPercent > 25 && !safeGap(target))
            {
                return;
            }

            List <Obj_AI_Minion> solis = getUsableSoliders().Where(sol => !sol.IsMoving).ToList();

            if (solis.Count == 0)
            {
                return;
            }
            foreach (var sol in solis)
            {
                float toSol = player.Distance(sol.Position);

                //Collision.GetCollision(new List<Vector3>{sol.Position},getMyEPred(sol));
                PredictionResult po = E.GetPrediction(target);//, toSol / 1500f);

                if (sol.Distance(po.UnitPosition) < 325 && interact(player.Position.To2D(), sol.Position.To2D(), po.UnitPosition.To2D(), 65) &&
                    interactsOnlyWithTarg(target, sol, player.Distance(po.UnitPosition)))
                {
                    E.Cast(sol.Position);
                    return;
                }


                /*if (po.CollisionObjects.Count == 0)
                 *  continue;
                 * Console.WriteLine(po.CollisionObjects.Count);
                 * Obj_AI_Base col = po.CollisionObjects.OrderBy(obj => obj.Distance(Player.Position)).First();
                 * if (col.NetworkId == target.NetworkId)
                 * {
                 *  E.Cast(sol);
                 *  return;
                 * }*/
            }
        }
Esempio n. 3
0
 public void AddToInterface(PredictionResult predictionResult)
 {
     if (SelectedItem != null && predictionResult.Prediction == SelectedItem)
     {
         Selected.Add(new OutputPrediction {
             Prediction = predictionResult.Prediction, Image = new BitmapImage(new Uri(predictionResult.Path))
         });
     }
     foreach (var i in Number)
     {
         if (i.Label == predictionResult.Prediction)
         {
             i.Number++;
         }
     }
     All.Add(new OutputPrediction {
         Prediction = predictionResult.Prediction, Image = new BitmapImage(new Uri(predictionResult.Path))
     });
 }
Esempio n. 4
0
        private static bool CastE(AIHeroClient target)
        {
            var Enemies = EntityManager.Heroes.Enemies.Where(x => x.IsValidTarget(1100, false, myhero.Position));

            if (Enemies != null && DemSpells.E.IsReady())
            {
                foreach (AIHeroClient enemy in Enemies)
                {
                    PredictionResult epred = DemSpells.E.GetPrediction(enemy);

                    if (epred.HitChancePercent >= slider(pred, "EPred") && DemSpells.E.Cast(epred.CastPosition))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        public async Task ProcessMarket(string[] stockItems)
        {
            log.LogDebug("Processing market");
            var sentimentTask = await twitterAnalysis.GetTrackingResults(new SentimentRequest(stockItems.Select(item => $"${item}").ToArray()) { Hours = new[] { 24 } }, CancellationToken.None)
                                .ConfigureAwait(false);

            foreach (string stock in stockItems)
            {
                log.LogInformation("Processing {0}", stock);

                PredictionResult result = await instance().Start(stock).ConfigureAwait(false);

                double sellAccuracy = result.Performance.PerClassMatrices[0].Accuracy;
                double buyAccuracy  = result.Performance.PerClassMatrices[1].Accuracy;
                string header       = $"${stock} trading signals ({sellAccuracy * 100:F0}%/{buyAccuracy * 100:F0}%)";
                var    text         = new StringBuilder();

                if (sentimentTask.TryGetValue($"${stock}", out var sentiment))
                {
                    var sentimentValue = sentiment.First();
                    text.AppendFormat(
                        "Average sentiment: {2}{0:F2}({1})\r\n",
                        sentimentValue.Average,
                        sentimentValue.TotalMessages,
                        sentimentValue.GetEmoji());
                }
                else
                {
                    log.LogWarning("Not found sentiment for {0}", stock);
                }

                for (int i = 0; i < result.Predictions.Length || i < 2; i++)
                {
                    MarketDirection prediction = result.Predictions[result.Predictions.Length - i - 1];
                    log.LogInformation("{2}, Predicted T-{0}: {1}\r\n", i, prediction, stock);
                    string icon = prediction == MarketDirection.Buy ? Emoji.CHART_WITH_UPWARDS_TREND.Unicode : Emoji.CHART_WITH_DOWNWARDS_TREND.Unicode;
                    text.AppendFormat("T-{0}: {2}{1}\r\n", i, prediction, icon);
                }

                var message = new MultiItemMessage(header, new[] { text.ToString() });
                publisher.PublishMessage(message);
            }
        }
Esempio n. 6
0
        public async Task Start()
        {
            List <FileInfo> imagesForRecognition = new List <FileInfo> {
            };

            DirectoryInfo dir = new DirectoryInfo(FolderPath);

            var tasks = new List <Task>();

            classifier.CancelTokenSource = new CancellationTokenSource();
            CancellationToken token = classifier.CancelTokenSource.Token;

            foreach (var curImg in dir.GetFiles())
            {
                tasks.Add(Task.Factory.StartNew((img) =>
                {
                    PredictionResult predictionResult = ImageInDB(curImg);
                    CurDispatcher.Invoke(() =>
                    {
                        if (predictionResult == null)
                        {
                            imagesForRecognition.Add(curImg);
                        }
                        else
                        {
                            AddToInterface(predictionResult);
                        }
                    }, DispatcherPriority.Render);
                }, curImg, token));
            }

            Task t = Task.WhenAll(tasks);

            try
            {
                await t;
            }
            catch (OperationCanceledException ex)
            {
            }

            await classifier.PredictAll(imagesForRecognition);
        }
Esempio n. 7
0
 private bool HasNegativeSentiment(string sentence, PredictionResult result, AFINNPrediction secondOpinion)
 {
     if (Convert.ToBoolean(result.SentimentPrediction.Prediction) && result.SentimentPrediction.Probability > 0.97)
     {
         if (secondOpinion.Score < -2)
         {
             return(true); // both predictors agree on negative sentiment
         }
         else
         {
             _logger.LogInformation($"AFINN server disagrees with sentence {sentence} being negative");
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Esempio n. 8
0
 private bool HasPositiveSentiment(string sentence, PredictionResult result, dynamic secondOpinion)
 {
     if (!Convert.ToBoolean(result.SentimentPrediction.Prediction) && result.SentimentPrediction.Probability < 0.02)
     {
         if (secondOpinion.Score > 2)
         {
             return(true); // both predictors agree on positive sentiment
         }
         else
         {
             _logger.LogInformation($"AFINN server disagrees with sentence {sentence} being positive");
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Esempio n. 9
0
        public void ArePredicitionResultToStringReturningEmptyString()
        {
            var result = new PredictionResult
            {
                Predictions = new List <Prediction> {
                    new Prediction {
                        Probability = 0.2, TagName = "Restaurant1"
                    },
                    new Prediction {
                        Probability = 0.01, TagName = "Restaurant2"
                    },
                    new Prediction {
                        Probability = 0.1, TagName = "Restaurant3"
                    }
                }
            };

            Assert.AreEqual("", result.ToString(), "The Prediction Result is " + result.ToString() + ", while expected \"\".");
        }
Esempio n. 10
0
 private async Task SavePrediction(PredictionResult result, string qcStr)
 {
     if (result.SaveType == "Update")
     {
         UpdateAction(result, qcStr);
     }
     else if (result.SaveType == "Insert")
     {
         InsertAction(result);
     }
     else if (result.SaveType == "Delete")
     {
         await DeleteAction(result, qcStr);
     }
     else
     {
         //logger.LogWarning($"Save type {result.SaveType} is not supported");
     }
 }
Esempio n. 11
0
        private VisionObject FromPrediction(string fileExtension, Bitmap img, PredictionResult prediction)
        {
            var fileInfo = new FileInfo(string.Format(@"C:\Folder\{0}.{1}", Guid.NewGuid(), fileExtension));
            var boxImg   = GetBoxImage(img, prediction.BoundingBox);
            var imgBytes = GetImageBytes(boxImg, GetFormat(fileExtension));
            var ocr      = _ocrService.DoOcr(fileInfo, imgBytes);
            var result   = new VisionObject()
            {
                Location = new Rectangle()
                {
                    X = 0, Y = 0, Width = boxImg.Width, Height = boxImg.Height
                },
                Probability = prediction.Probability,
                TagName     = prediction.TagName,
                OcrResult   = ocr.Data
            };

            return(result);
        }
Esempio n. 12
0
        public static void Harassmode()
        {
            var bestMinion =
                ObjectManager.Get <Obj_AI_Minion>()
                .Where(x => x.IsValidTarget(Program.E.Range))
                .Where(x => x.Distance(Game.CursorPos) < Variables._Player.Distance(Game.CursorPos))
                .OrderByDescending(x => x.Distance(Variables._Player))
                .FirstOrDefault();

            if (bestMinion != null && Variables._Player.IsFacing(bestMinion) && Variables.CanCastE(bestMinion) &&
                (Program.E.IsReady() && MenuManager.HarassMenu["E"].Cast <CheckBox>().CurrentValue))
            {
                Program.E.Cast(bestMinion);
            }
            var TsTarget = TargetSelector.GetTarget(1300, DamageType.Physical);

            if (TsTarget == null)
            {
                return;
            }
            if (Program.Q.IsReady() && MenuManager.HarassMenu["Q3"].Cast <CheckBox>().CurrentValue)
            {
                PredictionResult QPred = Program.Q.GetPrediction(TsTarget);
                if (!Variables.isDashing && QPred.HitChance >= EloBuddy.SDK.Enumerations.HitChance.Medium)
                {
                    Program.Q.Cast(QPred.CastPosition);
                    Core.DelayAction(Orbwalker.ResetAutoAttack, 250);
                }
                else if (Variables.Q3READY(Variables._Player) && Variables.isDashing &&
                         Variables._Player.Distance(TsTarget) <= 250 * 250)
                {
                    Program.Q.Cast(QPred.CastPosition);
                    Core.DelayAction(Orbwalker.ResetAutoAttack, 250);
                }
            }
            PredictionResult QPred2 = Program.Q.GetPrediction(TsTarget);

            if (!Variables.Q3READY(Variables._Player) && QPred2.HitChance >= EloBuddy.SDK.Enumerations.HitChance.Medium)
            {
                Program.Q.Cast(QPred2.CastPosition);
                Core.DelayAction(Orbwalker.ResetAutoAttack, 250);
            }
        }
Esempio n. 13
0
 public override void Execute()
 {
     if (Player.Instance.ManaPercent < 25)
     {
         return;
     }
     // TODO: Add harass logic here
     // See how I used the Settings.UseQ and Settings.Mana here, this is why I love
     // my way of using the menu in the Config class!
     if (Settings.UseE)
     {
         AIHeroClient target = TargetSelector.GetTarget(E.Range, DamageType.Physical);
         if (target != null)
         {
             PredictionResult pred = E.GetPrediction(target);
             if (pred.HitChancePercent >= 80)
             {
                 E.Cast(target);
             }
         }
     }
     if (Settings.UseQ && Q1.IsReady())
     {
         //EntityManager.Heroes.Enemies.ForEach(e => e.Buffs.ForEach(b=>Logger.Debug(b.Name)));
         AIHeroClient target = EntityManager.Heroes.Enemies.Where
                                   (hero => hero.Distance(Player.Instance) < 1200 && hero.HasBuff("urgotcorrosivedebuff"))
                               .OrderBy(TargetSelector.GetPriority)
                               .FirstOrDefault();
         if (target != null)
         {
             Q2.Cast(target);
         }
         else
         {
             target = TargetSelector.GetTarget(Q1.Range, DamageType.Physical);
             if (target != null)
             {
                 Q1.Cast(target);
             }
         }
     }
 }
Esempio n. 14
0
        private static void AutoR()
        {
            if (comboMenu["combouser"].Cast <CheckBox>().CurrentValue&& Spells[SpellSlot.R].IsReady())
            {
                List <AIHeroClient> enemies = EntityManager.Heroes.Enemies.Where(enemy => enemy.IsValid && !enemy.IsDead && Player.Instance.IsInRange(enemy, Spells[SpellSlot.R].Range)).ToList();

                if (enemies.Count() >= comboMenu["combocountr"].Cast <Slider>().CurrentValue)
                {
                    foreach (AIHeroClient enemy in enemies)
                    {
                        PredictionResult predictionResult = Prediction.Position.PredictLinearMissile(enemy, Spells[SpellSlot.R].Range, 125, 500, 3000, 0, Player.Instance.ServerPosition);
                        if (predictionResult.CollisionObjects.Count(x => x.IsValid() && !enemy.IsDead && x.Type == GameObjectType.AIHeroClient) + 1 >= comboMenu["combocountr"].Cast <Slider>().CurrentValue)
                        {
                            Spells[SpellSlot.R].Cast(predictionResult.CastPosition);
                            return;
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        private static void AutoWImmobile()
        {
            if (!Spells["w"].IsReady())
            {
                return;
            }

            foreach (AIHeroClient enemy in EntityManager.Heroes.Enemies.Where(x => x.IsValidTarget(Spells["w"].Range)))
            {
                PredictionResult pred = Spells["w"].GetPrediction(enemy);

                if (pred.HitChance == HitChance.Immobile)
                {
                    if (Spells["w"].Cast(pred.CastPosition))
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 16
0
        public void Analyze_doesnt_send_sentence_for_storage_if_ml_model_predicts_negative_but_afinn_disagrees()
        {
            var afinnMock = new Mock <IAFINN>();

            // predicts positive
            afinnMock.Setup(afinn => afinn.Predict(It.IsAny <string>())).ReturnsAsync(new AFINNPrediction()
            {
                Score = 3
            });
            var mlModelMock       = new Mock <IMLModel>();
            var neutralPrediction = new PredictionResult();

            neutralPrediction.Sentence = "doesnt matter for this test";
            // predicts negative
            neutralPrediction.SentimentPrediction = new SentimentPrediction()
            {
                Prediction = true, Probability = 0.99F, Score = 0
            };
            mlModelMock.Setup(ml => ml.Predict(It.IsAny <string>()))
            .Returns(neutralPrediction);
            var pipelineMock = new Mock <IPipeline>();
            var loggerMock   = new Mock <ILogger <Engine> >();
            var engine       = new Engine(loggerMock.Object, pipelineMock.Object, mlModelMock.Object, afinnMock.Object);

            var testArticle = new Article();

            testArticle.ArticleUrl = "http://madeupnews.com/article-one";
            testArticle.Header     = "Article number one";
            testArticle.Keywords   = new List <string>()
            {
                "magicKeyword"
            };
            testArticle.Source = "http://madeupnews.com";
            testArticle.Text   = @"This is one sentence. This is another sentence but non of the first two contains
            the keyword. This, third sentence, however does contain magicKeyword, which is what we are looking for";

            engine.Analyze(testArticle);
            afinnMock.Verify(a => a.Predict(It.IsAny <string>()), Times.Exactly(1));
            mlModelMock.Verify(m => m.Predict(It.IsAny <string>()), Times.Exactly(1));
            pipelineMock.Verify(p => p.SendForStorage(It.IsAny <AnalyzedSentence>()), Times.Exactly(0));
        }
Esempio n. 17
0
        public static void LogReport(PredictionResult result, LocationDetail loc)
        {
            RestClient _client = new RestClient(System.Configuration.ConfigurationManager.AppSettings["ElasticUrl"]);

            foreach (var prediction in result.Predictions)
            {
                var logEntry = new LogDetails
                {
                    Time        = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffZ"),
                    Location    = loc,
                    ReportedDis = prediction.TagName.Split('_')[1],
                    Crop        = prediction.TagName.Split('_')[0],
                    Probability = prediction.Probability * 100
                };

                var request = new RestRequest(Method.POST);
                request.RequestFormat = DataFormat.Json;
                request.AddBody(logEntry);
                var response = _client.Execute(request);
            }
        }
Esempio n. 18
0
        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage bi         = videoPlayer.Source.Clone() as BitmapImage;
            string      folderPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            string      fileName   = $"{folderPath}\\lulu.png";

            //save the image
            bi.Save(fileName);

            //test if its lulu

            Gateway g = new Gateway();
            var     r = await g.MakePredictionRequest(fullfilepath : fileName);

            var pr = PredictionResult.FromJson(r);

            if (pr.Predictions.Any())
            {
                Prediction = (pr.Predictions.First().Probability * 100).ToString("n");
            }
        }
Esempio n. 19
0
 private void RecognizeFaces(object sender, FaceFoundEventArgs args)
 {
     using (Image <Bgr, byte> image = new Image <Bgr, byte>(args.FileName))
     {
         using (var face = image.Copy(args.Face).Convert <Gray, byte>().Resize(100, 100, Inter.Cubic))
         {
             PredictionResult prediction = _currentFaceRecognizer.Predict(face);
             if (prediction.Label > -1)
             {
                 DoOnFaceRecognized(this,
                                    new FaceRecognizedEventArgs()
                 {
                     Face     = args.Face,
                     FileName = args.FileName,
                     LabelId  = prediction.Label,
                     Label    = _faceLabels[prediction.Label]
                 });
             }
         }
     }
 }
Esempio n. 20
0
        public SinglePrediction PostSingleImg([FromBody] string[] base64string_and_path)
        {
            string base64string = base64string_and_path[0];
            string path         = base64string_and_path[1];

            Console.WriteLine("process single image");

            var mdl = new Model("C:/test_mdl/resnet50-v2-7.onnx", null);


            PredictionResult res         = mdl.WorkSingleImg(base64string, path);
            SinglePrediction single_pred = new SinglePrediction()
            {
                Path       = res.Path,
                Confidence = res.Confidence,
                Label      = res.Label,
                Image      = base64string
            };

            return(single_pred);
        }
Esempio n. 21
0
        private void InsertMissingObjectToDatabase(PredictionResult result)
        {
            string  jsonDataObject = result.DataObject;
            JObject dataObject     = JObject.Parse(jsonDataObject);

            dataObject["ROW_CHANGED_BY"] = Environment.UserName;
            dataObject["ROW_CREATED_BY"] = Environment.UserName;
            jsonDataObject = dataObject.ToString();
            jsonDataObject = Helpers.Common.SetJsonDataObjectDate(jsonDataObject, "ROW_CHANGED_DATE");
            jsonDataObject = Helpers.Common.SetJsonDataObjectDate(jsonDataObject, "ROW_CREATED_DATE");
            string dataType = result.DataType;

            try
            {
                _dbConn.InsertDataObject(jsonDataObject, dataType);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 22
0
        public IIdentifier GetIdentity(IFaceImage img)
        {
            IIdentifier answ   = new Identifier(int.MinValue);
            var         labels = _labelRepo.GetAll();

            foreach (var label in labels)
            {
                IEnumerable <IFaceImage>   batch     = label.Images;
                List <Image <Gray, Byte> > compBatch = new List <Image <Gray, Byte> >();
                List <int> trainingLabels            = new List <int>();

                int enumerator = 0;
                foreach (var current in batch)
                {
                    compBatch.Add(new Image <Gray, Byte>(current.ImageOfFace));
                    trainingLabels.Add(enumerator++);
                }

                FaceRecognizer recognizer = new LBPHFaceRecognizer(_recognizerRadius, _recognizerNeighbors,
                                                                   _recognizerGridX, _recognizerGridY, _recognizerThreshold);

                recognizer.Train(compBatch.ToArray(), trainingLabels.ToArray());

                PredictionResult result = recognizer.Predict(new Image <Gray, Byte>(img.ImageOfFace));
                if (result.Distance < _minDistanse)
                {
                    _minDistanse = result.Distance;
                    answ         = label.Id;
                }
            }
            if (_minDistanse < _requiredDistance)
            {
                return(answ);
            }
            else
            {
                return(new Identifier(-1));
            }
        }
Esempio n. 23
0
        public void ArePredicitionResultToStringReturningGoodElement()
        {
            var result = new PredictionResult
            {
                Predictions = new List <Prediction> {
                    new Prediction {
                        Probability = 0.5, TagName = "Restaurant1"
                    },
                    new Prediction {
                        Probability = 8.5, TagName = "Restaurant2"
                    },
                    new Prediction {
                        Probability = 73.5, TagName = "Restaurant3"
                    },
                    new Prediction {
                        Probability = 65.5, TagName = "Restaurant4"
                    }
                }
            };

            Assert.AreEqual("Restaurant3", result.ToString(), "The Prediction Result is " + result.ToString() + ", while expected Restaurant3.");
        }
Esempio n. 24
0
        public void Analyze_doesnt_analyze_sentences_that_doesnt_contain_keyword()
        {
            var afinnMock = new Mock <IAFINN>();

            afinnMock.Setup(afinn => afinn.Predict(It.IsAny <string>())).ReturnsAsync(new AFINNPrediction()
            {
                Score = -1
            });
            var mlModelMock       = new Mock <IMLModel>();
            var neutralPrediction = new PredictionResult();

            neutralPrediction.Sentence            = "doesnt matter for this test";
            neutralPrediction.SentimentPrediction = new SentimentPrediction()
            {
                Prediction = true, Probability = 0.550F, Score = 0
            };
            mlModelMock.Setup(ml => ml.Predict(It.IsAny <string>()))
            .Returns(neutralPrediction);
            var pipelineMock = new Mock <IPipeline>();
            var loggerMock   = new Mock <ILogger <Engine> >();
            var engine       = new Engine(loggerMock.Object, pipelineMock.Object, mlModelMock.Object, afinnMock.Object);

            var testArticle = new Article();

            testArticle.ArticleUrl = "http://madeupnews.com/article-one";
            testArticle.Header     = "Article number one";
            testArticle.Keywords   = new List <string>()
            {
                "magicKeyword"
            };
            testArticle.Source = "http://madeupnews.com";
            testArticle.Text   = @"This is one sentence. This is another sentence but non of these two contains
            the keyword.";

            engine.Analyze(testArticle);
            afinnMock.Verify(a => a.Predict(It.IsAny <string>()), Times.Exactly(0));
            mlModelMock.Verify(m => m.Predict(It.IsAny <string>()), Times.Exactly(0));
            pipelineMock.Verify(p => p.SendForStorage(It.IsAny <AnalyzedSentence>()), Times.Exactly(0));
        }
Esempio n. 25
0
 private void OnPredictionCome(PredictionResult pr, EventArgs e, bool isInBase = false)
 {
     Dispatcherr.BeginInvoke(DispatcherPriority.Background, new Action(() =>
     {
         Observ.Add(new RecognitionModel(pr.Path, pr.ClassLabel));
         int index = -1;
         foreach (var tmp in ClassObserv)
         {
             if (tmp.Item1.Equals(pr.ClassLabel))
             {
                 index = ClassObserv.IndexOf(tmp);
                 break;
             }
         }
         if (index != -1)
         {
             ClassObserv[index] = new Tuple <string, int>(ClassObserv[index].Item1, ClassObserv[index].Item2 + 1);
         }
         else
         {
             ClassObserv.Add(new Tuple <string, int>(pr.ClassLabel, 1));
         }
         if (!isInBase)
         {
             var newElem = new RecognitionModel(pr.Path, pr.ClassLabel);
             DataBaseContext.DataBaseInfo.Add(newElem);
             DataBaseContext.SaveChanges();
             if (DataBaseContext.ClassLabelsInfo.Find(newElem.ClassLabel) == null)
             {
                 DataBaseContext.ClassLabelsInfo.Add(new ClassInfo(newElem.ClassLabel, newElem));
             }
             else
             {
                 DataBaseContext.ClassLabelsInfo.Find(newElem.ClassLabel).RecogModel.Add(newElem);
             }
             DataBaseContext.SaveChanges();
         }
     }));
 }
Esempio n. 26
0
        static void Harass()
        {
            if (UseQHarass && Q.IsReady())
            {
                var enemy = TargetSelector.GetTarget(Q.Range, DamageType.Physical);
                if (enemy.IsValidTarget())
                {
                    Q.Cast(enemy);
                }
            }

            if (UseWHarass && W.IsReady())
            {
                AIHeroClient target    = TargetSelector.GetTarget(950, DamageType.Physical);
                var          autoWI    = HarassAutoWI;
                var          autoWD    = HarassAutoWD;
                var          hitchance = HitChance.High;
                if (target != null && W.IsReady())
                {
                    if (!EvolvedW && myHero.Distance(target) <= W.Range)
                    {
                        PredictionResult predw = W.GetPrediction(target);
                        if (predw.HitChance == hitchance)
                        {
                            W.Cast(predw.CastPosition);
                            return;
                        }
                    }
                    else if (EvolvedW && target.IsValidTarget(W.Range + 200))
                    {
                        PredictionResult pred = W.GetPrediction(target);
                        if ((pred.HitChance == HitChance.Immobile && autoWI) || (pred.HitChance == HitChance.Dashing && autoWD) || pred.HitChance >= hitchance)
                        {
                            CastWE(target, pred.UnitPosition.To2D());
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        public static PredictionResult PredictMissingDataObjects(QcRuleSetup qcSetup, DbUtilities dbConn)
        {
            PredictionResult result = new PredictionResult
            {
                Status = "Failed"
            };
            RuleModel rule          = JsonConvert.DeserializeObject <RuleModel>(qcSetup.RuleObject);
            string    rulePar       = rule.RuleParameters;
            JObject   ruleParObject = JObject.Parse(rulePar);
            string    dataType      = ruleParObject["DataType"].ToString();

            if (string.IsNullOrEmpty(rulePar))
            {
                throw new NullReferenceException("Rule parameter is null.");
            }
            string emptyJson = RuleMethodUtilities.GetJsonForMissingDataObject(rulePar, dbConn);

            if (emptyJson == "Error")
            {
                throw new NullReferenceException("Could not create an empty json data object, maybe you are missing Datatype in parameters");
            }
            string json = RuleMethodUtilities.PopulateJsonForMissingDataObject(rulePar, emptyJson, qcSetup.DataObject);

            if (json == "Error")
            {
                throw new NullReferenceException("Could not create an json data object, problems with keys in parameters");
            }
            json = RuleMethodUtilities.AddDefaultsForMissingDataObjects(rulePar, json);
            if (json == "Error")
            {
                throw new NullReferenceException("Could not create an json data object, problems with defaults in parameters");
            }
            result.DataObject = json;
            result.DataType   = dataType;
            result.SaveType   = "Insert";
            result.IndexId    = qcSetup.IndexId;
            result.Status     = "Passed";
            return(result);
        }
Esempio n. 28
0
 private void UpdateResult(PredictionResult predictionResult)
 {
     CurDispatcher.Invoke(() =>
     {
         if (SelectedItem != null && predictionResult.Prediction == SelectedItem)
         {
             Selected.Add(new OutputPrediction {
                 Prediction = predictionResult.Prediction, Image = new BitmapImage(new Uri(predictionResult.Path))
             });
         }
         foreach (var i in Number)
         {
             if (i.Label == predictionResult.Prediction)
             {
                 i.Number++;
             }
         }
         All.Add(new OutputPrediction {
             Prediction = predictionResult.Prediction, Image = new BitmapImage(new Uri(predictionResult.Path))
         });
     }, DispatcherPriority.Render);
 }
Esempio n. 29
0
        private void InsertMissingObjectToIndex(PredictionResult result)
        {
            IndexFileData indexdata = GetIndexFileData(result.DataType);

            if (indexdata.DataName != null)
            {
                JObject       dataObject    = JObject.Parse(result.DataObject);
                string        dataName      = dataObject[indexdata.NameAttribute].ToString();
                string        dataType      = result.DataType;
                DataAccessDef dataAccessDef = _accessDefs.First(x => x.DataType == dataType);
                string        dataKey       = GetDataKey(dataObject, dataAccessDef.Keys);
                int           parentId      = result.IndexId;
                string        jsonData      = result.DataObject;
                double        latitude      = -99999.0;
                double        longitude     = -99999.0;
                int           nodeId        = GeIndextNode(dataType, parentId);
                if (nodeId > 0)
                {
                    _dbConn.InsertIndex(nodeId, dataName, dataType, dataKey, jsonData, latitude, longitude);
                }
            }
        }
Esempio n. 30
0
        private void UpdateAction(PredictionResult result, string qcStr)
        {
            string            idxQuery   = $" where INDEXID = {result.IndexId}";
            IndexAccess       idxAccess  = new IndexAccess();
            List <IndexModel> idxResults = idxAccess.SelectIndexesByQuery(idxQuery, databaseConnectionString);

            if (idxResults.Count == 1)
            {
                string condition = $"INDEXID={result.IndexId}";
                var    rows      = indexTable.Select(condition);
                rows[0]["JSONDATAOBJECT"] = result.DataObject;
                rows[0]["QC_STRING"]      = qcStr;
                indexTable.AcceptChanges();

                if (syncPredictions)
                {
                    string  jsonDataObject = result.DataObject;
                    JObject dataObject     = JObject.Parse(jsonDataObject);
                    dataObject["ROW_CHANGED_BY"] = Environment.UserName;
                    jsonDataObject = dataObject.ToString();
                    jsonDataObject = Helpers.Common.SetJsonDataObjectDate(jsonDataObject, "ROW_CHANGED_DATE");
                    string dataType = idxResults[0].DataType;
                    try
                    {
                        _dbConn.UpdateDataObject(jsonDataObject, dataType);
                    }
                    catch (Exception ex)
                    {
                        string error = ex.ToString();
                        //logger.LogWarning($"Error updating data object");
                        throw;
                    }
                }
            }
            else
            {
                //logger.LogWarning("Cannot find data key during update");
            }
        }
Esempio n. 31
0
        private static void PredictCastE(AIHeroClient target)
        {
            if (target.Distance(player) > maxRangeE) return;

            var posInicial = target.Position;
            if (player.CountEnemiesInRange(E.Range) >= 2)
            {
                var firstTarget = ObjectManager.Get<AIHeroClient>().Where(a => a.IsEnemy).Where(a => !a.IsDead).Where(a => a.Distance(player) < maxRangeE).FirstOrDefault();
                var lasttTarget = ObjectManager.Get<AIHeroClient>().Where(a => a.IsEnemy).Where(a => !a.IsDead).Where(a => a.Distance(player) < E.Range).LastOrDefault();
                if (firstTarget != null && lasttTarget != null)
                {
                    CastE(firstTarget.Position, lasttTarget.Position);
                }
            }
            else if (target.Distance(player) < maxRangeE)
            {
                var maxPosition = target.Position.Extend(player, player.Distance(target) - rangeE);

                var pred = new PredictionResult(maxPosition.To3D(), target.Position, 70, null, Int32.MaxValue);

                if (pred.HitChance >= HitChance.Medium)
                    CastE(target.Position, maxPosition.Extend(player.Position.To2D(), 30).To3D());

            }
            else if (E.IsInRange(target))
            {
                posInicial = posInicial.Extend(target.Position, 100);

                var pred = E.GetPrediction(target);

                if (pred.HitChance == HitChance.High)
                {
                    CastE(posInicial, pred.UnitPosition);
                }
            }
        }
Esempio n. 32
0
        private static void PredictCastE(AIHeroClient target)
        {
            if(target.Distance(_Player)> maxRangeE) return;

            var posInicial = target.Position;
            if (E.IsInRange(target))
            {
                posInicial = posInicial.Extend(target.Position, 100).To3D();

                var pred = E.GetPrediction(target);

                if (pred.HitChance == HitChance.High)
                {
                    CastE(posInicial, pred.UnitPosition);
                }
            }
            else if(target.Distance(_Player) < maxRangeE)
            {
                var maxPosition = target.Position.Extend(_Player, _Player.Distance(target) - rangeE);

                var pred = new PredictionResult(maxPosition.To3D(), target.Position, 70, null, Int32.MaxValue);

                if(pred.HitChance >= HitChance.Medium)
                    CastE(target.Position, maxPosition.Extend(_Player.Position.To2D(), 30).To3D());

            }
        }
Esempio n. 33
0
        private static void Game_OnTick(EventArgs args)
        {
            if (Player.IsDead || Player.IsRecalling())
                return;

            if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo))
                Combo();
            if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Harass))
                Harass();

            KillSteal();
            Immobile();

            Target = TargetSelector.GetTarget(Config.SpellSetting.Q.MaxrangeQ, DamageType.Magical);
            TargetPred = Q.GetPrediction(Target);
        }