Exemplo n.º 1
0
        public async Task <Participant <Player> > AddPlayerToTournamentAsync(string tournamentId, Participant <Player> player)
        {
            var playerRef = new TournamentPlayer()
            {
                Player = new SanityReference <Player>()
                {
                    Ref       = player.Item.Id,
                    SanityKey = player.Item.Id,
                },
                Information  = player.Information.ToList(),
                ToornamentId = player.ToornamentId,
            };

            SanityTournament tournament = await Sanity.DocumentSet <SanityTournament>().GetAsync(tournamentId);

            if (tournament == null || tournament.SignupType == "team" || !tournament.RegistrationOpen)
            {
                return(null);
            }

            if (tournament.SoloPlayers == null)
            {
                tournament.SoloPlayers = new List <TournamentPlayer>();
            }

            if (tournament.SoloPlayers.Find(t => t.Player.Ref == player.Item.Id) != null)
            {
                return(null);
            }
            tournament.SoloPlayers.Add(playerRef);

            await Sanity.DocumentSet <SanityTournament>().Update(tournament).CommitAsync();

            return(player);
        }
Exemplo n.º 2
0
        public async Task <Organization> CreateOrganizationAsync(User requester, Organization organization)
        {
            List <SanityOrganization> organizations = await GetOrganizationsAsync();

            SanityOrganization existingOrganization = organizations.FirstOrDefault(o => o.Members.Find(m => m.Player.Ref == requester.Id && m.Role == "owner") != null);

            if (existingOrganization != null)
            {
                return(existingOrganization.ToOrganization());
            }

            if (string.IsNullOrEmpty(organization.Id))
            {
                organization.Id = Guid.NewGuid().ToString();
                var newOrg = new SanityOrganization()
                {
                    Name    = organization.Name,
                    Id      = organization.Id,
                    Members = new List <SanityMember>(),
                };

                newOrg.Members.Add(new SanityMember(requester, "owner"));

                await Sanity.DocumentSet <SanityOrganization>().Create(newOrg).CommitAsync();

                organizations.Add(newOrg);

                return(newOrg.ToOrganization());
            }
            return(organization);
        }
