Exemplo n.º 1
0
 /// <summary>
 /// 加载汉语词典
 /// </summary>
 /// <param name="dicPath"></param>
 private void LoadDictionary(string dicPath)
 {
     string[] lines = File.ReadAllLines(dicPath);
     foreach (string line in lines)
     {
         string[] text = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
         if (!_dictionary.ContainsKey(text[0]) && text.Length > 0)
         {
             string[] explanations = text[1].Split(new[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries);
             Explain  explain      = new Explain();
             foreach (string explanation in explanations)
             {
                 if (explanation.StartsWith("[似]"))
                 {
                     explain.Thesaurus.Add(explanation.Replace("[似]", ""));
                 }
                 else if (explanation.StartsWith("[反]"))
                 {
                     explain.Antonym.Add(explanation.Replace("[反]", ""));
                 }
                 else
                 {
                     explain.Information.Add(explanation);
                 }
             }
             _dictionary.Add(text[0], explain);
         }
     }
 }
    private TimelineLiveElement getBaseDiff(LiveElementBase curr)
    {
        var diff = new TimelineLiveElement()
        {
            id = curr.id
        };

        var diffExplains = new List <Explain>();

        foreach (var explain in curr.explain)
        {
            var diffExplain = new Explain()
            {
                fixture = explain.fixture
            };
            diff.explain.Add(diffExplain);
            var diffStats = new List <ExplainElement>();
            foreach (var stat in explain.stats)
            {
                if (stat.points != 0 || stat.value != 0)
                {
                    diffStats.Add(stat);
                }
            }
            if (diffStats.Count > 0)
            {
                diffExplain.stats = diffStats;
            }
        }
        diff.CalcScore();
        var anyStats = diff.explain.Any(ex => ex.stats.Count > 0);

        return(anyStats ? diff : null);
    }
Exemplo n.º 3
0
 /// <summary>
 /// 修改说明信息
 /// </summary>
 /// <param name="explain"></param>
 /// <returns></returns>
 public int UpdExplain(Explain explain)
 {
     using (SqlSugarClient sqlsc = Educationcontext.GetClient())
     {
         var result = sqlsc.Updateable(explain).ExecuteCommand();
         return(result);
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// 添加说明信息
 /// </summary>
 /// <param name="explain"></param>
 /// <returns></returns>
 public long AddExplain(Explain explain)
 {
     using (SqlSugarClient sqlsc = Educationcontext.GetClient())
     {
         var result = sqlsc.Insertable(explain).ExecuteReturnIdentity();
         return(result);
     }
 }
Exemplo n.º 5
0
 public Explain(Explain other)
 {
     fixture = other.fixture;
     stats   = new List <ExplainElement>();
     foreach (var otherStat in other.stats)
     {
         stats.Add(new ExplainElement(otherStat));
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// 获取一个词的解释
 /// </summary>
 /// <param name="word">词语</param>
 /// <returns></returns>
 public string GetWordExplain(string word)
 {
     if (_dictionary.ContainsKey(word))
     {
         Explain explain = (Explain)_dictionary[word];
         return(string.Join("\n", explain.Information));
     }
     return(string.Empty);
 }
    public int calculateFootballerScore(Explain explain)
    {
        int score = 0;

        foreach (var explainElement in explain.stats)
        {
            score += explainElement.points;
        }
        return(score);
    }
Exemplo n.º 8
0
        public DictUnit(string unit)
        {
            string[] content = unit.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            word = content[0];

            for (int i = 1; i < content.Length; i++)
            {
                var exp = new Explain(content[i]);
                exps.Add(exp);
            }
        }
Exemplo n.º 9
0
 public static void ExplainBegin(Vdbe vdbe)
 {
     if (vdbe != null)
     {
         C._benignalloc_begin();
         Explain p = new Explain();
         if (p)
         {
             p.Vdbe       = vdbe;
             vdbe.Explain = p;
             Text.StringBuilder.Init(p.Str, p.ZBase, sizeof(p.ZBase), MAX_LENGTH);
             p.Str.UseMalloc = 2;
         }
         else
         {
             C._benignalloc_end();
         }
     }
 }
Exemplo n.º 10
0
        private void AddressList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (AddressList.SelectedIndex <= 0)
            {
                J_0.Text = R._("種類");
                Explain.Show();
                return;
            }
            uint typeID = GetTypeID();

            if (typeID <= 1)
            {
                J_0.Text = R._("ユニット");
            }
            else
            {
                J_0.Text = R._("クラス");
            }
            Explain.Hide();
        }
Exemplo n.º 11
0
        public List <Explain> getExplainList()
        {
            List <Explain> list    = new List <Explain>();
            StringBuilder  builder = new StringBuilder();

            builder.AppendFormat(OrderSqls.SELECT_EXPLAINLIST);
            string    sql = builder.ToString();
            DataTable dt  = DatabaseOperationWeb.ExecuteSelectDS(sql, "T").Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Explain explain = new Explain
                    {
                        explainUrl = dr["page_url"].ToString(),
                        explainImg = dr["page_img"].ToString()
                    };
                    list.Add(explain);
                }
            }

            return(list);
        }
 private ExplainElement GetCS(Explain fixtureExplain)
 {
     return(fixtureExplain.stats.FirstOrDefault(e => e.identifier.Equals("clean_sheets")));
 }
Exemplo n.º 13
0
        static async Task Main(string[] args)
        {
            bool          collectAuthors  = false;
            string        path            = null;
            SearchOptions options         = new SearchOptions();
            ISearchRange  range           = null;
            ActionType    requestedAction = ActionType.List;

            void SetBranchRange(string baseBranch, string branch)
            {
                if (range != null && !(range is BranchSearchRange))
                {
                    Errors.Die("Can not mix hash and branch ranges");
                }
                BranchSearchRange current = range != null ? (BranchSearchRange)range : new BranchSearchRange();

                if (baseBranch != null)
                {
                    current.Base = baseBranch;
                }
                if (branch != null)
                {
                    current.Branch = branch;
                }
                range = current;
            }

            void SetHashRange(string oldest, string newest)
            {
                if (range != null && !(range is HashSearchRange))
                {
                    Errors.Die("Can not mix hash and branch ranges");
                }
                HashSearchRange current = range != null ? (HashSearchRange)range : new HashSearchRange();

                if (oldest != null)
                {
                    current.Oldest = oldest;
                }
                if (newest != null)
                {
                    current.Newest = newest;
                }
                range = current;
            }

            OptionSet os = new OptionSet()
            {
                { "h|?|help", "Displays the help", v => requestedAction = ActionType.Help },
                { "verbose", "Print more details", v => Explain.Enabled = true },
                { "explain-commit=", "Parse a single commit and explain.", v => {
                      requestedAction = ActionType.ExplainCommit;
                      range           = new SingleHashSearchRange {
                          Hash = v
                      };
                  } },
                { "oldest=", "Starting hash to consider (hash range mode)", s => SetHashRange(s, null) },
                { "newest=", "Ending hash to consider (hash range mode)", e => SetHashRange(null, e) },
                { "base=", "Starting base to consider (branch/base mode)", b => SetBranchRange(b, null) },
                { "branch=", "Ending branch to consider (branch/base mode)", b => SetBranchRange(null, b) },

                { "explain", "Explain why each commit is considered a bug", v => Explain.Enabled = true },
                { "github-pat=", "Sets the PAT required to access github issues", v => options.GithubPAT = v },
                { "github-pat-file=", "Sets a file to read to use for github-path", v => options.GithubPAT = File.ReadLines(v).First() },
                { "github=", "Project to search issues of, such as xamarin/xamarin-macios. Must be '/' seperated", v => {
                      options.GithubLocation = v;
                  } },
                { "collect-authors", "Generate a list of unique authors to commits listed", v => collectAuthors = true },
                { "ignore=", "Commit hashes to ignore", v => options.CommitsToIgnore.Add(v) },
                new ResponseFileSource(),
            };

            try {
                IList <string> unprocessed = os.Parse(args);
                if (requestedAction == ActionType.Help || unprocessed.Count != 1)
                {
                    ShowHelp(os);
                    return;
                }
                path = unprocessed[0];
            }
            catch (Exception e) {
                Console.Error.WriteLine("Could not parse the command line arguments: {0}", e.Message);
                return;
            }

            if (String.IsNullOrEmpty(options.GithubLocation) || !options.GithubLocation.Contains("/"))
            {
                Errors.Die("--github formatted incorrectly");
            }

            if (!RepositoryValidator.ValidateGitHashes(path, range))
            {
                Environment.Exit(-1);
            }

            if (String.IsNullOrEmpty(options.GithubPAT))
            {
                Errors.Die("Unable to read GitHub PAT token");
            }

            Explain.Print("Finding Commits in Range");
            Explain.Indent();
            var commits = RangeFinder.Find(path, options, range).ToList();

            Explain.Print($"Found: {commits.Count}");
            Explain.Deindent();

            Explain.Print("Finding Pull Requests");
            Explain.Indent();
            var finder = new RequestFinder(options.GithubPAT);
            await finder.AssertLimits();

            var requestCollection = await finder.FindPullRequests(options.GithubLocation, commits);

            Explain.Print($"Found: {requestCollection.All.Count}");
            Explain.Deindent();

            var printer = new ConsolePrinter(requestCollection, options.GithubLocation);

            printer.Print(collectAuthors);
        }
Exemplo n.º 14
0
        public static async Task PerformFilterActions(DiscordClient client, DiscordMessage message, Piracystring trigger, FilterAction ignoreFlags = 0, string triggerContext = null, string infraction = null, string warningReason = null)
        {
            if (trigger == null)
            {
                return;
            }

            var severity         = ReportSeverity.Low;
            var completedActions = new List <FilterAction>();

            if (trigger.Actions.HasFlag(FilterAction.RemoveContent) && !ignoreFlags.HasFlag(FilterAction.RemoveContent))
            {
                try
                {
                    DeletedMessagesMonitor.RemovedByBotCache.Set(message.Id, true, DeletedMessagesMonitor.CacheRetainTime);
                    await message.Channel.DeleteMessageAsync(message, $"Removed according to filter '{trigger}'").ConfigureAwait(false);

                    completedActions.Add(FilterAction.RemoveContent);
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e);
                    severity = ReportSeverity.High;
                }
                try
                {
                    var author = client.GetMember(message.Author);
                    Config.Log.Debug($"Removed message from {author.GetMentionWithNickname()} in #{message.Channel.Name}: {message.Content}");
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e);
                }
            }

            if (trigger.Actions.HasFlag(FilterAction.IssueWarning) && !ignoreFlags.HasFlag(FilterAction.IssueWarning))
            {
                try
                {
                    await Warnings.AddAsync(client, message, message.Author.Id, message.Author.Username, client.CurrentUser, warningReason ?? "Mention of piracy", message.Content.Sanitize()).ConfigureAwait(false);

                    completedActions.Add(FilterAction.IssueWarning);
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, $"Couldn't issue warning in #{message.Channel.Name}");
                }
            }

            if (trigger.Actions.HasFlag(FilterAction.SendMessage) && !ignoreFlags.HasFlag(FilterAction.SendMessage))
            {
                try
                {
                    var msgContent = trigger.CustomMessage;
                    if (string.IsNullOrEmpty(msgContent))
                    {
                        var rules = await client.GetChannelAsync(Config.BotRulesChannelId).ConfigureAwait(false);

                        msgContent = $"Please follow the {rules.Mention} and do not discuss piracy on this server. Repeated offence may result in a ban.";
                    }
                    await message.Channel.SendMessageAsync($"{message.Author.Mention} {msgContent}").ConfigureAwait(false);

                    completedActions.Add(FilterAction.SendMessage);
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, $"Failed to send message in #{message.Channel.Name}");
                }
            }

            if (trigger.Actions.HasFlag(FilterAction.ShowExplain) && !ignoreFlags.HasFlag(FilterAction.ShowExplain))
            {
                var result = await Explain.LookupTerm(trigger.ExplainTerm).ConfigureAwait(false);

                await Explain.SendExplanation(result, trigger.ExplainTerm, message).ConfigureAwait(false);
            }

            var actionList = "";

            foreach (FilterAction fa in Enum.GetValues(typeof(FilterAction)))
            {
                if (trigger.Actions.HasFlag(fa) && !ignoreFlags.HasFlag(fa))
                {
                    actionList += (completedActions.Contains(fa) ? "✅" : "❌") + " " + fa + ' ';
                }
            }

            try
            {
                if (!trigger.Actions.HasFlag(FilterAction.MuteModQueue) && !ignoreFlags.HasFlag(FilterAction.MuteModQueue))
                {
                    await client.ReportAsync(infraction ?? "🤬 Content filter hit", message, trigger.String, triggerContext ?? message.Content, severity, actionList).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Config.Log.Error(e, "Failed to report content filter hit");
            }
        }
