System.Collections.Generic.List.Clear()

Here are the examples of the csharp api System.Collections.Generic.List.Clear() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

18695 Examples 7

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            while (results.TryDequeue(out var del)) ;
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            //var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            //sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();
        }

19 View Source File : DataFilter.cs
License : MIT License
Project Creator : 2881099

public void Dispose() {
			_filters.Clear();
		}

19 View Source File : LaunchWindow.cs
License : MIT License
Project Creator : 1ZouLTReX1

void OnGUI()
    {
        scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

        var defaultGUIColor = GUI.color;
        var defaultGUIBackgrounColor = GUI.backgroundColor;

        EditorGUI.BeginChangeCheck();

        EditorGUILayout.BeginVertical();

        // Quick start buttons
        DrawLine();
        GUI.backgroundColor = Color.green;
        if (GUILayout.Button("Start Selected"))
        {
            for (var i = 0; i < data.entries.Count; i++)
            {
                var entry = data.entries[i];
                if (!entry.selected)
                    continue;
                StartEntry(data.entries[i]);
            }
        }
        GUI.backgroundColor = defaultGUIBackgrounColor;

        DrawLine();
        GUI.backgroundColor = Color.red;
        if (GUILayout.Button("Stop All"))
        {
            BuildUtils.StopAll();
        }
        GUI.backgroundColor = defaultGUIBackgrounColor;

        DrawLine();
        if (GUILayout.Button("Add Entry"))
        {
            data.entries.Add(new Entry());
        }
        DrawLine();
        GUILayout.Space(10.0f);
        
        // Draw entries
        for (int i = 0; i < data.entries.Count; i++)
        {
            GUILayout.Space(5.0f);
            var entry = data.entries[i];

            GUILayout.BeginHorizontal(GUILayout.ExpandHeight(false));
            {
                GUILayout.Space(5.0f);
                GUI.backgroundColor = entry.selected ? Color.green : defaultGUIBackgrounColor;
                if (GUILayout.Button("S", GUILayout.Width(20)))
                    entry.selected = !entry.selected;
                GUI.backgroundColor = defaultGUIBackgrounColor;

                entry.name = (BuildUtils.GameLoopMode)EditorGUILayout.EnumPopup(entry.name);

                GUILayout.Label("Count:", GUILayout.Width(40));
                entry.count = EditorGUILayout.IntField(entry.count, GUILayout.Width(40), GUILayout.ExpandWidth(false));

                GUI.backgroundColor = Color.yellow;
                if (GUILayout.Button("Start", GUILayout.Width(50)))
                {
                    StartEntry(entry);
                }
                GUI.backgroundColor = defaultGUIBackgrounColor;
                GUI.backgroundColor = entry.runInEditor ? Color.yellow : GUI.backgroundColor;
                GUI.backgroundColor = defaultGUIBackgrounColor;

                var runInEditor = GUILayout.Toggle(entry.runInEditor, "Editor", new GUIStyle("Button"), GUILayout.Width(50));
                if (runInEditor != entry.runInEditor)
                {
                    for (var j = 0; j < data.entries.Count; j++)
                        data.entries[j].runInEditor = false;
                    entry.runInEditor = runInEditor;
                }
                GUILayout.Space(5.0f);
            }
            GUILayout.EndHorizontal();
        }

        GUILayout.FlexibleSpace();

        GUILayout.Space(10.0f);

        DrawLine();

        // Remove All Entries button
        GUILayout.BeginHorizontal();
        {
            GUI.backgroundColor = Color.red;
            if (GUILayout.Button("Remove All Entries"))
            {
                data.entries.Clear();
            }
            GUI.backgroundColor = defaultGUIBackgrounColor;
        }
        GUILayout.EndHorizontal();

        GUILayout.Space(10.0f);
        EditorGUILayout.EndVertical();

        EditorGUILayout.EndScrollView();
    }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void removeListViewItem(string flag, string way)
        {
            if (flag == "All")
            {
                listView3.Items.Clear();
                if (way == "L2R")
                {
                    localList.Clear();
                }
                else if(way == "R2L")
                {
                    remoteList.Clear();
                }
                else
                {
                    localList.Clear();
                    remoteList.Clear();
                }
            }
            else
            {
                int count = 0;
                foreach (ListViewItem item in listView3.Items)
                {
                    if (item.SubItems[1].Text == flag)
                    {
                        listView3.Items.Remove(item);
                        count++;
                        break;
                    }
                }
                if (way == "L2R")
                {
                    foreach (TransferItem item in localList)
                    {
                        if (item.Status.ToString() == flag)
                        {
                            localList.Remove(item);
                            count++;
                            break;
                        }
                    }
                }
                else
                {
                    foreach (TransferItem item in remoteList)
                    {
                        if (item.Status.ToString() == flag)
                        {
                            remoteList.Remove(item);
                            count++;
                            break;
                        }
                    }
                }
                if (count > 0)
                {
                    removeListViewItem(flag, way);
                }
            }
        }

19 View Source File : Player.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void MergeWithBuffer()
    {
        lock (userCommandBufferList)
        {
            // TODO work out why some User Commands are null 
            // it works for now tho
            for (int i = userCommandBufferList.Count - 1; i >= 0; i--)
            {
                if (userCommandBufferList[i] == null)
                {
                    userCommandBufferList.RemoveAt(i);
                }
                else
                {
                    jitter.Update(userCommandBufferList[i].serverRecTime - lastRecTime);
                    lastRecTime = userCommandBufferList[i].serverRecTime;
                }
            }

            userCommandList.AddRange(userCommandBufferList);
            userCommandBufferList.Clear();
        }
            
        userCommandList.Sort((a, b) => a.serverRecTime.CompareTo(b.serverRecTime));

        // DEBUG Jitter
        //Debug.Log(jitter.stdDeviation + ", " + jitter.average);
    }