Exemplo n.º 3
0
 public static int RunCommand(
     string exe,
     string args,
     string stdoutPath, // must be null in this version
     string stderrPath, // may be null
     bool throwOnFailure = true,
     IEnumerable <KeyValuePair <string, string> > envirVariables = null)
 {
     Sanity.Requires(stdoutPath == null, "This reduced version of RunCommand() does not support stdout redirection");
     Logger.WriteLine($"executing command: {exe} {args}");
     using (TextWriter stderrWriter = stderrPath == null ? null : new StreamWriter(stderrPath, append: false, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))
     {
         AutoFlush = true
     })
         using (var process = CreateProcess(exe, args, envirVariables, isPipe: false, stderr: stderrWriter))
         {
             process.WaitForExit();
             if (throwOnFailure && process.ExitCode != 0)
             {
                 throw new IOException($"Exit code {process.ExitCode} was returned by external process: {exe} {args}");
             }
             else
             {
                 return(process.ExitCode);
             }
         }
 }
        private void ValidateSingleFile(string filePath)
        {
            var list = File.ReadAllLines(filePath);

            Sanity.Requires(list.Length % 2 == 0, "Line count is not even.");
            bool   trimLastInterval = false;
            double previousMax      = -0;

            for (int i = 0; i < list.Length; i += 2)
            {
                string s1 = list[i];
                string s2 = list[i + 1];
                try
                {
                    previousMax = ValidateSentencePair(s1, s2, i, list.Length, previousMax);
                }
                catch (CommonException e)
                {
                    Console.WriteLine(filePath + "\t" + e.Message);
                    if (e.HResult == 1)
                    {
                        trimLastInterval = true;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Extra error:\t{filePath}\t{e.Message}");
                }
            }
            if (trimLastInterval)
            {
                File.WriteAllLines(filePath, list.Take(list.Length - 2));
            }
        }
        private IEnumerable <CutAudioLine> CutAudios()
        {
            var list = File.ReadLines(Constants.TOTAL_MAPPING_PATH)
                       .Select(x => new TotalMappingLine(x));
            int externalIndex = 0;

            foreach (var l in list)
            {
                if (!File.Exists(l.DeliveredTextPath))
                {
                    continue;
                }
                var content = File.ReadLines(l.DeliveredTextPath)
                              .Select(x => LocalCommon.ExtractTransLine(x))
                              .ToArray();
                Sanity.Requires(content.Length % 2 == 0);
                for (int i = 0; i < content.Length; i += 2)
                {
                    CutAudioLine line = new CutAudioLine
                    {
                        SourceAudioPath = l.DeliveredAudioPath,
                        SourceTextPath  = l.DeliveredTextPath,
                        Dialect         = l.Dialect,
                        ExternalIndex   = externalIndex,
                        InternalIndex   = i / 2,
                        StartTime       = content[i].StartTime.ToString(),
                        EndTime         = content[i].EndTime.ToString(),
                        SG = content[i].Content,
                        HG = content[i + 1].Content
                    };
                    yield return(line);
                }
                externalIndex++;
            }
        }
Exemplo n.º 6
0
        protected virtual IDbCommand GetCommand(IDbConnection connection)
        {
            Sanity.Enforce <NullReferenceException>(Table != null, nameof(Table));

            ISqlDialect dialect = Database.Dialect;

            var arguments = new List <object>();
            var snippets  = new List <string>();

            foreach (var predicate in _predicates)
            {
                snippets.Add($"({predicate.Text})");
                arguments.AddRange(predicate.Arguments);
            }

            var where = snippets.Count > 0
                ? "WHERE " + string.Join(" AND ", snippets)
                : "";

            var table   = dialect.QuoteName(Table.Name);
            var columns = string.Join(", ", (
                                          from column in Table.Columns
                                          where ColumnsToFetch?.Contains(column) ?? true
                                          select dialect.QuoteName(column.Name)
                                          ));

            if (columns.Length == 0)
            {
                columns = "*";
            }

            var commandText = $"SELECT {columns} FROM {table} {where}";

            return(connection.CreateCommand(commandText, arguments.ToArray()));
        }
Exemplo n.º 7
0
        private static void SetConfig()
        {
            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(Arg.XmlConfigFilePath);
            XmlNode root = xDoc["Root"];

            TaskName = root.GetValue("", "TaskName");
            Sanity.Requires(root["Common"] != null, $"Missing Common node.");

            WorkFolder = Path.Combine(TMP, $"{Now.ToStringPathMiddle()}_{TaskName}");
            Directory.CreateDirectory(WorkFolder);

            var taskNode = root[TaskName];

            if (taskNode != null)
            {
                string taskConfigPath = Path.Combine(WorkFolder, "Config.xml");
                taskNode.Save(taskConfigPath);
                string cfgKey = $"config{TaskName.ToLower()}";
                Sanity.Requires(ConfigDict.ContainsKey(cfgKey), $"Config for {TaskName} doesn't exist, may because of name mismatch.");
                var type = ConfigDict[cfgKey].GetType();
                Cfg = (Config)Deserialize(taskConfigPath, type);
                if (Arg.PostSetFlag)
                {
                    Cfg.PostSetConfig(Arg);
                }
            }

            var    commonNode = root["Common"];
            string commonPath = Path.Combine(WorkFolder, "Common.xml");

            commonNode.Save(commonPath);
            LCommon = (LocalCommon)Deserialize(commonPath, typeof(LocalCommon));
        }
        private static IEnumerable <string> MergeIntervals(IEnumerable <TextGridInterval> sequence)
        {
            List <TextGridInterval> hgList = new List <TextGridInterval>();
            List <TextGridInterval> sgList = new List <TextGridInterval>();

            foreach (var interval in sequence)
            {
                string content = GetContent(interval);
                if (!string.IsNullOrEmpty(content) && GetRaw(content) != "<unknown/>")
                {
                    if (interval.Item == SG_TAG)
                    {
                        sgList.Add(interval);
                    }
                    else
                    {
                        hgList.Add(interval);
                    }
                }
            }
            Sanity.Requires(hgList.Count == sgList.Count, "Interval count mismatch.");
            for (int i = 0; i < sgList.Count; i++)
            {
                double diff1 = Math.Abs(double.Parse(sgList[i].XMin) - double.Parse(hgList[i].XMin));
                double diff2 = Math.Abs(double.Parse(sgList[i].XMax) - double.Parse(hgList[i].XMax));
                Sanity.Requires(diff1 <= DIFF_THRESHOLD && diff2 <= DIFF_THRESHOLD, "Time stamp mismatch.");
                foreach (string s in OutputInterval(sgList[i], hgList[i]))
                {
                    yield return(s);
                }
            }
        }
Exemplo n.º 9
0
        // MEMBERS
        public async Task <Organization> AddPlayerAsync(User requester, string organizationId, string id)
        {
            List <SanityOrganization> organizations = await GetOrganizationsAsync();

            Player player = (await GetPlayersAsync()).FirstOrDefault(p => p.Id == id || p.DiscordId == id);

            SanityOrganization organization = organizations.FirstOrDefault(o => o.Id == organizationId);

            if (organization == null)
            {
                throw new Exception("Organization not found");
            }

            SanityPendingMember pending = organization.Pending.FirstOrDefault(p => p.Player.Ref == player.Id);

            if (pending != null)
            {
                organization.Pending.Remove(pending);
            }

            organization.Members.Add(new SanityMember(player, "member"));

            await Sanity.DocumentSet <SanityOrganization>().Update(organization).CommitAsync();

            return(organization.ToOrganization());
        }
Exemplo n.º 10
0
 public static void SetUpForbiddenType <T>()
 {
     customWriters.Add(typeof(T), (ser, obj) =>
     {
         Sanity.BreakIfAttached();
         throw new ArgumentException("Cannot serialize type " + typeof(T));
     });
 }
Exemplo n.º 11
0
    void OnTriggerStay(Collider col)
    {
        Sanity sanity = GameObject.FindGameObjectWithTag("Player").GetComponent <Sanity> ();

        if (col.gameObject.tag == "Player")
        {
            sanity.calculateSanityRate();
        }
    }
Exemplo n.º 12
0
 private void AddToObjectStack(object obj)
 {
     objectStack.Add(obj);
     if (objectStack.Count >= 400 && !hasLoggedSuspiciousDepth)
     {
         hasLoggedSuspiciousDepth = true;
         Sanity.ShouldntHaveHappenedButTryToContinue(new Exception("BinSerSerializer stack is becoming very deep:" + string.Join(" -> ", objectStack.Select(x => x.GetType().FullName))));
     }
 }
Exemplo n.º 13
0
        public Task <List <TournamentInfo> > GetAllTournamentsAsync()
        {
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            return(Cache.GetOrCreateAsync("Sanity_Tournament_Info_" + lang, async(c) => {
                c.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);
                var tournaments = await Sanity.DocumentSet <SanityTournament>().Include(t => t.Camp).Where(t => !t.IsDraft() && t.Camp.Value.Active).ToListAsync();
                return tournaments?.Select(t => t.ToTournamentInfo(Sanity.HtmlBuilder)).ToList();
            }));
        }
