/// <summary>
 /// Gets predictions for a given utterance, in the form of intents and
 /// entities. The current maximum query size is 500 characters.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='appId'>
 /// The LUIS application ID (Guid).
 /// </param>
 /// <param name='query'>
 /// The utterance to predict.
 /// </param>
 /// <param name='timezoneOffset'>
 /// The timezone offset for the location of the request.
 /// </param>
 /// <param name='verbose'>
 /// If true, return all intents instead of just the top scoring intent.
 /// </param>
 /// <param name='staging'>
 /// Use the staging endpoint slot.
 /// </param>
 /// <param name='spellCheck'>
 /// Enable spell checking.
 /// </param>
 /// <param name='bingSpellCheckSubscriptionKey'>
 /// The subscription key to use when enabling Bing spell check
 /// </param>
 /// <param name='log'>
 /// Log query (default is true)
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <LuisResult> ResolveAsync(this IPrediction operations, System.Guid appId, string query, double?timezoneOffset = default(double?), bool?verbose = default(bool?), bool?staging = default(bool?), bool?spellCheck = default(bool?), string bingSpellCheckSubscriptionKey = default(string), bool?log = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ResolveWithHttpMessagesAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckSubscriptionKey, log, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Initializes client properties.
 /// </summary>
 private void Initialize()
 {
     Prediction            = new Prediction(this);
     BaseUri               = "https://{AzureRegion}.api.cognitive.microsoft.com/luis/v2.0/apps";
     SerializationSettings = new JsonSerializerSettings
     {
         Formatting            = Newtonsoft.Json.Formatting.Indented,
         DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
         NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new  List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
     DeserializationSettings = new JsonSerializerSettings
     {
         DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
         NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
     CustomInitialize();
 }
 /// <summary>
 /// Gets the published endpoint prediction for the given long query.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope'
 /// </param>
 /// <param name='appId'>
 /// Format - guid. The application ID.
 /// </param>
 /// <param name='q'>
 /// The query to predict.
 /// </param>
 /// <param name='timezoneOffset'>
 /// The timezone offset for the location of the request.
 /// </param>
 /// <param name='verbose'>
 /// If true will return all intents instead of just the topscoring intent.
 /// </param>
 /// <param name='spellCheck'>
 /// Enable spell checking.
 /// </param>
 /// <param name='staging'>
 /// Use staging endpoint.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <LuisResult> GetPredictionsFromEndpointViaPostAsync(this IPrediction operations, AzureRegions azureRegion, string appId, string q, double?timezoneOffset = default(double?), bool?verbose = default(bool?), bool?spellCheck = default(bool?), bool?staging = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetPredictionsFromEndpointViaPostWithHttpMessagesAsync(azureRegion, appId, q, timezoneOffset, verbose, spellCheck, staging, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #4
0
        void SetTextHint(TextSlice slice)
        {
            _predictionSlice = slice;

            if (slice.Text.Length == 0)
            {
                _ambiguousKeys.Clear();
            }
            var hints = _ambiguousKeys.Count > 0 ? _ambiguousKeys : null;

            _queuedPrediction = _predictor.CreatePrediction(slice.Text, slice.Start, slice.Length, _isAutoSpaceNeeded, hints);

            if (AppSettings.Instance.Prediction.PredictCharacters)
            {
                var characterSuggestions = _queuedPrediction.GetSuggestions(SuggestionType.Character);

                _environment.GazeProvider?.SetCharacterSuggestions(characterSuggestions);
            }

            foreach (var item in SuggestionItems)
            {
                item.IsEnabled = false;
            }

            foreach (var item in PhraseItems)
            {
                item.IsEnabled = false;
            }

            if (!_suggesterRunning)
            {
                _suggesterRunning = true;
                ThreadPool.QueueUserWorkItem(SuggesterThread);
            }
        }
 public static PredictionDTO FromDomain(IPrediction prediction)
 {
     if (prediction is Domain.Prediction.RainPrediction)
     {
         var rainPrediction = (RainPrediction)prediction;
         return(new RainPredictionDTO(prediction.Days, prediction.Type.ToString(), rainPrediction.DaysWithHeavyRain));
     }
     else
     {
         return(new PredictionDTO(prediction.Days, prediction.Type.ToString()));
     }
 }
Example #6
0
        protected override void OnActivate()
        {
            base.OnActivate();
            var factory  = this.Config.Hero.Factory;
            var itemMenu = this.Config.Hero.ItemMenu;

            this.DrawRazeRange = factory.Item("Draw Raze Indicators", true);
            this.DrawRazeRange.Item.Tooltip = "When enabled, will draw raze indicators.";
            this.PriRaze = factory.Item("Make sure razes hit", true);
            this.PriRaze.Item.Tooltip =
                "When enabled, will stop razes if not guaranteed hit, but skip some attacks in return.";
            this.UltiCombo = factory.Item("Ulti Key", new KeyBind(70));
            this.UltiCombo.Item.Tooltip   = "Will use ulti with available items on target.";
            this.EullessUlti              = factory.Item("Use ulti without eul too", false);
            this.EullessUlti.Item.Tooltip = "Will use ulti without euls too. Only activate with good ping/fps";
            this.DrawingX = factory.Item("Drawing X", new Slider(0, 0, 1800));
            this.DrawingY = factory.Item("Drawing Y", new Slider(0, 0, 1800));

            this.BkbToggle      = itemMenu.Item("Bkb Toggle", new KeyBind(71, KeyBindType.Toggle, true));
            this.EtherealHeroes = itemMenu.Item("Ethereal Blade",
                                                new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.VeilOfDiscordHeroes = itemMenu.Item("Veil Of Discord",
                                                     new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.HexHeroes = itemMenu.Item("Hex",
                                           new HeroToggler(new Dictionary <string, bool>(), true, false, false));
            this.OrchidBloodthornHeroes = itemMenu.Item("Orchid/Bloodthorn",
                                                        new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.OrchidBloodthornHeroes = itemMenu.Item("Orchid/Bloodthorn",
                                                        new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.AtosHeroes = itemMenu.Item("Rod of Atos",
                                            new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.HalberdHeroes = itemMenu.Item("Heaven's Halberd",
                                               new HeroToggler(new Dictionary <string, bool>(), true, false, true));
            this.UseBlink = itemMenu.Item("Use blink in combo?", true);

            this.Particle   = this.Context.Particle;
            this.Prediction = this.Context.Prediction;

            UpdateManager.Subscribe(OnUpdate, 20);

            Unit.OnModifierAdded            += this.OnRazeAdded;
            Unit.OnModifierRemoved          += this.OnRazeRemoved;
            this.Context.RenderManager.Draw += this.OnDraw;

            this.RazeShort  = UnitExtensions.GetAbilityById(this.Owner, AbilityId.nevermore_shadowraze1);
            this.RazeMedium = UnitExtensions.GetAbilityById(this.Owner, AbilityId.nevermore_shadowraze2);
            this.RazeLong   = UnitExtensions.GetAbilityById(this.Owner, AbilityId.nevermore_shadowraze3);
            this.Ulti       = UnitExtensions.GetAbilityById(this.Owner, AbilityId.nevermore_requiem);
        }
Example #7
0
        public static MemoryStream DrawBounds(ILogger <Worker> logger, Image image, IPrediction result, Camera camera)
        {
            using (Graphics g = Graphics.FromImage(image))
            {
                using (Font font = new Font("Arial", 30, FontStyle.Italic, GraphicsUnit.Pixel))
                    using (SolidBrush brush = new SolidBrush(Color.White))

                        foreach (IDetectedObject detection in result.Detections)
                        {
                            Item watch = camera.Watches?.FirstOrDefault(w => w.Label == detection.Label);
                            if (watch == null || detection.Confidence <= watch.Confidence)
                            {
                                continue;
                            }

                            if (camera.Draw == null)
                            {
                                continue;
                            }

                            using (Pen redPen = new Pen(Color.Red, camera.Draw.Width))

                                if (camera.Draw.Target)
                                {
                                    g.DrawRectangle(
                                        redPen,
                                        detection.XMin,
                                        detection.YMin,
                                        detection.XMax - detection.XMin,
                                        detection.YMax - detection.YMin);
                                }

                            if (camera.Draw.Confidence)
                            {
                                g.DrawString($"{detection.Label}:{detection.Confidence}",
                                             font,
                                             brush,
                                             new Point(detection.XMin, detection.YMin - camera.Draw.Width - 1));
                            }
                        }
            }
            MemoryStream ms = new MemoryStream();

            image.Save(ms, image.RawFormat);
            return(ms);
        }
Example #8
0
        public static List <MemoryStream> CropBounds(ILogger <Worker> logger, Image image, IPrediction result, Camera camera)
        {
            List <MemoryStream> streams = new List <MemoryStream>();

            foreach (IDetectedObject detection in result.Detections)
            {
                Item watch = camera.Watches?.FirstOrDefault(w => w.Label == detection.Label);
                if (watch == null || detection.Confidence <= watch.Confidence)
                {
                    continue;
                }

                Rectangle cropRect = new Rectangle(detection.XMin, detection.YMin, detection.XMax - detection.XMin, detection.YMax - detection.YMin);
                Bitmap    src      = image as Bitmap;
                using (Bitmap target = new Bitmap(cropRect.Width, cropRect.Height))
                {
                    using (Graphics g = Graphics.FromImage(target))
                    {
                        g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
                                    cropRect,
                                    GraphicsUnit.Pixel);
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        target.Save(ms, image.RawFormat);
                        streams.Add(ms);
                    }
                }
            }
            return(streams);
        }
Example #9
0
 protected PredictionAbility(Ability ability, IPrediction prediction = null)
     : base(ability)
 {
     this.Prediction = prediction ?? IoC.Get <IPrediction>();
 }
Example #10
0
 public static void Load()
 {
     Instance = new Samaritan();
     Prediction.AddPrediction(Name, Instance);
     Game.Print($"Enhanced.SDK | {Name} prediction loaded!", Color.OrangeRed);
 }
Example #11
0
 internal NoveltyWordPrediction(NoveltyWordPredictor predictor, IPrediction innerPrediction)
 {
     this.predictor       = predictor;
     this.innerPrediction = innerPrediction;
 }
Example #12
0
        public SamplePluginWithAsync([Import] IServiceContext context, [Import] ITargetSelectorManager selector, [Import] IPrediction prediction)
        {
            this.Selector   = selector;
            this.Prediction = prediction;

            // this.Ability = new PredictionAbility(context.Owner as Hero, AbilityId.pudge_meat_hook, prediction);
        }
Example #13
0
 private void TheFactoryCreates_For_(IPrediction prediction, string predictionText)
 {
     _predictionFactory.CreatePrediction(predictionText)
         .Returns(prediction);
 }
 public Task <LuisResult> ResolveAsync(IPrediction prediction, string appId, string query, double?timezoneOffset = null,
                                       bool?verbose = null, bool?staging = null, bool?spellCheck = null, string bingSpellCheckSubscriptionKey = null,
                                       bool?log     = null, CancellationToken cancellationToken = default)
 => prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck,
                            bingSpellCheckSubscriptionKey, log, cancellationToken);
 public void Add(IPrediction prediction)
 {
     _predictions.TryAdd(prediction.Id, prediction);
 }
Example #16
0
        IPrediction DisplaySuggestions(int seedLength, IEnumerable <IPredictionSuggestion> wordSuggestions, IEnumerable <IPredictionSuggestion> phraseSuggestions)
        {
            if (_queuedPrediction == null)
            {
                var isShifted = ShiftToggleState.IsChecked;

                var suggestions = new List <string>();

                var itemPosition = 0;
                foreach (var suggestion in wordSuggestions)
                {
                    if (itemPosition < SuggestionItems.Count)
                    {
                        var item        = SuggestionItems[itemPosition];
                        var shiftedText = ShiftText(isShifted, suggestion.Text);
                        item.Keytop     = shiftedText;
                        item.Visibility = Visibility.Visible;
                        item.IsEnabled  = true;
                        item.Suggestion = suggestion;

                        suggestions.Add(shiftedText);
                    }

                    itemPosition++;
                }

                while (itemPosition < SuggestionItems.Count)
                {
                    var item = SuggestionItems[itemPosition];
                    itemPosition++;

                    item.Visibility = Visibility.Collapsed;
                    item.Suggestion = null;
                }

                SuggestionsHelper.SetSuggestions(suggestions);

                if (suggestions.Count != 0 && _lastNarrationEventArgs != null &&
                    (seedLength != 0 ||
                     _environment.AppSettings.Prediction.PredictionNovelty == PredictionNovelty.FromScratch))
                {
                    var args = NarrationEventArgs.Create(_lastNarrationEventArgs, suggestions[0]);
                    _narrator.OnNarrationEvent(args);
                }

                itemPosition = 0;
                foreach (var phrase in phraseSuggestions)
                {
                    if (itemPosition < PhraseItems.Count)
                    {
                        var item = PhraseItems[itemPosition];
                        item.Keytop     = phrase.Text;
                        item.Visibility = Visibility.Visible;
                        item.IsEnabled  = true;
                        item.Suggestion = phrase;
                    }

                    itemPosition++;
                }

                while (itemPosition < PhraseItems.Count)
                {
                    var item = PhraseItems[itemPosition];
                    itemPosition++;

                    item.Visibility = Visibility.Collapsed;
                    item.Suggestion = null;
                }
            }

            var prediction = _queuedPrediction;

            _queuedPrediction = null;

            _suggesterRunning = prediction != null;
            return(prediction);
        }
Example #17
0
        void SuggesterThread(object state)
        {
            Thread.Sleep(100);
            var prediction = _environment.Dispatcher.Invoke(() => { var r = _queuedPrediction; _queuedPrediction = null; return(r); });

            do
            {
                var seedLength = _predictionSlice.Text.ReverseWordLength(_predictionSlice.Start);

                var wordSuggestions         = prediction.GetSuggestions(SuggestionType.Word);
                var wordSuggestionsUncached = new List <IPredictionSuggestion>(wordSuggestions);

                var phraseSuggestions         = prediction.GetSuggestions(SuggestionType.Phrase);
                var phraseSuggestionsUncached = new List <IPredictionSuggestion>(phraseSuggestions);

                prediction = _environment.Dispatcher.Invoke(() => DisplaySuggestions(seedLength, wordSuggestionsUncached, phraseSuggestionsUncached));
            }while (prediction != null);
        }
Example #18
0
 /// <summary>
 /// Resets the implementation.
 /// </summary>
 public static void ResetImplementation()
 {
     Implementation = new PredictionImpl();
 }
Example #19
0
        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            _stopwatch.Start();
            try
            {
                _logger.LogInformation($"OnChange event start: {e.FullPath} {DateTime.Now}");
                try
                {
                    Camera camera = null;
                    try
                    {
                        camera = FindCamera(e);
                    }
                    catch (ArgumentOutOfRangeException exp)
                    {
                        _logger.LogError(exp.Message);
                        return;
                    }

                    Image image = null;
                    try
                    {
                        _logger.LogDebug($"Loading image for {e.FullPath}");
                        image = _fileAccessRetryPolicy.Execute <Image>(() => { return(Image.FromFile(e.FullPath)); });
                    }
                    catch (FileLoadException fe)
                    {
                        _logger.LogError($"Cannot load from file {fe.FileName}");
                    }
                    catch (OutOfMemoryException oe)
                    {
                        _logger.LogError($"An out of memory exception was thrown: {oe.Message}");
                    }

                    using (image)
                    {
                        _logger.LogInformation($"Checking file {e.FullPath}.");

                        IPrediction result = null;
                        try
                        {
                            result = DetectObjectAsync(image, e.FullPath).Result;
                            if (result.Detections != null)
                            {
                                foreach (var d in result.Detections)
                                {
                                    _logger.LogInformation($"Found item: {d.Label}, confidence: {d.Confidence} at x:{d.XMin} y:{d.YMin} xmax:{d.XMax} ymax:{d.YMax}");
                                }
                            }
                        }
                        catch
                        {
                            _logger.LogError($"Cannot connect to object detector.");
                            return;
                        }

                        bool foundTarget = DetectTarget(camera, result.Detections);



                        if ((result.Success && foundTarget) || (result.Detections.Count() > 0 && _publishFalseDetections))
                        {
                            _logger.LogInformation($"{result.Detections.Count()} target(s) found in {e.FullPath}.");
                            result.FileName = e.Name;

                            string topic = foundTarget ? e.Name : falseDetectionTopic;
                            if (camera.Clip)
                            {
                                List <MemoryStream> streams = ImageHelper.CropBounds(_logger, image, result, camera);
                                foreach (MemoryStream ms in streams)
                                {
                                    using (ms)
                                    {
                                        result.Base64Image = Convert.ToBase64String(ms.ToArray());
                                        PublishAsync(result, topic, CancellationToken.None).Wait();
                                    }
                                }
                            }
                            else
                            {
                                using (MemoryStream ms = ImageHelper.DrawBounds(_logger, image, result, camera))
                                {
                                    result.Base64Image = Convert.ToBase64String(ms.ToArray());
                                    PublishAsync(result, topic, CancellationToken.None).Wait();
                                }
                            }
                        }
                        else
                        {
                            _logger.LogInformation($"0 targets found in {e.FullPath}.");
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    _logger.LogError($"Unable to connect to IDetectObjects:{typeof(IDetectObjects)}:{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"{ex.Message}");
            }
            finally
            {
                _stopwatch.Stop();
                _logger.LogInformation($"OnChange event end: {e.FullPath} {DateTime.Now}, elapsed time:{_stopwatch.Elapsed.TotalSeconds}");
                _logger.LogInformation("_____________________________________");
                _stopwatch.Reset();
            }
        }
Example #20
0
 private void APrediction_IsAddedToTheRepository(IPrediction prediction)
 {
     _predictionRepository.Received().Add(prediction);
 }
Example #21
0
 private async Task <MqttClientPublishResult> PublishAsync(IPrediction prediction, string fileName, CancellationToken token)
 {
     return(await _httpRetryPolicy.ExecuteAsync(() => _publisher.PublishAsync(prediction, fileName, token))
            .ConfigureAwait(false));
 }
Example #22
0
 public Ember([Import] IServiceContext context, [Import] ITargetSelectorManager selector, [Import] IPrediction prediction)
 {
     Me        = context.Owner as Hero;
     Selector  = selector;
     Remnant   = new PredictionAbility(Me, AbilityId.ember_spirit_fire_remnant, prediction);
     Fist      = Me.GetAbilityById(AbilityId.ember_spirit_sleight_of_fist);
     Activator = Me.GetAbilityById(AbilityId.ember_spirit_activate_fire_remnant);
     Chains    = Me.GetAbilityById(AbilityId.ember_spirit_searing_chains);
 }
 public PredictionsController(IDatabaseConnection databaseConnection, ILogger logger, IPrediction prediction, IOpenPredictionRepository openPredictionRepository)
 {
     Logger     = logger;
     Prediction = prediction;
     OpenPredictionRepository = openPredictionRepository;
 }