19 View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

19 View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static List<YmlItem> FormatYmlToTree(string content)
        {
            List<YmlItem> lists = new List<YmlItem>();
            string[] lines = content.Split('\n');
            YmlItem item = null;
            string startStr = "";
            List<YmlItem> levels = new List<YmlItem>();
            int index1 = -1, index2 = -1, index = 0;
            foreach(string line in lines){
                if(string.IsNullOrWhiteSpace(line)){
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 2;
                    item.Key = "#" + line;
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    lists.Add(item);
                    continue;
                }
                if(line.TrimStart().StartsWith("#")){
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 2;
                    item.Key = line;
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    lists.Add(item);
                }
                else
                {
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 0;
                    item.Key = "";
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    item.SpcCount = StartSpaceCount(line);
                    if (item.SpcCount == 0)
                    {
                        levels.Clear();
                        item.Level = 0;
                    }
                    else
                    {
                        // level
                        for (int i = levels.Count - 1; i >= 0; i-- )
                        {
                            if (levels[i].SpcCount < item.SpcCount)
                            {
                                item.Level = levels[i].Level + 1;
                                item.Parent = levels[i];
                                break;
                            }
                        }
                    }
                    levels.Add(item);

                    index2 = line.IndexOf("#");
                    if (index2 > 0)
                    {
                        startStr = line.Substring(0, index2);
                        item.Common = line.Substring(index2);
                    }
                    else
                    {
                        startStr = line;
                    }

                    index1 = startStr.IndexOf(":");
                    if (index1 > 0)
                    {
                        item.Key = startStr.Substring(0, index1).TrimStart();
                        item.Value = startStr.Substring(index1 + 1).Trim();
                    }
                    else
                    {
                        item.Key = startStr.TrimStart();
                        item.Common = "--格式错误--";
                    }

                    if (!string.IsNullOrWhiteSpace(item.Value))
                    {
                        item.ImageIndex = 1;
                    }

                    lists.Add(item);
                }
            }

            return lists;
        }

19 View Source File : XMLParser.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

public static string[] FindByTag(string NodeName, XmlDoreplacedent doreplacedent)
        {
            XmlNodeList tags = doreplacedent.GetElementsByTagName(@NodeName);

            // Check if nodes were found
            if (tags.Count < 1)
            {
                // Return null if not found
                return null;
            }
            else
            {

                List<string> l = new List<string>();

                //Go though each found node and add it to the list
                foreach(XmlNode n in tags)
                {
                    l.Add(n.InnerText);
                }
                
                //Convert it to array, clear the list and return
                string[] f = l.ToArray();
                l.Clear();
                return f;
            }
        }

19 View Source File : SubSettingForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void RefreshSubsView()
        {
            panCon.Controls.Clear();
            lstControls.Clear();

            for (int k = config.subItem.Count - 1; k >= 0; k--)
            {
                SubItem item = config.subItem[k];
                if (Utils.IsNullOrEmpty(item.remarks)
                    && Utils.IsNullOrEmpty(item.url))
                {
                    if (!Utils.IsNullOrEmpty(item.id))
                    {
                        ConfigHandler.RemoveServerViaSubid(ref config, item.id);
                    }
                    config.subItem.RemoveAt(k);
                }
            }

            foreach (SubItem item in config.subItem)
            {
                SubSettingControl control = new SubSettingControl();
                control.OnButtonClicked += Control_OnButtonClicked;
                control.subItem = item;
                control.Dock = DockStyle.Top;

                panCon.Controls.Add(control);
                panCon.Controls.SetChildIndex(control, 0);

                lstControls.Add(control);
            }
        }

19 View Source File : CompressedAV1ImageCollection.cs
License : MIT License
Project Creator : 0xC0000054