Exemplo n.º 14
0
        public void ConvertToWave(string inputPath, string interMediaPath, string outputPath)
        {
            LocalCommon.SetAudioToWaveWithFfmpeg(inputPath.WrapPath(), interMediaPath.WrapPath());
            Wave w = new Wave();

            w.ShallowParse(interMediaPath);
            Sanity.Requires(w.SampleRate >= SampleRate, w.SampleRate.ToString());
            File.Delete(interMediaPath);
            LocalCommon.SetAudioWithFfmpeg(inputPath.WrapPath(), SampleRate, NumChannels, outputPath.WrapPath());
        }
 private IEnumerable <(string, string)> OfflinePathMatch(string offlineFolderPath, string sourceFolderPath)
 {
     foreach (string textGridPath in Directory.EnumerateFiles(offlineFolderPath, "*.textgrid"))
     {
         string wavePath       = textGridPath.Split('\\').Last().ToLower().Replace(".textgrid", ".wav");
         string sourceWavePath = Path.Combine(sourceFolderPath, wavePath);
         Sanity.Requires(File.Exists(sourceWavePath));
         yield return(textGridPath, sourceWavePath);
     }
 }
Exemplo n.º 16
0
        public Task <List <EventInfo> > GetAllEventsAsync()
        {
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            return(Cache.GetOrCreateAsync("Sanity_All_Events_" + lang, async(c) => {
                c.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);
                var events = await Sanity.DocumentSet <SanityEvent>().Where(e => !e.IsDraft()).ToListAsync();
                return events?.Select(t => t.ToEventInfo(Sanity.HtmlBuilder)).ToList();
            }));
        }