Exemplo n.º 15
0
	static int EndsWithNL(Explain p)
	{
		return (p != null && p.Str.zText && p.Str.nChar && p.Str.zText[p.Str.nChar-1]=='\n');
	}
    private void AddPotential(TimelineLiveElement current, Fixture fixture, Explain explain)
    {
        var fixtureMinutes = GetEstimatedFixtureMinutes(fixture);
        var minutesExplain = GetMinutes(explain);
        var bonusExplain   = GetBonus(explain);
        var element        = GetElement(current.id);

        if (minutesExplain == null)
        {
            explain.stats.Add(new ExplainElement()
            {
                identifier = "minutes",
                value      = 0,
                points     = 0
            });
        }

        // Add minutes (assume > 60min if it is still possible)
        if (minutesExplain.value > 0 && minutesExplain.value < 60)
        {
            var maxMinutes = (90 - fixtureMinutes) + minutesExplain.value;
            if (maxMinutes > 60)
            {
                minutesExplain.value  = 61;
                minutesExplain.points = 2;
            }
        }
        else if (minutesExplain.value == 0)
        {
            // No minutes yet
            if (fixture.started && !fixture.finished_provisional)
            {
                // Fixture is on, how many can we get?
                var maxMinutes = (90 - fixtureMinutes) + minutesExplain.value;
                minutesExplain.value  = (int)Math.Round(maxMinutes);
                minutesExplain.points = maxMinutes >= 60 ? 2 : 1;
            }
            else if (!fixture.started)
            {
                // Fixture hasn't started, assume start
                minutesExplain.value  = 90;
                minutesExplain.points = 2;
            }
        }

        // Goalkeepers and defenders get CS, if playing and eligible
        if (IsMidGkOrDef(element))
        {
            var csExplain = GetCS(explain);
            if (csExplain == null)
            {
                if (!HasOtherTeamScored(element, fixture))
                {
                    // Player has no CS and is playing...
                    var maxMinutes = 93.0 - fixtureMinutes + minutesExplain.value;
                    if (maxMinutes >= 60.0)
                    {
                        explain.stats.Add(new ExplainElement()
                        {
                            identifier = "clean_sheets",
                            value      = 1,
                            points     = element.element_type == 3 ? 1 : 4
                        });
                    }
                }
                else
                {
                    explain.stats.Add(new ExplainElement()
                    {
                        identifier = "clean_sheets",
                        value      = 0,
                        points     = 0
                    });
                }
            }
        }

        // Get any potential BPS
        if (bonusExplain == null)
        {
            // Fixture has started, and not completely finished?
            if (fixture.started && !fixture.finished)
            {
                var rank   = GetBpsRankInFixture(element, fixture);
                var points = 0;
                if (rank == 1)
                {
                    points = 3;
                }
                else if (rank == 2)
                {
                    points = 2;
                }
                else if (rank == 3)
                {
                    points = 1;
                }
                if (points > 0)
                {
                    explain.stats.Add(new ExplainElement()
                    {
                        identifier = "bonus",
                        value      = points,
                        points     = points
                    });
                }
            }
        }

        var currentScore = new ScoreCalculator().calculateFootballerScore(explain);
        var avg          = GetAverage(element);

        // If fixture has started, scale the average based on minutes played is player is in
        if (fixtureMinutes > 1.0e-6 && minutesExplain != null)
        {
            avg.points = (int)Math.Round(avg.points * (1.0 - fixtureMinutes / 90.0));
            avg.value  = 0;
        }

        // Only use average if average is > than the current + potential CS. If using average, only use the difference between avg and current
        if (avg.points > currentScore)
        {
            // If fixture hasn't started, use the average
            avg.points = avg.points - currentScore;
            explain.stats.Add(avg);
        }
    }
        /// <summary>
        /// Explain query
        /// </summary>
        /// <exception cref="Rakam.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="explain"></param>
        /// <returns>Task of ResponseQuery</returns>
        public async System.Threading.Tasks.Task <ResponseQuery> ExplainAsync(Explain explain)
        {
            ApiResponse <ResponseQuery> localVarResponse = await ExplainAsyncWithHttpInfo(explain);

            return(localVarResponse.Data);
        }