public void Clear()
        {
            for (int i = 0; i < this.items.Count; i++)
            {
                this.items[i]?.Dispose();
            }

            this.items.Clear();
            this.version++;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 20chan

private bool TryReplace() {
            foreach (var w in badWords) {
                if (Match(w)) {
                    Replace(w.Length);
                    queue.Clear();
                    return true;
                }
            }
            return false;

            bool Match(string s) {
                if (s.Length != queue.Count) {
                    return false;
                }
                for (var i = 0; i < s.Length; i++) {
                    if (queue[i] != char.ToUpper(s[i])) {
                        return false;
                    }
                }
                return true;
            }
        }

19 View Source File : UnityThread.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void Update()
    {
        if (noActionQueueToExecuteUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueUpdateFunc queue
        actionCopiedQueueUpdateFunc.Clear();
        lock (actionQueuesUpdateFunc)
        {
            //Copy actionQueuesUpdateFunc to the actionCopiedQueueUpdateFunc variable
            actionCopiedQueueUpdateFunc.AddRange(actionQueuesUpdateFunc);
            //Now clear the actionQueuesUpdateFunc since we've done copying it
            actionQueuesUpdateFunc.Clear();
            noActionQueueToExecuteUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueUpdateFunc
        for (int i = 0; i < actionCopiedQueueUpdateFunc.Count; i++)
        {
            actionCopiedQueueUpdateFunc[i].Invoke();
        }
    }

19 View Source File : MetadataProvider.cs
License : MIT License
Project Creator : 0xd4d

public void Dispose() {
			foreach (var module in modules)
				module.Dispose();
			modules.Clear();
		}

19 View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static List<YmlLine> FormatYml(string content, bool beautify = false)
        {
            List<YmlLine> list = new List<YmlLine>();
            string[] lines = content.Split('\n');
            YmlLine ylText = null;
            int index1 = -1, index2 = -1, count = 0, num = 0;
            string startStr = null, endStr = null, line = "";
            string key = null, value = null, mh = ":";
            List<int> levels = new List<int>();
            for(int i = 0, k = lines.Length; i < k; i++){
                line = lines[i];

                if(line.TrimStart().StartsWith("#")){
                    ylText = new YmlLine()
                    {
                        Text = line + "\n",
                        Color = Color.Gray
                    };
                    list.Add(ylText);
                }
                else
                {
                    // 非整行注释

                    // 美化
                    if (beautify)
                    {
                        count = StartSpaceCount(line);
                        if (count == 0)
                        {
                            levels.Clear();
                        }
                        // level
                        if (!levels.Contains(count))
                        {
                            levels.Add(count);
                            levels.Sort();
                        }
                        num = levels.IndexOf(count) * 4;
                        if (num > count)
                        {
                            line = GetSpace(num - count) + line;
                        }
                    }                    

                    // 行中有井号,但不是首位#
                    index2 = line.IndexOf("#");
                    if(index2 > 0){
                        startStr = line.Substring(0, index2);

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value,
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            ylText = new YmlLine()
                            {
                                Text = "#" + startStr,
                                Color = Color.Gray
                            };
                            list.Add(ylText);
                        }

                        // 注释掉的部分
                        endStr = line.Substring(index2);
                        ylText = new YmlLine()
                        {
                            Text = endStr + "\n",
                            Color = Color.Gray
                        };
                        list.Add(ylText);
                    }
                    else
                    {
                        // 行中无井号
                        startStr = line;

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value + "\n",
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            // 行中无井号,且是不合规的配置值
                            if (string.IsNullOrWhiteSpace(line))
                            {
                                ylText = new YmlLine()
                                {
                                    Text = line + "\n",
                                    Color = Color.OrangeRed
                                };
                            }
                            else
                            {
                                ylText = new YmlLine()
                                {
                                    Text = "#" + line + "\n",
                                    Color = Color.Gray
                                };
                            }                            
                            list.Add(ylText);                            
                        }
                    }
                }
            }
            return list;
        }

19 View Source File : StringDedupeContext.cs
License : MIT License
Project Creator : 0x0ade

public void Cleanup() {
            foreach (KeyValuePair<int, int> entry in Counting) {
                int score = entry.Value - DemotionScore;
                if (score <= 0) {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, 0));
                } else if (score >= PromotionTreshold) {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, 0));
                    Map[entry.Key] = new();
                } else {
                    CountingUpdates.Add(ToCountingUpdate(entry.Key, score));
                }
            }
            foreach (ulong update in CountingUpdates) {
                FromCountingUpdate(update, out int key, out int value);
                if (value == 0)
                    Counting.Remove(key);
                else
                    Counting[key] = value;
            }
            CountingUpdates.Clear();
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void restartTransfersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (localQueue.Count == 0 && localList.Count > 0)
            {
                listView3.Items.Clear();
                foreach (TransferItem item in localList)
                {
                    if (item.Status != TransferStatus.Success)
                    {
                        AddItemToListView(item);
                        localQueue.Enqueue(item);
                    }
                }
                localList.Clear();

                StartL2R();
            }
            else if (remoteQueue.Count == 0 && remoteList.Count > 0)
            {
                listView3.Items.Clear();
                foreach (TransferItem item in remoteList)
                {
                    if (item.Status != TransferStatus.Success)
                    {
                        AddItemToListView(item);
                        remoteQueue.Enqueue(item);
                    }
                }
                remoteList.Clear();

                StartR2L();
            }
        }

19 View Source File : CollectionAbstract.cs
License : MIT License
Project Creator : 17MKH

public void Clear()
    {
        Collection.Clear();
    }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private int GetLvSelectedIndex()
        {
            int index = -1;
            lvSelecteds.Clear();
            try
            {
                if (lvServers.SelectedIndices.Count <= 0)
                {
                    UI.Show(UIRes.I18N("PleaseSelectServer"));
                    return index;
                }

                index = lvServers.SelectedIndices[0];
                foreach (int i in lvServers.SelectedIndices)
                {
                    lvSelecteds.Add(i);
                }
                return index;
            }
            catch
            {
                return index;
            }
        }

19 View Source File : RequestDispatcher.cs
License : MIT License
Project Creator : 0ffffffffh

public static void Shutdown()
        {
            _Active = false;

            Log.Info("waiting dispatchers to finish");

            foreach (Thread t in _Dispatchers)
            {
                t.Join();
            }

            Log.Info("all dispatchers finished their jobs");

            _Dispatchers.Clear();
        }

19 View Source File : DbContextSync.cs
License : MIT License
Project Creator : 2881099