Exemplo n.º 17
0
    public stat Health, Sanity, Strength, Agility, Intelligence, Willpower, Perception, Charisma; // Stats that are accessed through other scripts. E.g. GetComponent<rpgStats>().health.Add(-2);

    private void Awake()                                                                          // All stat values set to their starting values.
    {
        Health.SetValue(StartHealth);
        Sanity.SetValue(StartSanity);
        Strength.SetValue(StartStrength);
        Agility.SetValue(StartAgility);
        Intelligence.SetValue(StartIntelligence);
        Willpower.SetValue(StartWillpower);
        Perception.SetValue(StartPerception);
        Charisma.SetValue(StartCharisma);
    }
        public (string Dialect, string SpeakerId, string AudioId) ExtractOscarId(string oscarId)
        {
            var match = OscarDdReg.Match(oscarId);

            Sanity.Requires(match.Success, $"Invalid Id.\t{oscarId}");
            string dialect   = match.Groups[1].Value;
            string speakerId = match.Groups[2].Value;
            string audioId   = match.Groups[3].Value;

            return(dialect, speakerId, audioId);
        }
Exemplo n.º 19
0
    void OnTriggerStay(Collider col)
    {
        //if inside the trigger radius, sanity increases
        if (col.gameObject.tag == "Player")
        {
            Player player = GameObject.FindGameObjectWithTag("Player").GetComponent <Player>();
            player.isDetected = true;

            Sanity sanity = GameObject.FindGameObjectWithTag("Player").GetComponent <Sanity> ();
            sanity.calculateSanityRate();
        }
    }