Exemplo n.º 18
0
        public int Create(Explain explain)
        {
            var result = WebApiHelper.GetApiResult("post", "explain", "Addexplain", explain);

            return(int.Parse(result));
        }
Exemplo n.º 19
0
 static int EndsWithNL(Explain p)
 {
     return(p != null && p.Str.zText && p.Str.nChar && p.Str.zText[p.Str.nChar - 1] == '\n');
 }
Exemplo n.º 20
0
        public static async Task OnError(CommandErrorEventArgs e)
        {
            if (e.Context.User.IsBotSafeCheck())
            {
                return;
            }

            if (!(e.Exception is CommandNotFoundException cnfe))
            {
                Config.Log.Error(e.Exception);
                return;
            }

            if (string.IsNullOrEmpty(cnfe.CommandName))
            {
                return;
            }

            if (e.Context.Prefix != Config.CommandPrefix &&
                e.Context.Prefix != Config.AutoRemoveCommandPrefix &&
                (e.Context.Message.Content?.EndsWith("?") ?? false) &&
                e.Context.CommandsNext.RegisteredCommands.TryGetValue("8ball", out var cmd))
            {
                var updatedContext = e.Context.CommandsNext.CreateContext(
                    e.Context.Message,
                    e.Context.Prefix,
                    cmd,
                    e.Context.Message.Content.Substring(e.Context.Prefix.Length).Trim()
                    );
                try { await cmd.ExecuteAsync(updatedContext).ConfigureAwait(false); } catch { }
                return;
            }

            if (cnfe.CommandName.Length < 3)
            {
                return;
            }

#if !DEBUG
            if (e.Context.User.IsSmartlisted(e.Context.Client, e.Context.Guild))
            {
                return;
            }
#endif

            var pos = e.Context.Message?.Content?.IndexOf(cnfe.CommandName) ?? -1;
            if (pos < 0)
            {
                return;
            }

            var gameTitle = e.Context.Message.Content.Substring(pos).TrimEager().Trim(40);
            if (string.IsNullOrEmpty(gameTitle) || char.IsPunctuation(gameTitle[0]))
            {
                return;
            }

            var term = gameTitle.ToLowerInvariant();
            var(explanation, fuzzyMatch, score) = await Explain.LookupTerm(term).ConfigureAwait(false);

            if (score > 0.5 && explanation != null)
            {
                if (!string.IsNullOrEmpty(fuzzyMatch))
                {
                    var fuzzyNotice = $"Showing explanation for `{fuzzyMatch}`:";
#if DEBUG
                    fuzzyNotice = $"Showing explanation for `{fuzzyMatch}` ({score:0.######}):";
#endif
                    await e.Context.RespondAsync(fuzzyNotice).ConfigureAwait(false);
                }
                StatsStorage.ExplainStatCache.TryGetValue(explanation.Keyword, out int stat);
                StatsStorage.ExplainStatCache.Set(explanation.Keyword, ++stat, StatsStorage.CacheTime);
                await e.Context.Channel.SendMessageAsync(explanation.Text, explanation.Attachment, explanation.AttachmentFilename).ConfigureAwait(false);

                return;
            }

            gameTitle = CompatList.FixGameTitleSearch(gameTitle);
            var productCodes = ProductCodeLookup.GetProductIds(gameTitle);
            if (productCodes.Any())
            {
                await ProductCodeLookup.LookupAndPostProductCodeEmbedAsync(e.Context.Client, e.Context.Message, productCodes).ConfigureAwait(false);

                return;
            }

            var(productCode, titleInfo) = await IsTheGamePlayableHandler.LookupGameAsync(e.Context.Channel, e.Context.Message, gameTitle).ConfigureAwait(false);

            if (titleInfo != null)
            {
                var thumbUrl = await e.Context.Client.GetThumbnailUrlAsync(productCode).ConfigureAwait(false);

                var embed = titleInfo.AsEmbed(productCode, thumbnailUrl: thumbUrl);
                await ProductCodeLookup.FixAfrikaAsync(e.Context.Client, e.Context.Message, embed).ConfigureAwait(false);

                await e.Context.Channel.SendMessageAsync(embed : embed).ConfigureAwait(false);

                return;
            }

            var ch = await e.Context.GetChannelForSpamAsync().ConfigureAwait(false);

            await ch.SendMessageAsync(
                $"I am not sure what you wanted me to do, please use one of the following commands:\n" +
                $"`{Config.CommandPrefix}c {term.Sanitize(replaceBackTicks: true)}` to check the game status\n" +
                $"`{Config.CommandPrefix}explain list` to look at the list of available explanations\n" +
                $"`{Config.CommandPrefix}help` to look at available bot commands\n"
                ).ConfigureAwait(false);
        }
    private TimelineLiveElement Compare(LiveElementBase prev, LiveElementBase curr)
    {
        var diff = new TimelineLiveElement()
        {
            id = curr.id
        };

        for (var i = 0; i < curr.explain.Count; i++)
        {
            var allExplainIdentifiers = new HashSet <string>(curr.explain[i].stats.Select(s => s.identifier).ToHashSet());
            if (prev != null && prev.explain != null && prev.explain.Count > i)
            {
                foreach (var stat in prev.explain[i].stats)
                {
                    allExplainIdentifiers.Add(stat.identifier);
                }
            }

            var currFixtureExplain = curr.explain[i];
            var prevFixtureExplain = prev != null && prev.explain != null && prev.explain.Count > i ? prev.explain[i] : null;
            var diffExplain        = new Explain()
            {
                fixture = currFixtureExplain.fixture,
                stats   = new List <ExplainElement>()
            };
            diff.explain.Add(diffExplain);

            foreach (var explainIdentifier in allExplainIdentifiers)
            {
                var currStat = currFixtureExplain.stats.FirstOrDefault(e => e.identifier.Equals(explainIdentifier));
                var prevStat = prevFixtureExplain != null?prevFixtureExplain.stats.FirstOrDefault(s => s.identifier.Equals(explainIdentifier)) : null;

                if (prevStat == null)
                {
                    prevStat = new ExplainElement()
                    {
                        identifier = explainIdentifier
                    };
                }
                if (currStat == null)
                {
                    currStat = new ExplainElement()
                    {
                        identifier = explainIdentifier
                    };
                }
                var statDiff = GetExplainDiff(currStat, prevStat);
                if (statDiff != null)
                {
                    diffExplain.stats.Add(statDiff);
                }
            }
        }

        var saveDiff = diff.explain.Any(ex => ex.stats.Count > 0);

        if (saveDiff)
        {
            diff.CalcScore();
            return(diff);
        }

        return(null);
    }
 private ExplainElement GetBonus(Explain fixtureExplain)
 {
     return(fixtureExplain.stats.FirstOrDefault(e => e.identifier.Equals("bonus")));
 }