internal void ExecCommand() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, int> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], int>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(int));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(int)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Action funcDelete = () => {
				_affrows += dbContextBetch("DbContextBetchRemove");
				states.Clear();
			};
			Action funcInsert = () => {
				_affrows += dbContextBetch("DbContextBetchAdd");
				states.Clear();
			};
			Action<bool> funcUpdate = isLiveUpdate => {
				var affrows = 0;
				if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
				else affrows = dbContextBetch("DbContextBetchUpdate");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : InvokeMethodAction.cs
License : MIT License
Project Creator : 1iveowl

private void UpdateMethodDescriptors()
        {
            _methodDescriptors.Clear();

            _cachedMethodDescriptor = null;

            if (string.IsNullOrWhiteSpace(MethodName) || _targetObjectType is null)
            {
                return;
            }

            foreach (var method in _targetObjectType.GetRuntimeMethods())
            {
                if (string.Equals(method.Name, MethodName, StringComparison.Ordinal) 
                    && method.ReturnType == typeof(void)
                    && method.IsPublic)
                {
                    var parameters = method.GetParameters();

                    if (parameters.Length == 0)
                    {
                        _cachedMethodDescriptor = new MethodDescriptor(method, parameters);
                    }
                        
                    else if (parameters.Length == 2 && parameters[0].ParameterType == typeof(object))
                    {
                        _methodDescriptors.Add(new MethodDescriptor(method, parameters));
                    }
                }
            }

        }

19 View Source File : WorldState.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static void Interp(List<PlayerState> prevStates, List<PlayerState> nextStates, float f,
                              ref List<PlayerState> playerStates)
    {
        playerStates.Clear();

        PlayerState temp;
        
        foreach (var nextState in nextStates)
        {
            var prevState = prevStates.FirstOrDefault(x => x.playerId == nextState.playerId);
            // Check whether the end result is also contained in the start snapshot
            // if so we can interpolate otherwise we simply set the value.
            if (!nextState.Equals(default(PlayerState))) {
                // interpolate
                var interpPosition = Vector2.Lerp(prevState.pos, nextState.pos, f);
                var interpRotation = Mathf.LerpAngle(prevState.zAngle, nextState.zAngle, f);

                temp = new PlayerState(nextState.playerId, interpRotation, interpPosition);
                playerStates.Add(temp);
            } 
            else
            {
                // set the value directly
                playerStates.Add(nextState);
            }
        }
    }

19 View Source File : UIIconManager.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void Reset() {
            IconConfigs.Clear();
            Icons.ForEach(x => x.Dispose());
            Icons.Clear();
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void Update()
    {
        // Network Tick.
        lock (instantiateJobs)
        {
            for (int i = 0; i < instantiateJobs.Count; i++)
            {
                (User user, ushort id) = instantiateJobs[i]; 

                var obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.idenreplacedy);
                var tmpPlayer = obj.GetComponent<Player>();
                tmpPlayer.SetPlayerID(id);

                user.player = tmpPlayer;

                // Attach the Lag compensation module to the new instantiated player.
                obj.AddComponent<LagCompensationModule>().Init(user.player);
            }

            instantiateJobs.Clear();
        }

        
        lock (disconnectedClients)
        {

            foreach (var clientSock in clients.Keys)
            {
                if (clients[clientSock].player.playerContainer == null)
                {
                    OnUserDisconnect(clientSock);
                }
            }

            foreach (var disconnectedSock in disconnectedClients)
            {
                var playerId = clients[disconnectedSock].player.playerId;
                if (clients[disconnectedSock].player.playerContainer != null)
                {
                    GameObject.Destroy(clients[disconnectedSock].player.playerContainer);
                }

                lock (clients)
                {
                    clients.Remove(disconnectedSock);
                }

                lock (playerIdList)
                {
                    playerIdList.Add(playerId);
                    // return the id number to the id pool for new players to join in.
                    Console.WriteLine("Client Disconnected, Returned Player ID: " + playerId);
                    Console.WriteLine("Player Count: " + (MaximumPlayers - playerIdList.Count) + " / " + MaximumPlayers);
                }
            }

            disconnectedClients.Clear();
        }

        // Every tick we call update function which will process all the user commands and apply them to the physics world.
        serverLoop.Update(clients.Values.Select(x => x.player).ToList());

        WorldState snapshot = serverLoop.GetSnapshot();

        lock (OutputsOG)
        {
            for (int i = OutputsOG.Count - 1; i >= 0; i--)
            {
                var sock = OutputsOG[i];

                try
                {
                    SendSnapshot(sock, snapshot);
                }
                catch
                {
                    OnUserDisconnect(sock);
                }
            }
        }
    }

19 View Source File : Disassembler.cs
License : MIT License
Project Creator : 0xd4d

public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
			formatterOutput.writer = output;
			targets.Clear();
			sortedTargets.Clear();

			bool uppercaseHex = formatter.Options.UppercaseHex;

			output.Write(commentPrefix);
			output.WriteLine("================================================================================");
			output.Write(commentPrefix);
			output.WriteLine(method.MethodFullName);
			uint codeSize = 0;
			foreach (var info in method.Code)
				codeSize += (uint)info.Code.Length;
			var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
			output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
			var instrCount = method.Instructions.Count;
			var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
			output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");

			void Add(ulong address, TargetKind kind) {
				if (!targets.TryGetValue(address, out var addrInfo))
					targets[address] = new AddressInfo(kind);
				else if (addrInfo.Kind < kind)
					addrInfo.Kind = kind;
			}
			if (method.Instructions.Count > 0)
				Add(method.Instructions[0].IP, TargetKind.Unknown);
			foreach (ref var instr in method.Instructions) {
				switch (instr.FlowControl) {
				case FlowControl.Next:
				case FlowControl.Interrupt:
					break;

				case FlowControl.UnconditionalBranch:
					Add(instr.NextIP, TargetKind.Unknown);
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Branch);
					break;

				case FlowControl.ConditionalBranch:
				case FlowControl.XbeginXabortXend:
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Branch);
					break;

				case FlowControl.Call:
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Call);
					break;

				case FlowControl.IndirectBranch:
					Add(instr.NextIP, TargetKind.Unknown);
					// Unknown target
					break;

				case FlowControl.IndirectCall:
					// Unknown target
					break;

				case FlowControl.Return:
				case FlowControl.Exception:
					Add(instr.NextIP, TargetKind.Unknown);
					break;

				default:
					Debug.Fail($"Unknown flow control: {instr.FlowControl}");
					break;
				}

				var baseReg = instr.MemoryBase;
				if (baseReg == Register.RIP || baseReg == Register.EIP) {
					int opCount = instr.OpCount;
					for (int i = 0; i < opCount; i++) {
						if (instr.GetOpKind(i) == OpKind.Memory) {
							if (method.Contains(instr.IPRelativeMemoryAddress))
								Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
							break;
						}
					}
				}
				else if (instr.MemoryDisplSize >= 2) {
					ulong displ;
					switch (instr.MemoryDisplSize) {
					case 2:
					case 4: displ = instr.MemoryDisplacement; break;
					case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
					default:
						Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
						goto case 8;
					}
					if (method.Contains(displ))
						Add(displ, TargetKind.Branch);
				}
			}
			foreach (var map in method.ILMap) {
				if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
					if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
						info.Kind = TargetKind.BlockStart;
				}
				else
					targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
				if (info.ILOffset < 0)
					info.ILOffset = map.ilOffset;
			}

			int labelIndex = 0, methodIndex = 0;
			string GetLabel(int index) => LABEL_PREFIX + index.ToString();
			string GetFunc(int index) => FUNC_PREFIX + index.ToString();
			foreach (var kv in targets) {
				if (method.Contains(kv.Key))
					sortedTargets.Add(kv);
			}
			sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
			foreach (var kv in sortedTargets) {
				var address = kv.Key;
				var info = kv.Value;

				switch (info.Kind) {
				case TargetKind.Unknown:
					info.Name = null;
					break;

				case TargetKind.Data:
					info.Name = GetLabel(labelIndex++);
					break;

				case TargetKind.BlockStart:
				case TargetKind.Branch:
					info.Name = GetLabel(labelIndex++);
					break;

				case TargetKind.Call:
					info.Name = GetFunc(methodIndex++);
					break;

				default:
					throw new InvalidOperationException();
				}
			}

			foreach (ref var instr in method.Instructions) {
				ulong ip = instr.IP;
				if (targets.TryGetValue(ip, out var lblInfo)) {
					output.WriteLine();
					if (!(lblInfo.Name is null)) {
						output.Write(lblInfo.Name);
						output.Write(':');
						output.WriteLine();
					}
					if (lblInfo.ILOffset >= 0) {
						if (ShowSourceCode) {
							foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
								output.Write(commentPrefix);
								var line = info.Line;
								int column = commentPrefix.Length;
								WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
								output.WriteLine();
								if (info.Partial) {
									output.Write(commentPrefix);
									column = commentPrefix.Length;
									WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
									output.WriteLine(new string('^', info.Span.Length));
								}
							}
						}
					}
				}

				if (ShowAddresses) {
					var address = FormatAddress(bitness, ip, uppercaseHex);
					output.Write(address);
					output.Write(" ");
				}
				else
					output.Write(formatter.Options.TabSize > 0 ? "\t\t" : "        ");

				if (ShowHexBytes) {
					if (!method.TryGetCode(ip, out var nativeCode))
						throw new InvalidOperationException();
					var codeBytes = nativeCode.Code;
					int index = (int)(ip - nativeCode.IP);
					int instrLen = instr.Length;
					for (int i = 0; i < instrLen; i++) {
						byte b = codeBytes[index + i];
						output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
					}
					int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
					for (int i = 0; i < missingBytes; i++)
						output.Write("  ");
					output.Write(" ");
				}

				formatter.Format(instr, formatterOutput);
				output.WriteLine();
			}
		}

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void StartListening()
    {
        List<Socket> Inputs;
        List<Socket> Errors;

        Console.WriteLine("Main Loop Listening");
        InputsOG.Add(listenerSocket);

        isRunning = true;
        while (isRunning)
        {
            Inputs = InputsOG.ToList();
            Errors = InputsOG.ToList();

            Socket.Select(Inputs, null, Errors, -1);

            foreach (Socket sock in Inputs)
            {
                if (sock == listenerSocket)
                {
                    // If the sock is the server socket then we got a new player.
                    // So we need to Accept the socket and replacedign the socket an available new player ID and enreplacedy.
                    Socket newConnection = sock.Accept();

                    if (playerIdList.Count > 0)
                    {
                        OnUserConnect(newConnection);
                    } 
                    else
                    {
                        Debug.Log($"{newConnection.RemoteEndPoint} failed to connect: Server full!");
                        newConnection.Close();
                    }
                }
                else if (sock != null)
                {
                    if (!isRunning)
                        return;

                    try
                    {
                        User usr = clients[sock];
                        // Receive and process one message at a time.
                        bool result = usr.ReceiveOnce();

                        if (result == false)
                        {
                            OnUserDisconnect(sock);
                        }
                    }
                    catch { }
                }
            }

            foreach (Socket sock in Errors)
            {
                Console.WriteLine("Client Disconnected: Cause - Error");
                OnUserDisconnect(sock);
            }

            Errors.Clear();
        }

        Debug.Log("Stop Listening");
    }