Exemplo n.º 20
0
        public Task <EventInfo> GetEventInfoAsync(string eventId)
        {
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            return(Cache.GetOrCreateAsync("Sanity_Event_Info_" + lang, async(c) =>
            {
                c.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);
                var result = await Sanity.DocumentSet <SanityEvent>().Where(e => e.Id == eventId || e.Slug.Current == eventId).FirstOrDefaultAsync();
                EventInfo eventI = result.ToEventInfo(Sanity.HtmlBuilder);
                return eventI;
            }));
        }
        public void MergeNewAnnontationData()
        {
            string offLinePath        = @"F:\WorkFolder\Transcripts\OfflineMapping.txt";
            string onlinePath         = @"F:\WorkFolder\Transcripts\OnlineMapping.txt";
            string overallMappingPath = @"F:\WorkFolder\Summary\20210222\Important\FullMapping.txt";
            string oldMappingPath     = @"F:\WorkFolder\Summary\20210222\Important\TransMapping.txt";
            string outputPath         = @"F:\WorkFolder\Summary\20210222\Important\TransMapping_New.txt";
            var    existingList       = File.ReadLines(oldMappingPath).Select(x => x.ToLower()).ToHashSet();
            var    dict = File.ReadLines(overallMappingPath)
                          .Select(x => new FullMappingLine(x))
                          .Select(x => new { x.OldPath, x.NewPath })
                          .Distinct()
                          .ToDictionary(x => x.OldPath.ToLower(), x => x.NewPath);

            var           list       = File.ReadLines(offLinePath).Concat(File.ReadLines(onlinePath));
            List <string> outputList = new List <string>();

            foreach (string s in list)
            {
                string textPath  = s.Split('\t')[1].ToLower();
                string audioPath = s.Split('\t')[2].ToLower();
                Sanity.Requires(File.Exists(textPath));
                Sanity.Requires(File.Exists(audioPath));
                if (!dict.ContainsKey(audioPath))
                {
                    continue;
                }
                string newAudioPath = dict[audioPath];
                string newTextPath  = newAudioPath.ToLower().Replace("300hrsrecordingnew", "300hrsannotationnew").Replace(".wav", ".txt");
                string newS         = $"{textPath}\t{audioPath}\t{newTextPath}\t{newAudioPath}";
                if (existingList.Contains(newS))
                {
                    continue;
                }
                string textFolder = GetFolder(newTextPath).Folder;
                Directory.CreateDirectory(textFolder);
                if (File.Exists(newTextPath))
                {
                    Console.WriteLine(textPath);
                }
                else if (!File.Exists(newAudioPath))
                {
                    Console.WriteLine(newAudioPath);
                }
                else
                {
                    //File.Copy(textPath, newTextPath);
                    outputList.Add(newS);
                }
            }
            File.WriteAllLines(outputPath, outputList);
        }
Exemplo n.º 22
0
    public override void Awake()
    {
        base.Awake();

        AddWayPoints();
        AddModels();
        DisableAllModels();
        SwitchModel();

        _cam   = Camera.main;
        player = GameObject.FindGameObjectWithTag("Player").GetComponent <Transform>();
        sanity = player.GetComponent <Sanity>();
    }
Exemplo n.º 23
0
        public Task <List <Game> > GetGamesAsync()
        {
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            return(Cache.GetOrCreateAsync("Sanity_Games_" + lang, async(c) =>
            {
                c.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);

                var result = await Sanity.DocumentSet <SanityGame>().ToListAsync();

                return result.Select(g => g.ToGame()).ToList();
            }));
        }
Exemplo n.º 24
0
        public async Task <Organization> AddPendingPlayerAsync(User requester, string organizationId, Player player)
        {
            SanityOrganization organization = (await GetOrganizationsAsync()).FirstOrDefault(o => o.Id == organizationId);

            if (organization != null && organization.Members != null && organization.Members.Find(m => m.Player.Ref == player.Id) == null)
            {
                organization.Pending.Add(new SanityPendingMember(player, "request"));

                await Sanity.DocumentSet <SanityOrganization>().Update(organization).CommitAsync();

                return(organization.ToOrganization());
            }
            throw new Exception();
        }
Exemplo n.º 25
0
        public void Load(XmlElement source)
        {
            Sanity.Enforce <ArgumentException>(
                source.LocalName == nameof(FetchRequest),
                $"Element must be named {nameof(FetchRequest)}");

            _predicates.Clear();
            foreach (XmlElement element in source.SelectNodes($"Predicates/{nameof(FetchPredicate)}"))
            {
                var predicate = new FetchPredicate();
                predicate.Load(element);
                _predicates.Add(predicate);
            }
        }