Exemplo n.º 23
0
 public Domain.Task Replace(Explain _explain, Domain.Task _task) => new Domain.Task(_task.ID, _task.Title, _explain, _task.Status);
Exemplo n.º 24
0
 public int UpdExplain(Explain explain)
 {
     return(_explainsIServices.UpdExplain(explain));
 }
Exemplo n.º 25
0
        public int Edit(Explain explain)
        {
            var result = WebApiHelper.GetApiResult("post", "explain", "UpdExplain", explain);

            return(int.Parse(result));
        }
Exemplo n.º 26
0
 public long Addexplain(Explain explain)
 {
     return(_explainsIServices.AddExplain(explain));
 }
Exemplo n.º 27
0
 /// <summary>
 /// 加载汉语词典
 /// </summary>
 /// <param name="dicPath"></param>
 private void LoadDictionary(string dicPath)
 {
     string[] lines = File.ReadAllLines(dicPath);
     foreach (string line in lines)
     {
         string[] text = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
         if (!_dictionary.ContainsKey(text[0]) && text.Length > 0)
         {
             string[] explanations = text[1].Split(new[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries);
             Explain explain = new Explain();
             foreach (string explanation in explanations)
             {
                 if (explanation.StartsWith("[似]"))
                 {
                     explain.Thesaurus.Add(explanation.Replace("[似]", ""));
                 }
                 else if (explanation.StartsWith("[反]"))
                 {
                     explain.Antonym.Add(explanation.Replace("[反]", ""));
                 }
                 else
                 {
                     explain.Information.Add(explanation);
                 }
             }
             _dictionary.Add(text[0], explain);
         }
     }
 }
        /// <summary>
        /// Explain query
        /// </summary>
        /// <exception cref="Rakam.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="explain"></param>
        /// <returns>ResponseQuery</returns>
        public ResponseQuery Explain(Explain explain)
        {
            ApiResponse <ResponseQuery> localVarResponse = ExplainWithHttpInfo(explain);

            return(localVarResponse.Data);
        }
Exemplo n.º 29
0
	public static void ExplainBegin(Vdbe vdbe)
	{
		if (vdbe != null)
		{
			C._benignalloc_begin();
			Explain p = new Explain();
			if (p)
			{
				p.Vdbe = vdbe;
				vdbe.Explain = p;
				Text.StringBuilder.Init(p.Str, p.ZBase, sizeof(p.ZBase), MAX_LENGTH);
				p.Str.UseMalloc = 2;
			}
			else
				C._benignalloc_end();
		}
	}
        /// <summary>
        /// Explain query
        /// </summary>
        /// <exception cref="Rakam.Client.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="explain"></param>
        /// <returns>Task of ApiResponse (ResponseQuery)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <ResponseQuery> > ExplainAsyncWithHttpInfo(Explain explain)
        {
            // verify the required parameter 'explain' is set
            if (explain == null)
            {
                throw new ApiException(400, "Missing required parameter 'explain' when calling QueryApi->Explain");
            }

            var    localVarPath         = "/query/explain";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new Dictionary <String, String>();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (explain != null && explain.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(explain); // http body (model) parameter
            }
            else
            {
                localVarPostBody = explain; // byte array
            }

            // authentication (read_key) required
            if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("read_key")))
            {
                localVarHeaderParams["read_key"] = Configuration.GetApiKeyWithPrefix("read_key");
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("Explain", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <ResponseQuery>(localVarStatusCode,
                                                   localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                   (ResponseQuery)Configuration.ApiClient.Deserialize(localVarResponse, typeof(ResponseQuery))));
        }
 private void MakePrediction(TimelineLiveElement current, Fixture fixture, Explain explain)
 {
     AddPotential(current, fixture, explain);
 }