19 View Source File : UnityThread.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void LateUpdate()
    {
        if (noActionQueueToExecuteLateUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueLateUpdateFunc queue
        actionCopiedQueueLateUpdateFunc.Clear();
        lock (actionQueuesLateUpdateFunc)
        {
            //Copy actionQueuesLateUpdateFunc to the actionCopiedQueueLateUpdateFunc variable
            actionCopiedQueueLateUpdateFunc.AddRange(actionQueuesLateUpdateFunc);
            //Now clear the actionQueuesLateUpdateFunc since we've done copying it
            actionQueuesLateUpdateFunc.Clear();
            noActionQueueToExecuteLateUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueLateUpdateFunc
        for (int i = 0; i < actionCopiedQueueLateUpdateFunc.Count; i++)
        {
            actionCopiedQueueLateUpdateFunc[i].Invoke();
        }
    }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private void WaitForConnectionCallback(IAsyncResult result)
        {
            if (server == null)
            {
                return;
            }

            try
            {
                server.EndWaitForConnection(result);
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            byte[] replySizeBuffer = new byte[sizeof(int)];
            server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);

            int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);

            byte[] messageBytes = new byte[messageLength];

            server.ProperRead(messageBytes, 0, messageLength);

            List<string> parameters = DecodeMessageBuffer(messageBytes);

            if (!TryGetValue(parameters[0], "command=", out string command))
            {
                throw new InvalidOperationException("The first item must be a command.");
            }

            if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the input mode.");
                }

                InputMode inputMode = ParseInputMode(mode);

#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
                string reply = GetMaxLayerSize(inputMode);

                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the input mode.");
                }

                if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
                {
                    throw new InvalidOperationException("The third item must be the crop rectangle.");
                }

                InputMode inputMode = ParseInputMode(mode);
                RectangleF cropRect = GetCropRectangle(packedCropRect);