Exemplo n.º 26
0
    public override void Awake()
    {
        base.Awake();

        _passcards      = new List <string>();
        _escapePodParts = new List <EscapePodPart>();

        if (!feetAudioSource)
        {
            feetAudioSource = GetComponent <AudioSource>();
        }

        sanity = GetComponent <Sanity>();
    }
Exemplo n.º 27
0
    void Start()
    {
        hearts = healthContainer.GetComponentsInChildren<Image>();
        sanity = GetComponent<Sanity>();
        maxHearts = hearts.Length;
        sanityClock = sanityTickTime;
        playerAnimator = GameObject.Find("Player").GetComponent<Animator>();

        for (int i = maxHealth / heartValue; i < maxHearts; i++)
        {
            hearts[i].enabled = false;
        }
        UpdateHearts();
    }
        public IEnumerable <(string, string)> GetOfflineFiles(string folderPath)
        {
            string tgPath = Path.Combine(folderPath, "TextGrid");

            foreach (string taskFolderPath in Directory.EnumerateDirectories(tgPath))
            {
                string           taskName          = taskFolderPath.Split('\\').Last();
                string           sourceFolderPath  = "";
                HashSet <string> sourceFolderPaths = new HashSet <string>();
                if (NamePathDict.ContainsKey(taskName))
                {
                    sourceFolderPath = NamePathDict[taskName];
                }
                else if (Team1Reg.IsMatch(taskName))
                {
                    var match = Team1Reg.Match(taskName);
                    sourceFolderPath = Path.Combine(@"F:\WorkFolder\Input\300hrsRecordingContent", match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value);
                }
                else if (Team2Reg.IsMatch(taskName))
                {
                    var    match     = Team2Reg.Match(taskName);
                    string speakerId = match.Groups[1].Value;
                    sourceFolderPaths = SpeakerIdPathDict[speakerId];
                    if (sourceFolderPaths.Count == 1)
                    {
                        sourceFolderPath = sourceFolderPaths.Single();
                    }
                }
                else
                {
                    throw new CommonException();
                }
                if (sourceFolderPath != "")
                {
                    Sanity.Requires(Directory.Exists(sourceFolderPath));
                    foreach (var item in OfflinePathMatch(taskFolderPath, sourceFolderPath))
                    {
                        yield return(item);
                    }
                }
                else
                {
                    foreach (var item in OfflinePathMatch(taskFolderPath, sourceFolderPaths))
                    {
                        yield return(item);
                    }
                }
            }
        }
Exemplo n.º 29
0
        private static void RunFeature()
        {
            Sanity.Requires(FeatureDict.ContainsKey(TaskName.ToLower()), $"Feature {TaskName} doesn't exist.");
            if (!Arg.SkipConfirmFlag)
            {
                Console.WriteLine($"You're going to run the following feature:");
                Console.WriteLine(TaskName);
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
            }
            var feature = FeatureDict[TaskName.ToLower()];

            feature.WorkFolder = WorkFolder;
            feature.LoadAndRun(Cfg, LCommon);
        }
Exemplo n.º 30
0
        public DownloadClient(string clientId, string uriAddress, string downloadDir, HtmlParser parser)
        {
            ClientId = clientId;

            DownloadDir = downloadDir;
            Directory.CreateDirectory(DownloadDir);

            Parser = parser;

            Sanity.Requires(Common.ValidateUri(uriAddress), string.Format(GlobalMessages.URI_IS_INVALID, uriAddress));

            UriAddress = uriAddress;

            Parser.LoadHtmlStream(UriAddress);
        }
        public void Load(XmlElement source)
        {
            Sanity.Enforce <ArgumentException>(
                source.LocalName == nameof(FetchPredicate),
                $"Element must be named {nameof(FetchPredicate)}");

            Text = source.SelectSingleNode(nameof(Text)).InnerText;
            var arguments = new List <object>();

            foreach (XmlElement element in source.SelectNodes("Arguments/Value"))
            {
                arguments.Add(element.InnerText);
            }

            Arguments = arguments.ToArray();
        }