#if DEBUG
                System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                                 "'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
                                                                 inputMode.ToString(), cropRect.ToString()));
#endif
                string reply = PrepareCroppedLayers(inputMode, cropRect);

                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the output mode.");
                }

                OutputMode outputMode = ParseOutputMode(mode);

#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif

                List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);

                string reply = ProcessOutputImage(outputLayers, outputMode);
                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif

                for (int i = 0; i < memoryMappedFiles.Count; i++)
                {
                    memoryMappedFiles[i].Dispose();
                }
                memoryMappedFiles.Clear();

                SendMessage(server, "done");
            }
            else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
            {
                // This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
                // Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
                // integer to the unsigned 32-bit size_t type.
                long maxDataLength = 0;

                foreach (GmicLayer layer in layers)
                {
                    maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
                }

                server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
                server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
            }

            // Wait for the acknowledgment that the client is done reading.
            if (server.IsConnected)
            {
                byte[] doneMessageBuffer = new byte[4];
                int bytesRead = 0;
                int bytesToRead = doneMessageBuffer.Length;

                do
                {
                    int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);

                    bytesRead += n;
                    bytesToRead -= n;

                } while (bytesToRead > 0 && server.IsConnected);
            }

            // Start a new server and wait for the next connection.
            server.Dispose();
            server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            server.BeginWaitForConnection(WaitForConnectionCallback, null);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 20chan

private void TryEnqueue(int key) {
            var isChar = 65 <= key && key <= 90;
            if (!isChar) {
                queue.Clear();
                return;
            }
            queue.Add(key);
        }

19 View Source File : ListSnapshot.cs
License : MIT License
Project Creator : 0x0ade

public void Set(IEnumerable<T> list) {
            List.Clear();
            List.AddRange(list);
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void restartFailedsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(localQueue.Count == 0 && localList.Count > 0){
                listView3.Items.Clear();
                foreach (TransferItem item in localList)
                {
                    if(item.Status == TransferStatus.Failed){
                        AddItemToListView(item);
                        localQueue.Enqueue(item);
                    }
                }
                localList.Clear();

                StartL2R();
            }
            else if (remoteQueue.Count == 0 && remoteList.Count > 0)
            {
                listView3.Items.Clear();
                foreach (TransferItem item in remoteList)
                {
                    if (item.Status == TransferStatus.Failed)
                    {
                        AddItemToListView(item);
                        remoteQueue.Enqueue(item);
                    }
                }
                remoteList.Clear();

                StartR2L();
            }
        }

19 View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var nodes))
            {
                if (!currentNodes.Any())
                    nodes.Clear();

                var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
                if (leavedNodes.Any())
                {
                    Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                    OnNodeLeave?.Invoke(serviceName, leavedNodes);
                    nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
                }

                var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
                if (addedNodes.Any())
                {
                    nodes.AddRange(addedNodes);
                    Logger.LogTrace(
                        $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                    OnNodeJoin?.Invoke(serviceName, addedNodes);
                }
            }
            else
            {
                if (!currentNodes.Any())
                    ServiceNodes.TryAdd(serviceName, currentNodes);
            }
        }

19 View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099

public void Dispose()
        {

            running = false;

            while (_freeObjects.TryPop(out var fo)) ;

            while (_getSyncQueue.TryDequeue(out var sync))
            {
                try { sync.Wait.Set(); } catch { }
            }

            while (_getAsyncQueue.TryDequeue(out var async))
                async.TrySetCanceled();

            while (_getQueue.TryDequeue(out var qs)) ;

            for (var a = 0; a < _allObjects.Count; a++)
            {
                Policy.OnDestroy(_allObjects[a].Value);
                try { (_allObjects[a].Value as IDisposable)?.Dispose(); } catch { }
            }

            _allObjects.Clear();
        }

19 View Source File : Watchdog.cs
License : MIT License
Project Creator : 0ffffffffh

private void SnapshotProcesses(List<Process> processes)
        {
            Process[] procs = Process.GetProcesses();
            processes.Clear();

            foreach (var proc in procs)
            {
                if (IsWatchableProcess(proc))
                    processes.Add(proc);
            }

            procs = null;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {

            sedb.StringSet("key1", (string)null);

            var val111 = sedb.StringGet("key1");














            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            results.Clear();
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //Task.Run(async () =>
            //{
            //    for (var a = 0; a < 100000; a++)
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }
            //}).Wait();
            //sw.Stop();
            //Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            //sw.Reset();
            //sw.Start();
            //tasks = new List<Task>();
            //for (var a = 0; a < 100000; a++)
            //{
            //    tasks.Add(Task.Run(async () =>
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }));
            //}
            //Task.WaitAll(tasks.ToArray());
            //sw.Stop();
            ////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            ////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            //Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();
        }

19 View Source File : Assets.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

public static void Flush() => allreplacedetsKnown.Clear();

19 View Source File : TransactionsAdapter.cs
License : MIT License
Project Creator : 2881099

void TryReset()
            {
                if (_redisSocket == null) return;
#if isasync
                for (var a = 0; a < _commands.Count; a++)
                    _commands[a].TrySetCanceled();
#endif
                _commands.Clear();
                _redisSocket?.Dispose();
                _redisSocket = null;
            }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void Dispose() {
            Modder?.Dispose();

#if !CECIL0_9
            foreach (ModuleDefinition mod in Modules)
                mod.Dispose();
#endif
            Modules.Clear();
            ModulesToStub.Clear();
            Directories.Clear();
        }

19 View Source File : PipelineAdapter.cs
License : MIT License
Project Creator : 2881099

public override void Dispose()
            {
#if isasync
                for (var a = 0; a < _commands.Count; a++)
                    _commands[a].TrySetCanceled();
#endif
                _commands.Clear();
            }

19 View Source File : QueryParameters.cs
License : MIT License
Project Creator : 17MKH

public void Clear()
    {
        _parameters.Clear(); 
    }

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : CooldownPartyMember.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void SetupTrackers() {
            Trackers.Clear();

            var trackerProps = JobBars.CooldownManager.GetCooldownConfigs(CurrentJob);
            foreach (var prop in trackerProps.OrderBy(x => x.Order)) {
                if (!prop.Enabled) continue;
                Trackers.Add(new CooldownTracker(prop));
            }
        }

19 View Source File : RoutingRuleSettingForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private int GetLvSelectedIndex()
        {
            int index = -1;
            lvSelecteds.Clear();
            try
            {
                if (lvRoutings.SelectedIndices.Count <= 0)
                {
                    UI.Show(UIRes.I18N("PleaseSelectRules"));
                    return index;
                }

                index = lvRoutings.SelectedIndices[0];
                foreach (int i in lvRoutings.SelectedIndices)
                {
                    lvSelecteds.Add(i);
                }
                return index;
            }
            catch
            {
                return index;
            }
        }

19 View Source File : ServerLoop.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void Update(List<Player> players)
    {
        /*
        Update Clients and Apply User Commands
        Tick length is Time.fixedDeltaTime

        Remove used player's User Commands
        
        Take A Snapshot of the updated world
        */
        NetworkTick.tickSeq++;

        rayStates.Clear();

        tickDuration = Time.deltaTime;
        
        float startTickTime = StopWacthTime.Time;
        float endTickTime = startTickTime + tickDuration;

        // Important debug
        //Debug.Log("Tick Rate: " + (1.0f / tickDuration) + " [Hz], Tick Duration: " + (tickDuration * 1000) + "[ms]");
        //Debug.Log("Tick Duration " + tickDuration + " Start: " + startTickTime + " End: " + endTickTime);
        //Debug.Log("Tick delta " + (Mathf.RoundToInt((startTickTime - lastStartTickTime) / 0.00001f) * 0.00001)); // Drift;

        float simTimeForCurrTick = 0;
        float minorJump;

        float currEventsTime;
        float nextEventsTime;

        List<ServerUserCommand> currUserCommands;
        List<int> playerEventIndexes = new List<int>();

        for (int i = players.Count - 1; i >= 0; i--)
        {
            Player p = players[i];
            if (p.playerContainer != null)
            {
                // Before we run the tick we store the last tick in the backtracking buffer
                // Which is then beign used in the lag compensation algorithm.
                // This snapshot is being taken before the start of the tick therefore we subtract one
                p.playerContainer.GetComponent<LagCompensationModule>().TakeSnapshot(NetworkTick.tickSeq - 1);

                playerEventIndexes.Add(0);

                if (p != null)
                {
                    p.MergeWithBuffer();
                }
            }
            else
            {
                players.Remove(p);
            }
        }

        // Simulate Till first event
        // or Till the end Tick Time if there is no event from the clients.
        currEventsTime = GetEventsMinimalTime(players, playerEventIndexes);
        if (currEventsTime == NoMoreEvents)
            minorJump = tickDuration;
        else
            minorJump = (currEventsTime - startTickTime);

        if (minorJump > 0)
        {
            // DEBUG
            simTimeForCurrTick += minorJump;
            Physics2D.Simulate(minorJump);
        }
        else
        {
            minorJump = 0;
        }

        while (simTimeForCurrTick < tickDuration)
        {
            // Get all the events with minimal time.
            currUserCommands = GetEvents(players, playerEventIndexes, currEventsTime);

            nextEventsTime = GetEventsMinimalTime(players, playerEventIndexes);

            // START DEBUGGING
            // TODO MUST DEBUG HERE 
            /*
            if (currEventsTime == nextEventsTime)
            {
                nextEventsTime = NoMoreEvents;
            }

            if (currUserCommands.Count == 0)
            {
                nextEventsTime = NoMoreEvents;
            }
            */
            if (nextEventsTime == NoMoreEvents)
            {
                minorJump = tickDuration - simTimeForCurrTick;
            }
            else
            {
                minorJump = nextEventsTime - currEventsTime;
            }

            // END DEBUGGING

            if ((simTimeForCurrTick + minorJump) > tickDuration)
            {
                minorJump = tickDuration - simTimeForCurrTick;
            } 

            currEventsTime = nextEventsTime;

            ApplyUserCommands(currUserCommands);

            // DEBUG
            //Debug.Log("Minor Jump " + minorJump);

            simTimeForCurrTick += minorJump;
            Physics2D.Simulate(minorJump);
        }

        DeleteUsedEvents(players, playerEventIndexes);

        TakeSnapshot(players, rayStates);

        lastStartTickTime = startTickTime;

        // DEBUG the event loop, make sure we are simulating the same amount of time that preplaced in realtime
        // Debug.Log("Sim Time for tick: " + NetworkTick.tickSeq + ", " + simTimeForCurrTick + ", delta: " + (simTimeForCurrTick - tickDuration));
    }

19 View Source File : DialogueManagerController.cs
License : MIT License
Project Creator : 0xbustos

public bool DisplayNextSentence()
        {
            foreach (LetterComponent letter in this.letters)
            {
                GameObject.Destroy( letter.gameObject );
            }

            this.currentSpeed = this.Model.WaitTime;
            this.currentEffect = null;
            this.effects.Clear();
            this.speeds.Clear();
            this.letters.Clear();
            this.currentX = 0;
            this.currentY = 0;

            if (sentences.Count == 0)
            {
                EndDialogue();
                return false;
            }

            this.Model.ImageText.sprite = sprites.Dequeue();
            this.sentence = sentences.Dequeue();
            this.audioQueue = voices.Dequeue();
            this.Model.WaitTime = 0f;
            string onlyWords = string.Empty;

            for (int i = 0; i < this.sentence.Length; i++)
            {
                if (this.sentence[i] == '[')
                {
                    i = this.changeSpeed( i );
                }
                else if (this.sentence[i] == '<')
                {
                    i = this.changeEffect( i );
                }
                else
                {
                    this.effects.Add( this.currentEffect );
                    if (this.sentence[i] != ' ')
                    {
                        this.speeds.Add( ( float )this.currentSpeed );
                    }
                    onlyWords += this.sentence[i];
                }
            }

            string[] words = onlyWords.Split( ' ' );
            int letterSpacing = ( int )( this.fontSize * 0.5 );
            int currentIndexEffects = 0;
            int currentIndexSpeeds = 0;
            foreach (string word in words)
            {
                GameObject wordObject = new GameObject( word, typeof( RectTransform ) );
                wordObject.transform.SetParent( this.Model.DialogueStartPoint );
                int wordSize = word.Length * letterSpacing;
                if (this.currentX + wordSize > this.boxSize)
                {
                    this.currentX = 0;
                    this.currentY -= ( int )( this.fontSize * 0.9 );
                }
                wordObject.GetComponent<RectTransform>().localPosition = new Vector3( currentX, currentY, 0 );

                for (int i = 0; i < word.Length; i++)
                {
                    GameObject letterObject = new GameObject( word[i].ToString() );
                    letterObject.transform.SetParent( wordObject.transform );
                    Text myText = letterObject.AddComponent<Text>();
                    myText.text = word[i].ToString();
                    myText.alignment = TextAnchor.LowerCenter;
                    myText.fontSize = this.fontSize;
                    myText.font = this.Model.Font;
                    myText.material = this.Model.Material;
                    myText.GetComponent<RectTransform>().localPosition = new Vector3( i * letterSpacing, 0, 0 );
                    myText.color = new Color( 0.0f, 0.0f, 0.0f, 0.0f );
                    RectTransform rt = letterObject.GetComponentInParent<RectTransform>();
                    rt.sizeDelta = new Vector2( this.fontSize, this.fontSize );
                    rt.pivot = new Vector2( 0, 1 );

                    LetterComponent letterComponent = letterObject.AddComponent<LetterComponent>();
                    
                    Letter newLetter = new Letter
                    {
                        Character = word[i],
                        Speed = this.speeds[currentIndexSpeeds],
                        isActive = false
                    };
                    if (this.effects[currentIndexEffects] != null)
                    {
                        newLetter.Effect = this.effects[currentIndexEffects].Build( letterObject );
                    }
                    letterComponent.Model = newLetter;
                    this.letters.Add( letterComponent );
                    currentIndexEffects++;
                    currentIndexSpeeds++;
                }
                currentX += wordSize + letterSpacing;
                currentIndexEffects++;
            }
            return true;
        }

19 View Source File : BuffPartyMember.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void SetupTrackers() {
            Trackers.Clear();

            var trackerProps = JobBars.BuffManager.GetBuffConfigs(CurrentJob, IsPlayer);
            foreach (var prop in trackerProps) {
                if (!prop.Enabled) continue;
                Trackers.Add(new BuffTracker(prop));
            }
        }

19 View Source File : Watchdog.cs
License : MIT License
Project Creator : 0ffffffffh

public void Release()
            {
                FirstSnapshot.Clear();
                SecondSnapshot.Clear();

                FirstSnapshot = null;
                SecondSnapshot = null;
            }

19 View Source File : StringMap.cs
License : MIT License
Project Creator : 0x0ade

public void Cleanup() {
            lock (Pending) {
                foreach (KeyValuePair<string, int> entry in Counting) {
                    int score = entry.Value - DemotionScore;
                    if (score <= 0) {
                        CountingUpdateKeys.Add(entry.Key);
                        CountingUpdateValues.Add(0);
                    } else if (score >= PromotionTreshold) {
                        CountingUpdateKeys.Add(entry.Key);
                        CountingUpdateValues.Add(0);
                        Pending.Add(entry.Key);
                    } else {
                        CountingUpdateKeys.Add(entry.Key);
                        CountingUpdateValues.Add(score);
                    }
                }
                for (int i = 0; i < CountingUpdateKeys.Count; i++) {
                    string key = CountingUpdateKeys[i];
                    int value = CountingUpdateValues[i];
                    if (value == 0)
                        Counting.Remove(key);
                    else
                        Counting[key] = value;
                }
                CountingUpdateKeys.Clear();
                CountingUpdateValues.Clear();
            }
        }

19 View Source File : TextureCollection.cs
License : MIT License
Project Creator : 0xC0000054

public void Clear()
        {
            for (int i = 0; i < this.items.Count; i++)
            {
                this.items[i]?.Dispose();
            }

            this.items.Clear();
        }

19 View Source File : UnityThread.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void FixedUpdate()
    {
        if (noActionQueueToExecuteFixedUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueFixedUpdateFunc queue
        actionCopiedQueueFixedUpdateFunc.Clear();
        lock (actionQueuesFixedUpdateFunc)
        {
            //Copy actionQueuesFixedUpdateFunc to the actionCopiedQueueFixedUpdateFunc variable
            actionCopiedQueueFixedUpdateFunc.AddRange(actionQueuesFixedUpdateFunc);
            //Now clear the actionQueuesFixedUpdateFunc since we've done copying it
            actionQueuesFixedUpdateFunc.Clear();
            noActionQueueToExecuteFixedUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueFixedUpdateFunc
        for (int i = 0; i < actionCopiedQueueFixedUpdateFunc.Count; i++)
        {
            actionCopiedQueueFixedUpdateFunc[i].Invoke();
        }
    }

See More Examples