System.Collections.Generic.List.Add(System.Tuple)

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

1378 Examples 7

19 Source : StringMap.cs
with MIT License
from 0x0ade

public List<Tuple<string, int>> PromoteRead() {
            lock (Pending) {
                if (Pending.Count == 0)
                    return Dummy<Tuple<string, int>>.EmptyList;

                List<Tuple<string, int>> added = new();
                foreach (string value in Pending) {
                    int id = NextID++;
                    MapRead[id] = value;
                    MappedRead.Add(value);
                    added.Add(Tuple.Create(value, id));
                }
                Pending.Clear();
                return added;
            }
        }

19 Source : PInvokeHooks.cs
with zlib License
from 0x0ade

public static IntPtr SetWindowsHookEx(HookType hookType, HookProc lpfn, IntPtr hMod, uint dwThreadId) {
            // TODO: SetWindowsHookEx currently ignores the module and thread.
            int handle = PInvoke.AllHooks.Count + 1;
            List<Delegate> hooks = PInvoke.Hooks[hookType];
            PInvoke.AllHooks.Add(Tuple.Create<HookType, Delegate, int>(hookType, lpfn, hooks.Count));
            hooks.Add(lpfn);
            XnaToFnaHelper.Log($"[PInvokeHooks] Added global hook #{handle} of type {hookType}");
            return (IntPtr) handle;
        }

19 Source : DataContext.cs
with MIT License
from 0x0ade

public void RegisterHandlersIn(object owner) {
            if (RegisteredHandlers.ContainsKey(owner))
                return;

            List<Tuple<Type, DataHandler>> handlers = RegisteredHandlers[owner] = new();
            List<Tuple<Type, DataFilter>> filters = RegisteredFilters[owner] = new();

            foreach (MethodInfo method in owner.GetType().GetMethods()) {
                if (method.Name == "Handle" || method.Name == "Filter") {
                    ParameterInfo[] args = method.GetParameters();
                    if (args.Length != 2 || !args[0].ParameterType.IsCompatible(typeof(CelesteNetConnection)))
                        continue;

                    Type argType = args[1].ParameterType;
                    if (!argType.IsCompatible(typeof(DataType)))
                        continue;

                    if (method.Name == "Filter") {
                        Logger.Log(LogLevel.VVV, "data", $"Autoregistering filter for {argType}: {method.GetID()}");
                        DataFilter filter = (con, data) => method.Invoke(owner, new object[] { con, data }) as bool? ?? false;
                        filters.Add(Tuple.Create(argType, filter));
                        RegisterFilter(argType, filter);

                    } else {
                        Logger.Log(LogLevel.VVV, "data", $"Autoregistering handler for {argType}: {method.GetID()}");
                        DataHandler handler = (con, data) => method.Invoke(owner, new object[] { con, data });
                        handlers.Add(Tuple.Create(argType, handler));
                        RegisterHandler(argType, handler);
                    }
                }
            }
        }

19 Source : Roomer.cs
with MIT License
from 1upD

public override void Step(AlifeMap map)
        {
            try
            {
                // Mark to discard
                this._completed = true;

                // Local variables
                int spacesOccupied = 0;
                int total = 0;
                List<Tuple<int, int, int>> locationsToMark = new List<Tuple<int, int, int>>();

                for (int z = this.Z; z < this.Z + this.Height; z++)
                {
                    for (int x = this.X + this._x2; x < this.X + this._x1; x++)
                    {
                        for (int y = this.Y + this._y2; y < this.Y + this._y1; y++)
                        {
                            locationsToMark.Add(new Tuple<int, int, int>(x, y, z));
                            bool isSpaceOccupied = map.GetLocation(x, y, z) != null && map.GetLocation(x, y, z) != "";
                            spacesOccupied += isSpaceOccupied ? 1 : 0;
                            total++;
                        }
                    }
                }

                if (spacesOccupied < total / 2 && MustDeploy)
                {
                    log.Debug(string.Format("Roomer deployed: {0} spaces occupied, {1} total.", spacesOccupied, total));
                    log.Debug(string.Format("Roomer deployed at x: {0} y: {1} z: {2}", this.X, this.Y, this.Z));
                    foreach (var tuple in locationsToMark)
                    {
                        map.MarkLocation(this.Style, tuple.Item1, tuple.Item2, tuple.Item3);
                    }
                } else
                {
                    log.Debug(string.Format("Roomer did not deploy. {0} spaces occupied, {1} total.", spacesOccupied, total));
                }

            }
            catch (Exception e)
            {
                log.Error("Error in Roomer Step function: ", e);
            }

        }

19 Source : Server.cs
with MIT License
from 1ZouLTReX1

private void OnUserConnect(Socket newConnection)
    {
        User usr = new User(newConnection);

        ushort newPlayerID = GetPlayerId();
        // Instantiate at the main thread, not here.
        lock (instantiateJobs)
        {
            instantiateJobs.Add(Tuple.Create(usr, newPlayerID));
        }

        Console.WriteLine("Client Connected, Given Player ID: " + newPlayerID);
        Console.WriteLine("Player Count: " + (MaximumPlayers - playerIdList.Count) + " / " + MaximumPlayers);

        // Send to the connected client his new replacedigned ID.
        BeginSend(usr, WelcomeMessage.Serialize(newPlayerID));

        clients.Add(newConnection, usr);

        InputsOG.Add(newConnection);
        lock (OutputsOG)
        {
            OutputsOG.Add(newConnection);
        }
    }

19 Source : RedisTransaction.cs
with MIT License
from 2881099

void OnTransactionQueued<T>(RedisCommand<T> command, string response)
        {
            if (_connector.IsPipelined)
                _pipeCommands.Add(Tuple.Create(command.Command, command.Arguments));
            else
                OnTransactionQueued(command.Command, command.Arguments, response);
        }

19 Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension

private async void ButtonApply_Click(object sender, RoutedEventArgs e)
        {
            List<Tuple<int, double>> ToSend = new List<Tuple<int, double>>();

            foreach (KeyValuePair<int, double> kvp in CurrentSettings)
            {
                double newval;

                if (!double.TryParse(SettingsBoxes[kvp.Key].Text, System.Globalization.NumberStyles.Float, Util.Constants.DecimalParseFormat, out newval))
                {
                    MessageBox.Show($"Value \"{SettingsBoxes[kvp.Key].Text}\" is invalid for Setting \"{Util.GrblCodeTranslator.Settings[kvp.Key].Item1}\"");
                    return;
                }

                if (newval == kvp.Value)
                    continue;

                ToSend.Add(new Tuple<int, double>(kvp.Key, newval));
            }

            if (SendLine == null)
                return;

            foreach (Tuple<int, double> setting in ToSend)
            {
                SendLine.Invoke($"${setting.Item1}={setting.Item2.ToString(Util.Constants.DecimalOutputFormat)}");
                CurrentSettings[setting.Item1] = setting.Item2;
                await Task.Delay(Properties.Settings.Default.SettingsSendDelay);
            }
        }

19 Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void ButtonGrblExport_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("This will export the currently displayed settings to a file - even any modified values that you have entered.  If you need to export the settings before modifications, please export before changing.  Continue To Export?", "Important", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            { // YES - Export               
                SaveFileDialog exportFileName = new SaveFileDialog();
                exportFileName.Filter = "Text File (*.txt)|*.txt";
                exportFileName.replacedle = "Save exported GRBL Settings";
                exportFileName.FileName = "Exported_GRBL_Settings.txt";

                if (exportFileName.ShowDialog() == true)
                {
                    List<Tuple<int, double>> ToExport = new List<Tuple<int, double>>();
                    foreach (KeyValuePair<int, double> kvp in CurrentSettings)
                    {
                        ToExport.Add(new Tuple<int, double>(kvp.Key, kvp.Value));
                    }

                    using (StreamWriter sw = new StreamWriter(exportFileName.FileName))
                    {
                        sw.WriteLine("{0,-10} {1,-10} {2,-18} {3, -35}", "Setting", "Value", "Units", "Description");

                        foreach (Tuple<int, double> setting in ToExport)
                        // setting.Item1 = GRBL Code, setting.Item2 = Setting Value, Util.GrblCodeTranslator.Settings[setting.Item1].Item1 = Setting Description, Util.GrblCodeTranslator.Settings[setting.Item1].Item2 = Units
                        {
                            sw.WriteLine("{0,-10} {1,-10} {2,-18} {3, -35}", "$" + setting.Item1, setting.Item2.ToString(Util.Constants.DecimalOutputFormat), Util.GrblCodeTranslator.Settings[setting.Item1].Item2, Util.GrblCodeTranslator.Settings[setting.Item1].Item1);
                        }
                        MessageBox.Show("Settings Exported to " + exportFileName.FileName, "Exported GRBL Settings", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            else
            { // NO
                return;
            }
        }

19 Source : MainWindow.xaml.Macros.cs
with MIT License
from 3RD-Dimension

private void ButtonAddMacro_Click(object sender, RoutedEventArgs e)
		{
			Macros.Add(new Tuple<string, string, bool>("New Macro", "", false));
			RefreshMacroButtons();
		}

19 Source : MainWindow.xaml.Macros.cs
with MIT License
from 3RD-Dimension

private void LoadMacros()
		{
			Macros.Clear();

			var regexMacro = new Regex("([^:;]+):([^:;]+)(:E)?;");

			foreach (System.Text.RegularExpressions.Match m in regexMacro.Matches(Properties.Settings.Default.Macros))
			{
				Macros.Add(new Tuple<string, string, bool>(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Success));
			}

			RefreshMacroButtons();
		}

19 Source : ServerInformation.cs
with Apache License 2.0
from AantCoder

public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
        {
            lock (context.Player)
            {
                switch (packet.Value)
                {
                    case (long)ServerInfoType.Full:
                        {
                            var result = GetModelInfo(context.Player);
                            return result;
                        }

                    case (long)ServerInfoType.SendSave:
                        {
                            if (context.PossiblyIntruder)
                            {
                                context.Disconnect("Possibly intruder");
                                return null;
                            }
                            var result = new ModelInfo();
                            //передача файла игры, для загрузки WorldLoad();
                            // файл передать можно только в том случае если файлы прошли проверку

                            //!Для Pvp проверка нужна всегда, в PvE нет
                            if (ServerManager.ServerSettings.IsModsWhitelisted)
                            {
                                if ((int)context.Player.ApproveLoadWorldReason > 0)
                                {
                                    context.Player.ExitReason = DisconnectReason.FilesMods;
                                    Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
                                    result.SaveFileData = null;
                                    return result;
                                }
                            }

                            result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);

                            if (result.SaveFileData != null)
                            {
                                if (context.Player.MailsConfirmationSave.Count > 0)
                                {
                                    for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++) 
                                        context.Player.MailsConfirmationSave[i].NeedSaveGame = false;

                                    Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
                                    //Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
                                    //Отправляем письма ещё раз
                                    if (context.Player.Mails.Count == 0)
                                    {
                                        context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
                                    }
                                    else
                                    {
                                        var ms = context.Player.MailsConfirmationSave
                                            .Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
                                            .ToList();
                                        context.Player.Mails.AddRange(ms);
                                    }
                                    Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
                                }
                            }
                            Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");

                            return result;
                        }

                    case (long)ServerInfoType.FullWithDescription:
                        {
                            var result = GetModelInfo(context.Player);
                            //result.Description = "";
                            var displayAttributes = new List<Tuple<int, string>>();

                            foreach (var prop in typeof(ServerSettings).GetFields())
                            {
                                var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
                                if (attribute is null || !prop.IsPublic)
                                {
                                    continue;
                                }

                                var dispAtr = (DisplayAttribute)attribute;
                                var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
                                strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
                                var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
                                displayAttributes.Add(Tuple.Create(order, strvalue));
                            }

                            var sb = new StringBuilder();
                            var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
                            foreach (var prop in sorte)
                            {
                                sb.AppendLine(prop);
                            }

                            //result.Description = sb.ToString();
                            return result;
                        }
                    case (long)ServerInfoType.Short:
                    default:
                        {
                            // краткая (зарезервированно, пока не используется) fullInfo = false
                            var result = new ModelInfo();
                            return result;
                        }
                }
            }
        }

19 Source : SceneInfoUtils.cs
with Apache License 2.0
from abist-co-ltd

private static void RefreshCachedTypes()
        {
            if (EditorApplication.isCompiling || BuildPipeline.isBuildingPlayer)
            {   // Don't refresh cached types if we're in the middle of something important
                return;
            }

            cachedComponentTypes.Clear();

            foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
            {
                foreach (Type t in replacedembly.GetTypes().Where(t => t.IsSubclreplacedOf(typeof(Component))))
                {
                    foreach (FieldInfo f in t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                    {
                        if (fieldTypesToSearch.Contains(f.FieldType))
                        {
                            cachedComponentTypes.Add(new Tuple<Type, FieldInfo>(t, f));
                        }
                    }
                }
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

public virtual void Register(GameObject listener)
        {
            // Because components on an object can change during its lifetime, we can't enumerate all handlers on an object 
            // at this point in time and register them via the new API.
            // This forces us to store an object and use ExecuteEvents traversal at time of handling events.
            if (eventExecutionDepth == 0)
            {
                if (!EventListeners.Contains(listener))
                {
                    // Due to how events are sent to game objects, if any of registered handlers sits on a 
                    // registered object it will receive any event preplaceded to this object.
                    // We need to mark such handlers, so they don't receive their events twice.
                    // It can be checked in HandleEvent with less code, but this becomes a 
                    // performance bottleneck with many handlers in the system

                    bool report = false;
                    foreach (var typeEntry in EventHandlersByType)
                    {
                        for (int index = 0; index < typeEntry.Value.Count; index++)
                        {
                            var handlerEntry = typeEntry.Value[index];

                            var comp = handlerEntry.handler as Component;

                            if (comp != null && comp.gameObject == listener)
                            {
                                handlerEntry.parentObjectIsInObjectCollection = true;
                                typeEntry.Value[index] = handlerEntry;
                                report = true;
                            }
                        }
                    }

                    if (report)
                    {
                        WarnAboutConflictingApis(listener.name);
                    }

                    EventListeners.Add(listener);
                }
            }
            else
            {
                postponedObjectActions.Add(Tuple.Create(Action.Add, listener));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

public virtual void Unregister(GameObject listener)
        {
            if (eventExecutionDepth == 0)
            {
                if (EventListeners.Contains(listener))
                {
                    // Reset cached flags in handler collection as object will not intercept the events anymore.
                    // This is a slow loop, which is here to maintain backward compatibility and enable co-existing of
                    // new and old API.
                    foreach (var typeEntry in EventHandlersByType)
                    {
                        for (int index = 0; index < typeEntry.Value.Count; index++)
                        {
                            var handlerEntry = typeEntry.Value[index];

                            // if cache flag is true, handler is guaranteed to be a unity component.
                            if (handlerEntry.parentObjectIsInObjectCollection && (handlerEntry.handler as Component).gameObject == listener)
                            {
                                // Don't need to report, because it was reported during registration
                                handlerEntry.parentObjectIsInObjectCollection = false;
                                typeEntry.Value[index] = handlerEntry;
                            }
                        }
                    }

                    EventListeners.Remove(listener);
                }
            }
            else
            {
                postponedObjectActions.Add(Tuple.Create(Action.Remove, listener));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

private void UnregisterHandler(Type handlerType, IEventSystemHandler handler)
        {
            if (eventExecutionDepth == 0)
            {
                RemoveHandlerFromMap(handlerType, handler);
            }
            else
            {
                postponedActions.Add(Tuple.Create(Action.Remove, handlerType, handler));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

private void RegisterHandler(Type handlerType, IEventSystemHandler handler)
        {
            if (eventExecutionDepth == 0)
            {
                AddHandlerToMap(handlerType, handler);
            }
            else
            {
                postponedActions.Add(Tuple.Create(Action.Add, handlerType, handler));
            }
        }

19 Source : GroupingByFeature.cs
with MIT License
from ABTSoftware

public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
        {
            var temp = examples.SelectMany(pair =>
            {
                var l = new List<Tuple<Features, Example>>();
                pair.Value.Features.ForEach(feature => l.Add(new Tuple<Features, Example>(feature, pair.Value)));
                return l;
            });
            
            var groups = temp.OrderBy(pair => pair.Item1.ToString()).GroupBy(pair => pair.Item1);

            var result = new ObservableCollection<TileViewModel>();
            foreach (IGrouping<Features, Tuple<Features, Example>> pairs in groups)
            {
                result.Add(new TileViewModel
                {
                    TileDataContext = new EverythingGroupViewModel {GroupingName = pairs.Key.ToString()}
                });
                foreach (var example in pairs.Select(x => x.Item2))
                {
                    result.Add(new TileViewModel { TileDataContext = example });
                }
            }

            return result;
        }

19 Source : AllegianceHierarchy.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, AllegianceHierarchy hierarchy)
        {
            // ushort - recordCount - Number of character allegiance records
            // ushort - oldVersion = 0x000B - Defines which properties are available. 0x000B seems to be the latest version which includes all properties.
            // Dictionary<ObjectID, AllegianceOfficerLevel> - officers - Taking a guess on these values. Guessing they may only be valid for Monarchs
            //                                                           A list of officers and their officer levels?
            // List<string> - officerreplacedles - Believe these may preplaced in the current officer replacedle list. Guessing they may only be valid on Monarchs.
            // uint - monarchBroadcastTime - May only be valid for Monarchs/Speakers?
            // uint - monarchBroadcastsToday - May only be valid for Monarchs/Speakers?
            // uint - spokesBroadcastTime - May only be valid for Monarchs/Speakers?
            // uint - spokesBroadcastsToday - May only be valid for Monarchs/Speakers?
            // string - motd - Text for current Message of the Day. May only be valid for Monarchs/Speakers?
            // string - motdSetBy - Who set the current Message of the Day. May only be valid for Monarchs/Speakers?
            // uint - chatRoomID - allegiance chat channel number
            // Position - bindpoint - Location of monarchy bindpoint
            // string - allegianceName - The name of the allegiance.
            // uint - nameLastSetTime - Time name was last set. Seems to count upward for some reason.
            // bool - isLocked - Whether allegiance is locked.
            // int - approvedVreplacedal - ??
            // AllegianceData - monarchData - Monarch's data

            // records: vector of length recordCount - 1
            // ObjectID - treeParent - The ObjectID for the parent character to this character. Used by the client to decide how to build the display in the Allegiance tab. 1 is the monarch.
            // AllegianceData - allegianceData

            // recordCount = Monarch + Patron + Vreplacedals?
            // 2 in data for small allegiances?
            ushort recordCount = 0;
            ushort oldVersion = 0x000B;
            var officers = new Dictionary<ObjectGuid, AllegianceOfficerLevel>();
            var officerreplacedles = new List<string>();
            uint monarchBroadcastTime = 0;
            uint monarchBroadcastsToday = 0;
            uint spokesBroadcastTime = 0;
            uint spokesBroadcastsToday = 0;
            var motd = "";
            var motdSetBy = "";
            uint chatRoomID = 0;
            var bindPoint = new Position();
            var allegianceName = "";
            uint nameLastSetTime = 0;
            bool isLocked = false;
            int approvedVreplacedal = 0;
            AllegianceData monarchData = null;
            List<Tuple<ObjectGuid, AllegianceData>> records = null;

            var allegiance = hierarchy.Profile.Allegiance;
            var node = hierarchy.Profile.Node;

            if (allegiance != null && node != null)
            {
                // only send these to monarch?
                //foreach (var officer in allegiance.Officers)
                    //officers.Add(officer.Key, (AllegianceOfficerLevel)officer.Value.Player.AllegianceOfficerRank);

                // not in retail packets, breaks decal
                /*if (allegiance.HasCustomreplacedles)
                {
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Speaker));
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Seneschal));
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Castellan));
                }*/

                allegianceName = allegiance.AllegianceName ?? allegiance.Monarch.Player.Name;
                //motd = allegiance.AllegianceMotd ?? "";
                //motdSetBy = allegiance.AllegianceMotdSetBy ?? "";
                motd = "";          // fixes decal AllegianceUpdate parsing
                motdSetBy = "";
                chatRoomID = allegiance.Biota.Id;

                if (allegiance.Sanctuary != null)
                    bindPoint = allegiance.Sanctuary;

                // aclogview (verify):
                // i == 0 : monarch (no guid)
                // i == 1 : patron
                // i == 2 : peer?
                // i  > 2 : vreplacedals

                // peers = others with the same patron?

                recordCount = 1;    // monarch
                if (node.Patron != null && !node.Patron.IsMonarch)  // patron
                    recordCount++;
                if (!node.IsMonarch)    // self
                    recordCount++;
                if (node.TotalVreplacedals > 0)  // vreplacedals
                {
                    recordCount += (ushort)node.TotalVreplacedals;
                }
                //Console.WriteLine("Records: " + recordCount);

                // monarch
                monarchData = new AllegianceData(allegiance.Monarch);

                if (recordCount > 1)
                {
                    records = new List<Tuple<ObjectGuid, AllegianceData>>();

                    // patron
                    if (node.Patron != null && !node.Patron.IsMonarch)
                    {
                        records.Add(new Tuple<ObjectGuid, AllegianceData>(node.Monarch.PlayerGuid, new AllegianceData(node.Patron)));
                    }

                    // self
                    if (!node.IsMonarch)
                        records.Add(new Tuple<ObjectGuid, AllegianceData>(node.Patron.PlayerGuid, new AllegianceData(node)));

                    // vreplacedals
                    if (node.TotalVreplacedals > 0)
                    {
                        foreach (var vreplacedal in node.Vreplacedals.Values)
                            records.Add(new Tuple<ObjectGuid, AllegianceData>(node.PlayerGuid, new AllegianceData(vreplacedal)));
                    }
                }
            }

            writer.Write(recordCount);
            writer.Write(oldVersion);
            writer.Write(officers);
            writer.Write(officerreplacedles);
            writer.Write(monarchBroadcastTime);
            writer.Write(monarchBroadcastsToday);
            writer.Write(spokesBroadcastTime);
            writer.Write(spokesBroadcastsToday);
            writer.WriteString16L(motd);
            writer.WriteString16L(motdSetBy);
            writer.Write(chatRoomID);
            writer.Write(bindPoint);
            writer.WriteString16L(allegianceName);
            writer.Write(nameLastSetTime);
            writer.Write(Convert.ToUInt32(isLocked));
            writer.Write(approvedVreplacedal);

            if (monarchData != null)
                writer.Write(monarchData);

            if (records != null)
                writer.Write(records);
        }

19 Source : OutputManagerL0.cs
with MIT License
from actions

private TestHostContext Setup(
            [CallerMemberName] string name = "",
            IssueMatchersConfig matchers = null,
            ContainerInfo jobContainer = null,
            ContainerInfo stepContainer = null)
        {
            matchers?.Validate();

            _onMatcherChanged = null;
            _issues = new List<Tuple<DTWebApi.Issue, string>>();
            _messages = new List<string>();
            _commands = new List<string>();

            var hostContext = new TestHostContext(this, name);

            _variables = new Variables(hostContext, new Dictionary<string, DTWebApi.VariableValue>());

            _executionContext = new Mock<IExecutionContext>();
            _executionContext.Setup(x => x.Global)
                .Returns(new GlobalContext
                {
                    Container = jobContainer,
                    Variables = _variables,
                    WriteDebug = true,
                });
            _executionContext.Setup(x => x.GetMatchers())
                .Returns(matchers?.Matchers ?? new List<IssueMatcherConfig>());
            _executionContext.Setup(x => x.Add(It.IsAny<OnMatcherChanged>()))
                .Callback((OnMatcherChanged handler) =>
                {
                    _onMatcherChanged = handler;
                });
            _executionContext.Setup(x => x.AddIssue(It.IsAny<DTWebApi.Issue>(), It.IsAny<string>()))
                .Callback((DTWebApi.Issue issue, string logMessage) =>
                {
                    _issues.Add(new Tuple<DTWebApi.Issue, string>(issue, logMessage));
                });
            _executionContext.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
                .Callback((string tag, string message) =>
                {
                    _messages.Add($"{tag}{message}");
                    hostContext.GetTrace().Info($"{tag}{message}");
                });

            _commandManager = new Mock<IActionCommandManager>();
            _commandManager.Setup(x => x.TryProcessCommand(It.IsAny<IExecutionContext>(), It.IsAny<string>(), It.IsAny<ContainerInfo>()))
                .Returns((IExecutionContext executionContext, string line, ContainerInfo container) =>
                {
                    if (line.IndexOf("##[some-command]") >= 0)
                    {
                        _commands.Add(line);
                        return true;
                    }

                    return false;
                });

            _outputManager = new OutputManager(_executionContext.Object, _commandManager.Object, stepContainer);
            return hostContext;
        }

19 Source : SetEnvFileCommandL0.cs
with MIT License
from actions

private TestHostContext Setup([CallerMemberName] string name = "")
        {
            _issues = new List<Tuple<DTWebApi.Issue, string>>();

            var hostContext = new TestHostContext(this, name);

            // Trace
            _trace = hostContext.GetTrace();

            // Directory for test data
            var workDirectory = hostContext.GetDirectory(WellKnownDirectory.Work);
            ArgUtil.NotNullOrEmpty(workDirectory, nameof(workDirectory));
            Directory.CreateDirectory(workDirectory);
            _rootDirectory = Path.Combine(workDirectory, nameof(SetEnvFileCommandL0));
            Directory.CreateDirectory(_rootDirectory);

            // Execution context
            _executionContext = new Mock<IExecutionContext>();
            _executionContext.Setup(x => x.Global)
                .Returns(new GlobalContext
                {
                    EnvironmentVariables = new Dictionary<string, string>(VarUtil.EnvironmentVariableKeyComparer),
                    WriteDebug = true,
                });
            _executionContext.Setup(x => x.AddIssue(It.IsAny<DTWebApi.Issue>(), It.IsAny<string>()))
                .Callback((DTWebApi.Issue issue, string logMessage) =>
                {
                    _issues.Add(new Tuple<DTWebApi.Issue, string>(issue, logMessage));
                    var message = !string.IsNullOrEmpty(logMessage) ? logMessage : issue.Message;
                    _trace.Info($"Issue '{issue.Type}': {message}");
                });
            _executionContext.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
                .Callback((string tag, string message) =>
                {
                    _trace.Info($"{tag}{message}");
                });

            // SetEnvFileCommand
            _setEnvFileCommand = new SetEnvFileCommand();
            _setEnvFileCommand.Initialize(hostContext);

            return hostContext;
        }

19 Source : IntraLineViewportAdornmentManager.cs
with MIT License
from Actipro

private void OnAdornmentRemoved(IAdornment adornment) {
			if (adornment != null) {
				var element = adornment.VisualElement as AdornmentElement;
				if (element != null) {
					cachedElements.Add(Tuple.Create(new WeakReference(adornment.Tag), element));
					element.Tag = null;
				}
			}
		}

19 Source : SquareFinder.cs
with GNU General Public License v3.0
from AdamWhiteHat

public Tuple<BigInteger, BigInteger> CalculateAlgebraicSide(CancellationToken cancelToken)
		{
			bool solutionFound = false;

			RootsOfS.AddRange(relationsSet.Select(rel => new Tuple<BigInteger, BigInteger>(rel.A, rel.B)));

			PolynomialRing = new List<Polynomial>();
			foreach (Relation rel in relationsSet)
			{
				// poly(x) = A + (B * x)
				Polynomial newPoly =
					new Polynomial(
						new Term[]
						{
							new Term( rel.B, 1),
							new Term( rel.A, 0)
						}
					);

				PolynomialRing.Add(newPoly);
			}

			if (cancelToken.IsCancellationRequested) { return new Tuple<BigInteger, BigInteger>(1, 1); }

			BigInteger m = polyBase;
			Polynomial f = monicPoly.Clone();
			int degree = f.Degree;

			Polynomial fd = Polynomial.GetDerivativePolynomial(f);
			Polynomial d3 = Polynomial.Product(PolynomialRing);
			Polynomial derivativeSquared = Polynomial.Square(fd);
			Polynomial d2 = Polynomial.Multiply(d3, derivativeSquared);
			Polynomial dd = Polynomial.Field.Modulus(d2, f);

			// Set the result to S
			S = dd;
			SRingSquare = dd;
			TotalS = d2;

			algebraicNormCollection = relationsSet.Select(rel => rel.AlgebraicNorm);
			AlgebraicProduct = d2.Evaluate(m);
			AlgebraicSquare = dd.Evaluate(m);
			AlgebraicProductModF = dd.Evaluate(m).Mod(N);
			AlgebraicSquareResidue = AlgebraicSquare.Mod(N);

			IsAlgebraicIrreducible = IsPrimitive(algebraicNormCollection); // Irreducible check
			IsAlgebraicSquare = AlgebraicSquareResidue.IsSquare();

			List<BigInteger> primes = new List<BigInteger>();
			List<Tuple<BigInteger, BigInteger>> resultTuples = new List<Tuple<BigInteger, BigInteger>>();

			BigInteger primeProduct = 1;


			BigInteger lastP = ((N * 3) + 1).NthRoot(3) + 1; //N / N.ToString().Length; //((N * 3) + 1).NthRoot(3); //gnfs.QFB.Select(fp => fp.P).Max();

			int attempts = 7;

			while (!solutionFound && attempts > 0)
			{
				if (primes.Count > 0 && resultTuples.Count > 0)
				{
					primes.Remove(primes.First());
					resultTuples.Remove(resultTuples.First());
				}

				do
				{
					if (cancelToken.IsCancellationRequested) { return new Tuple<BigInteger, BigInteger>(1, 1); }

					lastP = PrimeFactory.GetNextPrime(lastP + 1);

					Tuple<BigInteger, BigInteger> lastResult = AlgebraicSquareRoot(f, m, degree, dd, lastP);

					if (lastResult.Item1 != 0)
					{
						primes.Add(lastP);
						resultTuples.Add(lastResult);
					}
				}
				while (primes.Count < degree);


				if (primes.Count > degree)
				{
					primes.Remove(primes.First());
					resultTuples.Remove(resultTuples.First());
				}

				primeProduct = (resultTuples.Select(tup => BigInteger.Min(tup.Item1, tup.Item2)).Product());

				if (primeProduct < N)
				{
					continue;
				}

				if (cancelToken.IsCancellationRequested) { return new Tuple<BigInteger, BigInteger>(1, 1); ; }

				var temp = resultTuples.Select(tup => new List<BigInteger>() { tup.Item1, tup.Item2 });

				IEnumerable<IEnumerable<BigInteger>> permutations =
					Combinatorics.CartesianProduct(temp);

				BigInteger algebraicSquareRoot = 1;

				BigInteger min;
				BigInteger max;
				BigInteger A;
				BigInteger B;
				BigInteger U;
				BigInteger V;
				BigInteger P = 0;
				BigInteger Q;

				foreach (List<BigInteger> X in permutations)
				{
					if (cancelToken.IsCancellationRequested) { return new Tuple<BigInteger, BigInteger>(1, 1); }

					algebraicSquareRoot = FiniteFieldArithmetic.ChineseRemainder(N, X, primes);

					min = BigInteger.Min(RationalSquareRootResidue, algebraicSquareRoot);
					max = BigInteger.Max(RationalSquareRootResidue, algebraicSquareRoot);

					A = max + min;
					B = max - min;

					U = GCD.FindGCD(N, A);
					V = GCD.FindGCD(N, B);

					if (U > 1 && U != N)
					{
						P = U;
						solutionFound = true;
					}
					else if (V > 1 && V != N)
					{
						P = V;
						solutionFound = true;
					}

					if (solutionFound)
					{
						BigInteger rem;
						BigInteger other = BigInteger.DivRem(N, P, out rem);

						if (rem != 0)
						{
							solutionFound = false;
						}
						else
						{
							Q = other;
							AlgebraicResults = X;
							AlgebraicSquareRootResidue = algebraicSquareRoot;
							AlgebraicPrimes = primes;

							return new Tuple<BigInteger, BigInteger>(P, Q);
						}
					}
				}

				if (!solutionFound)
				{
					gnfs.LogFunction($"No solution found amongst the algebraic square roots {{ {string.Join(", ", resultTuples.Select(tup => $"({ tup.Item1}, { tup.Item2})"))} }} mod primes {{ {string.Join(", ", primes.Select(p => p.ToString()))} }}");

					attempts--;
				}
			}

			return new Tuple<BigInteger, BigInteger>(1, 1);
		}

19 Source : NoteReplication.cs
with MIT License
from Adoxio

public override void Created()
		{
			var ownerid = Source.GetAttributeValue<EnreplacedyReference>("objectid");

			if (ownerid == null || ownerid.LogicalName != "adx_webfile")
			{
				return;
			}

			var ownerFile = Context.CreateQuery("adx_webfile").FirstOrDefault(f => f.GetAttributeValue<Guid?>("adx_webfileid") == ownerid.Id);

			if (ownerFile == null)
			{
				return;
			}

			var subscribedFiles = ownerFile.GetRelatedEnreplacedies(Context, "adx_webfile_masterwebfile", EnreplacedyRole.Referenced).ToList();
			
			if (!subscribedFiles.Any())
			{
				return;
			}

			var newNotes = new List<Tuple<Guid, Enreplacedy>>();
			var replication = (HttpContext.Current.Application[BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>
				?? (Dictionary<string, Tuple<Guid, Guid>[]>)(HttpContext.Current.Application[BlobReplicationKey] = new Dictionary<string, Tuple<Guid, Guid>[]>()));

			foreach (var file in subscribedFiles)
			{
				var notes = file.GetRelatedEnreplacedies(Context, "adx_webfile_Annotations");

				if (notes.Any())
				{
					// This file already has attachments, leave it alone.
					continue;
				}

				var replicatedNote = new Enreplacedy("annotation");

				replicatedNote.SetAttributeValue("doreplacedentbody", Source.GetAttributeValue("doreplacedentbody"));
				replicatedNote.SetAttributeValue("filename", Source.GetAttributeValue("filename"));
				replicatedNote.SetAttributeValue("mimetype", Source.GetAttributeValue("mimetype"));
				replicatedNote.SetAttributeValue("subject", Source.GetAttributeValue("subject"));
				replicatedNote.SetAttributeValue("notetext", Source.GetAttributeValue("notetext"));
				replicatedNote.SetAttributeValue("isdoreplacedent", Source.GetAttributeValue("isdoreplacedent") ?? false);
				replicatedNote.SetAttributeValue("objectid", new EnreplacedyReference("adx_webfile", file.Id));
				replicatedNote.SetAttributeValue("objecttypecode", "adx_webfile");

				newNotes.Add(new Tuple<Guid, Enreplacedy>(file.GetAttributeValue<EnreplacedyReference>("adx_websiteid").Id, replicatedNote));
				Context.AddObject(replicatedNote);
			}

			Context.SaveChanges();
			
			replication[Source.Id.ToString("N")] = newNotes.Select(n => new Tuple<Guid, Guid>(n.Item1, n.Item2.Id)).ToArray();
		}

19 Source : CrmChartBuilder.cs
with MIT License
from Adoxio

private void PopulateAttributeMetadataCacheForEnreplacedyLinkAttributes(IEnumerable<Link> links)
		{
			if (links == null)
			{
				return;
			}

			foreach (var link in links.Where(l => l.Attributes != null && l.Attributes.Any()))
			{
				if (this.enreplacedyMetadataCache.ContainsKey(link.Name))
				{
					var enreplacedyMetadata = this.enreplacedyMetadataCache[link.Name];

					foreach (var attribute in link.Attributes)
					{
						var attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute.Name);

						if (attributeMetadata == null)
						{
							continue;
						}

						this.attributeMetadataCache.Add(new Tuple<string, string, AttributeMetadata>(link.Name, attribute.Name, attributeMetadata));
					}
				}

				this.PopulateAttributeMetadataCacheForEnreplacedyLinkAttributes(link.Links);
			}
		}

19 Source : RmCommand.cs
with MIT License
from Adoxio

private static List<Tuple<string, string>> RemoveFiles(ICommandContext commandContext)
		{
			var errors = new List<Tuple<string, string>>();

			var targetHashes = (commandContext.Parameters["targets[]"] ?? string.Empty).Split(',');

			if (!targetHashes.Any())
			{
				return errors;
			}

			var portal = commandContext.CreatePortalContext();
			var website = portal.Website.ToEnreplacedyReference();
			var security = commandContext.CreateSecurityProvider();
			var dataServiceProvider = commandContext.CreateDependencyProvider().GetDependency<ICmsDataServiceProvider>();

			foreach (var targetHash in targetHashes)
			{
				var serviceContext = commandContext.CreateServiceContext();

				Enreplacedy target;

				if (!TryGetTargetEnreplacedy(serviceContext, targetHash, website, out target))
				{
					errors.Add(new Tuple<string, string>(targetHash, ResourceManager.GetString("Unable_To_Retrieve_Target_Enreplacedy_For_Given_Hash_Error")));

					continue;
				}

				try
				{
					OrganizationServiceContextInfo serviceContextInfo;
					EnreplacedySetInfo enreplacedySetInfo;

					if (dataServiceProvider != null
					    && OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), out serviceContextInfo)
					    && serviceContextInfo.EnreplacedySetsByEnreplacedyLogicalName.TryGetValue(target.LogicalName, out enreplacedySetInfo))
					{
						dataServiceProvider.DeleteEnreplacedy(serviceContext, enreplacedySetInfo.Property.Name, target.Id);
					}
					else
					{
						if (!security.Tryreplacedert(serviceContext, target, CrmEnreplacedyRight.Change))
						{
							errors.Add(new Tuple<string, string>(GetDisplayName(target), ResourceManager.GetString("Delete_Permission_Denied_For_Target_Enreplacedy_Error")));

							continue;
						}

						CrmEnreplacedyInactiveInfo inactiveInfo;

						if (CrmEnreplacedyInactiveInfo.TryGetInfo(target.LogicalName, out inactiveInfo))
						{
							serviceContext.SetState(inactiveInfo.InactiveState, inactiveInfo.InactiveStatus, target);
						}
						else
						{
							serviceContext.DeleteObject(target);
							serviceContext.SaveChanges();
						}
					}
				}
				catch (Exception e)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0} {1}", ResourceManager.GetString("Deleting_File_Exception"), e.ToString()));
					errors.Add(new Tuple<string, string>(GetDisplayName(target), e.Message));
				}
			}

			return errors;
		}

19 Source : UploadCommand.cs
with MIT License
from Adoxio

private static void CreateFiles(ICommandContext commandContext, DirectoryUploadInfo uploadInfo, IEnumerable<HttpPostedFile> files, EnreplacedyReference publishingState, out List<string> @select, out List<Tuple<string, string>> errors)
		{
			@select = new List<string>();
			errors = new List<Tuple<string, string>>();
			
			var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies();
			var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
			var website = HttpContext.Current.GetWebsite();

			var location = website.Settings.Get<string>("WebFiles/StorageLocation");

			StorageLocation storageLocation;
			if (!Enum.TryParse(location, true, out storageLocation))
			{
				storageLocation = StorageLocation.CrmDoreplacedent;
			}

			var maxFileSizeErrorMessage = website.Settings.Get<string>("WebFiles/MaxFileSizeErrorMessage");

			var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(),
				storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage);
						
			foreach (var file in files)
			{
				var serviceContext = commandContext.CreateServiceContext();

				try
				{
					var webFile = new Enreplacedy("adx_webfile");

					var fileName = Path.GetFileName(file.FileName);

					webFile.Attributes["adx_name"] = fileName;
					webFile.Attributes["adx_partialurl"] = GetPartialUrlFromFileName(fileName);
					webFile.Attributes["adx_websiteid"] = website.Enreplacedy.ToEnreplacedyReference();
					webFile.Attributes["adx_publishingstateid"] = publishingState;
					webFile.Attributes["adx_hiddenfromsitemap"] = true;
					webFile.Attributes[uploadInfo.WebFileForeignKeyAttribute] = uploadInfo.EnreplacedyReference;

					serviceContext.AddObject(webFile);
					serviceContext.SaveChanges();

					annotationDataAdapter.CreateAnnotation(new Annotation
					{
						Regarding = webFile.ToEnreplacedyReference(),
						FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation)
					}, annotationSettings);

					@select.Add(new DirectoryContentHash(webFile.ToEnreplacedyReference()).ToString());
				}
				catch (Exception e)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception uploading file: {0}",  e.ToString()));

                    errors.Add(new Tuple<string, string>(file.FileName, e.Message));
				}
			}
		}

19 Source : DarksVMRuntime.cs
with GNU General Public License v3.0
from Aekras1a

public void AddMethod(MethodDef method, ScopeBlock rootScope)
        {
            ILBlock entry = null;
            foreach(ILBlock block in rootScope.GetBasicBlocks())
            {
                if(block.Id == 0)
                    entry = block;
                basicBlocks.Add(Tuple.Create(method, block));
            }
            Debug.replacedert(entry != null);
            methodMap[method] = Tuple.Create(rootScope, entry);
        }

19 Source : DarksVMRuntime.cs
with GNU General Public License v3.0
from Aekras1a

public void AddBlock(MethodDef method, ILBlock block)
        {
            basicBlocks.Add(Tuple.Create(method, block));
        }

19 Source : Scanner.cs
with GNU General Public License v3.0
from Aekras1a

private void PopulateResult(MethodDef method)
        {
            if(exclude.Contains(method) || method.DeclaringType.HasGenericParameters)
                return;
            results.Add(Tuple.Create(method, export.Contains(method)));
        }

19 Source : Planet.cs
with The Unlicense
from aeroson

private void GenerateChunks(Stopwatch frameStart, TimeSpan timeBudget)
	{
		MyProfiler.BeginSample("Procedural Planet / Generate chunks / start new");
		if (chunkGenerationCoroutinesInProgress.Count <= 300)
		{
			// start only one new coroutine every frame, so their steps are interleaved
			// we don't want all coroutines to do the same thing at once, because when they all request mesh from GPU at once, they may cause big render thread stall
			while (subdivisonCalculationLast.NumChunksToGenerate > 0)
			{
				ChunkData chunk = subdivisonCalculationLast.GetNextChunkToStartGeneration();
				if (chunk == null) continue;
				if (chunk.GenerationInProgress) continue;
				chunkGenerationCoroutinesInProgress.Add(new Tuple<ChunkData, IEnumerator>(chunk, chunk.StartGenerateCoroutine()));
				break;
			};
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Generate chunks / execution");
		chunkGenerationJustFinished.Clear();
		//do
		{
			for (int i = chunkGenerationCoroutinesInProgress.Count - 1; i >= 0; --i)
			{
				var c = chunkGenerationCoroutinesInProgress[i];
				MyProfiler.BeginSample("Procedural Planet / Generate chunks / execution / MoveNext()");
				bool finishedExecution = !c.Item2.MoveNext();
				MyProfiler.EndSample();
				if (finishedExecution)
				{
					chunkGenerationCoroutinesInProgress.RemoveAt(i);
					chunkGenerationJustFinished.Add(c.Item1);
					considerChunkForCleanup.Add(c.Item1);
				}

				if (frameStart.Elapsed > timeBudget) break;
			}
		}
		// we dont want to execute again, as some coroutines might just be idling, waiting for getMeshDataReadbackRequest.done
		//while (frameStart.Elapsed < timeBudget);
		MyProfiler.EndSample();

		MyProfiler.AddNumberSample("Procedural Planet / Generate chunks / concurrent coroutines", chunkGenerationCoroutinesInProgress.Count);
		MyProfiler.AddNumberSample("Procedural Planet / Generate chunks / to generate", subdivisonCalculationLast.NumChunksToGenerate);
	}

19 Source : ImageProcessing.cs
with GNU General Public License v3.0
from aglab2

public static Bitmap GetEmptied(Bitmap goldStar, int size)
        {
            bool IsTupleValid(Tuple<int, int> t)
            {
                if (t.Item1 < 0 || t.Item1 >= goldStar.Width)
                    return false;

                if (t.Item2 < 0 || t.Item2 >= goldStar.Height)
                    return false;

                return true;
            }

            List<Tuple<int, int>> GetIndices(int x, int y)
            {
                List<Tuple<int, int>> indices = new List<Tuple<int, int>>();
                for (int i = -size; i <= size; i++)
                {
                    for (int j = -size; j <= size; j++)
                    {
                        if (i == 0 && j == 0)
                            continue;

                        var pos = new Tuple<int, int>(x - i, y - j);
                        if (!IsTupleValid(pos))
                            continue;

                        indices.Add(pos);
                    }
                }
                return indices;
            }

            Bitmap darkStar = new Bitmap(goldStar);
            for (int i = 0; i < goldStar.Width; i++)
            {
                for (int j = 0; j < goldStar.Height; j++)
                {
                    var indices = GetIndices(i, j);
                    var alphas = indices.Select(t => goldStar.GetPixel(t.Item1, t.Item2).A);
                    var visibleCount = alphas.Where(a => a == 0xff).Count();
                    var invisibleCount = alphas.Count() - visibleCount;
                    var totalCount = indices.Count();

                    Color c = goldStar.GetPixel(i, j);
                    if (invisibleCount == totalCount)
                    {
                        darkStar.SetPixel(i, j, c);
                    }
                    else
                    {
                        darkStar.SetPixel(i, j, Color.FromArgb((int) ((float) invisibleCount / (float) alphas.Count() * 255), c.R, c.G, c.B));
                    }
                }
            }
            return darkStar;
        }

19 Source : ValidationComponent.cs
with GNU General Public License v3.0
from agolaszewski

public IValidateComponent<T> Add(Func<T, bool> fn, Func<T, string> errorMessageFn)
        {
            _validators.Add(new Tuple<Func<T, bool>, Func<T, string>>(fn, errorMessageFn));
            return this;
        }

19 Source : ValidationComponent.cs
with GNU General Public License v3.0
from agolaszewski

public IValidateComponent<T> Add(Func<T, bool> fn, string errorMessage)
        {
            _validators.Add(new Tuple<Func<T, bool>, Func<T, string>>(fn, value => { return errorMessage; }));
            return this;
        }

19 Source : Forwarder.cs
with Apache License 2.0
from airbus-cert

public void AddFilter(string fieldName, string fieldValue)
        {
            this.Filters.Add(Tuple.Create(fieldName, fieldValue));
        }

19 Source : Camera.cs
with MIT License
from Alan-FGR

public List<Tuple<Texture2D, BlendState>> Render()
   {
      UpdateBeforeDrawing();

      var viewportSize = Graphics.Viewport.Size().DividedBy(pixelSize);

      List<Tuple<Texture2D, BlendState>> retList = new List<Tuple<Texture2D, BlendState>>();

      //render all targets
      for (var index = 0; index < renderTargets_.Count; index++)
      {
         CameraRenderTarget target = renderTargets_[index];
         
         target.PrepareForDrawing(viewportSize);
         
         var layers = renderLayers_.Count > 0 ? renderLayers_ : DEFAULT_RENDER_PATH;

         //can't get ordered ienumerator :( TODO make extension or subclreplaced
         var queue = new SimplePriorityQueue<RenderLayer>();
         foreach (RenderLayer layer in layers)
         {
            queue.Enqueue(layer, layers.GetPriority(layer));
         }

         while (queue.TryDequeue(out var command))
         {
            if(command.renderTargetIndex == index) //TODO optimize
               command.Draw(this);
         }

         retList.Add(new Tuple<Texture2D, BlendState>(target.renderTarget, target.blendMode));

      }

      return retList;

      //      backBufferEffect_.Projection = globalMatrix;
      //      backBufferEffect_.Texture = atlas;
      //      backBufferEffect_.TextureEnabled = true;
      //      backBufferEffect_.CurrentTechnique.Preplacedes[0].Apply();

   }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from Albo1125

public void Add(T1 item, T2 item2)
        {
            Add(new Tuple<T1, T2>(item, item2));
        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from Albo1125

public void Add(T1 item, T2 item2, T3 item3)
        {
            Add(new Tuple<T1, T2, T3>(item, item2, item3));
        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from Albo1125

public void Add(T1 item, T2 item2, T3 item3, T4 item4)
        {
            Add(new Tuple<T1, T2, T3, T4>(item, item2, item3, item4));
        }

19 Source : FilesSelfTest.cs
with Apache License 2.0
from aloneguid

private List<Tuple<string, Func<Task>>> FindTestMethods()
      {
         var r = new List<Tuple<string, Func<Task>>>();

         foreach(MethodInfo mi in GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
         {
            Attribute ta = mi.GetCustomAttribute(typeof(TestAttribute));
            if(ta != null)
            {
               // validate
               if(mi.ReturnType != typeof(Task))
                  throw new ApplicationException($"{mi.Name}: return type must be Task");

               if(mi.GetParameters().Length > 0)
                  throw new ApplicationException($"{mi.Name}: parameters are not supported");

               r.Add(new Tuple<string, Func<Task>>(mi.Name, () => (Task)mi.Invoke(this, new object[0])));
            }
         }

         return r;
      }

19 Source : ExtensionsManager.cs
with MIT License
from Analogy-LogViewer

public void RegisterExtension(IreplacedogyExtension extension)
        {
            if (extension == null)
            {
                return;
            }

            registeredExtensions.Add(extension);
            if (extension is IreplacedogyExtensionInPlace inPlaceExtension)
            {
                var columns = inPlaceExtension.GetColumnsInfo();
                foreach (replacedogyColumnInfo column in columns)
                {
                    extensionsDataColumns.Add(
                        new Tuple<IreplacedogyExtension, replacedogyColumnInfo, int>(extension, column, ColumnIndexes));
                    ColumnIndexes++;
                }
            }
        }

19 Source : FilesOperationsUC.cs
with MIT License
from Analogy-LogViewer

public void AppendMessage(replacedogyLogMessage message, string dataSource)
        {
            lock (lockObject)
            {
                Messages.Add(new Tuple<string, replacedogyLogMessage>(dataSource, message));
            }
        }

19 Source : Thread_Info.cs
with MIT License
from Andy53

public List<Tuple<IntPtr, IntPtr>> GetSehChain()
        {
            List<Tuple<IntPtr, IntPtr>> SehPtrs = new List<Tuple<IntPtr, IntPtr>>();
            var pteb = PopulateTEB();
            if (pteb.Error != null)
            {
                throw pteb.Error;
            }

            if(SehChain == null)
            {
                throw new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
            }

            if(X64 == MachineType.x64)
            {
                for (int i = 0; i < SehChain.Count; i++)
                {
                    Tuple<IntPtr, IntPtr> tuple = new Tuple<IntPtr, IntPtr>((IntPtr)BitConverter.ToInt64(SehChain[i].Item1, 0), (IntPtr)BitConverter.ToInt64(SehChain[i].Item2, 0));
                    SehPtrs.Add(tuple);
                }
            }
            else
            {
                for (int i = 0; i < SehChain.Count; i++)
                {
                    Tuple<IntPtr, IntPtr> tuple = new Tuple<IntPtr, IntPtr>((IntPtr)BitConverter.ToInt32(SehChain[i].Item1, 0), (IntPtr)BitConverter.ToInt32(SehChain[i].Item2, 0));
                    SehPtrs.Add(tuple);
                }
            }
            return SehPtrs;
        }

19 Source : UniFiOrchestrator.cs
with MIT License
from anthturner

public IList<Tuple<INetworkedDevice, int>> GeneratePathTo(INetworkedDevice device)
        {
            var list = new List<Tuple<INetworkedDevice, int>>();
            var thisDevice = device;
            while (thisDevice != null)
            {
                var parent = GetParentPortOf(thisDevice);
                if (parent == null)
                    break;
                list.Add(Tuple.Create((INetworkedDevice)parent.Item1, parent.Item2));
                thisDevice = parent.Item1;
            }
            return list;
        }

19 Source : GeneratorContext.cs
with GNU General Public License v3.0
from anydream

public void AddStaticField(string typeName, string sfldName, bool hasRef)
		{
			if (!InitFldsMap.TryGetValue(typeName, out var nameSet))
			{
				nameSet = new List<Tuple<string, bool>>();
				InitFldsMap.Add(typeName, nameSet);
			}
			nameSet.Add(new Tuple<string, bool>(sfldName, hasRef));
		}

19 Source : MethodTable.cs
with GNU General Public License v3.0
from anydream

public void ResolveTable()
		{
			Debug.replacedert(InstGenArgs == null);

			var metDefList = new List<Tuple<string, MethodDef>>();
			var conflictMap = new Dictionary<string, ConflictPair>();
			var nameSet = new HashSet<string>();

			bool thisIsInterface = Def.IsInterface;
			bool thisIsAbstract = Def.IsAbstract;

			StringBuilder sb = new StringBuilder();

			uint lastRid = 0;
			foreach (MethodDef metDef in Def.Methods)
			{
				// 跳过非虚方法
				if (!metDef.IsVirtual)
				{
					// 非虚方法如果存在显式重写则视为错误
					if (metDef.HasOverrides)
					{
						throw new TypeLoadException(
							string.Format("Explicit overridden method must be virtual in type {0}: {1}",
								GetNameKey(),
								metDef.FullName));
					}

					continue;
				}

				if (metDef.Rid != 0)
				{
					Debug.replacedert(lastRid == 0 || lastRid < metDef.Rid);
					lastRid = metDef.Rid;
				}

				// 获得方法签名
				Helper.MethodDefNameKey(sb, metDef, null);
				string metNameKey = sb.ToString();
				sb.Clear();
				nameSet.Add(metNameKey);

				if (thisIsInterface)
				{
					Debug.replacedert(metDef.IsAbstract && metDef.IsNewSlot);
					metDefList.Add(new Tuple<string, MethodDef>(metNameKey, metDef));
				}
				else
				{
					// 特殊处理签名冲突的方法
					if (!conflictMap.TryGetValue(metNameKey, out var confPair))
					{
						confPair = new ConflictPair();
						conflictMap.Add(metNameKey, confPair);
						metDefList.Add(new Tuple<string, MethodDef>(metNameKey, metDef));
					}

					if (metDef.IsNewSlot)
						confPair.NewSlots.Add(metDef);
					else
						confPair.ReuseSlots.Add(metDef);
				}
			}

			if (!thisIsInterface)
			{
				foreach (var item in conflictMap.Where(kvp => !kvp.Value.ContainsConflicts()).ToList())
				{
					conflictMap.Remove(item.Key);
				}
			}

			// 解析基类方法表
			MethodTable baseTable = null;
			if (Def.BaseType != null)
			{
				baseTable = TypeMgr.ResolveMethodTable(Def.BaseType);

				// 继承基类数据
				DerivedTable(baseTable);
			}

			var expOverrides = new List<Tuple<string, MethodDef>>();
			// 解析隐式重写
			foreach (var mereplacedem in metDefList)
			{
				string metNameKey = mereplacedem.Item1;

				if (thisIsInterface)
				{
					// 接口需要合并相同签名的方法
					MethodDef metDef = mereplacedem.Item2;
					var entry = new TableMethodPair(this, metDef);
					MergeInterface(metNameKey, entry);
				}
				else if (conflictMap.TryGetValue(metNameKey, out var confPair))
				{
					Debug.replacedert(confPair.ContainsConflicts());

					// 冲突签名的方法需要先处理重写槽方法, 再处理新建槽方法
					VirtualSlot lastVSlot = null;
					foreach (var metDef in confPair.ReuseSlots)
						lastVSlot = ProcessMethod(metNameKey, metDef, baseTable, expOverrides);

					// 应用重写信息到入口映射
					ApplyVirtualSlot(lastVSlot);

					foreach (var metDef in confPair.NewSlots)
						ProcessMethod(metNameKey, metDef, baseTable, expOverrides);
				}
				else
				{
					MethodDef metDef = mereplacedem.Item2;
					ProcessMethod(metNameKey, metDef, baseTable, expOverrides);
				}
			}
			metDefList = null;
			conflictMap = null;
			baseTable = null;

			// 关联抽象基类未实现的接口
			if (NotImplInterfaces.IsCollectionValid())
			{
				List<string> removedKeys = new List<string>();
				foreach (var kv in NotImplInterfaces)
				{
					string metNameKey = kv.Key;
					var notImplEntries = kv.Value;
					if (SlotMap.TryGetValue(metNameKey, out var vslot))
					{
						vslot.Entries.UnionWith(notImplEntries);
						removedKeys.Add(metNameKey);
						ApplyVirtualSlot(vslot);
					}
				}
				foreach (var key in removedKeys)
					NotImplInterfaces.Remove(key);
			}

			// 关联接口
			if (Def.HasInterfaces)
			{
				foreach (var inf in Def.Interfaces)
				{
					MethodTable infTable = TypeMgr.ResolveMethodTable(inf.Interface);
					foreach (var kv in infTable.SlotMap)
					{
						string metNameKey = kv.Key;
						var infEntries = kv.Value.Entries;

						if (thisIsInterface)
						{
							MergeInterfaces(metNameKey, infEntries);
						}
						else if (nameSet.Contains(metNameKey) &&
								 SlotMap.TryGetValue(metNameKey, out var vslot))
						{
							// 关联当前类型内签名相同的方法
							vslot.Entries.UnionWith(infEntries);
							ApplyVirtualSlot(vslot);
						}
						else
						{
							foreach (var entry in infEntries)
							{
								if (!EntryMap.ContainsKey(entry))
								{
									if (SlotMap.TryGetValue(metNameKey, out vslot))
									{
										// 关联继承链上签名相同的方法
										vslot.Entries.Add(entry);
										ApplyVirtualSlot(vslot);
									}
									else if (thisIsAbstract)
									{
										AddNotImplInterface(metNameKey, entry);
									}
									else
									{
										// 暂时未实现的接口入口
										SetEntryMap(entry, null);
									}
								}
							}
						}
					}
				}
			}

			// 记录显式重写目标以便查重
			var expOverTargets = new HashSet<TableMethodPair>();

			// 解析显式重写
			foreach (var expItem in expOverrides)
			{
				string metNameKey = expItem.Item1;
				MethodDef metDef = expItem.Item2;

				foreach (MethodOverride metOver in metDef.Overrides)
				{
					var overTarget = metOver.MethodDeclaration;
					var overImpl = metOver.MethodBody;

					MethodTable targetTable = TypeMgr.ResolveMethodTable(overTarget.DeclaringType);
					MethodDef targetDef = overTarget.ResolveMethodDef();

					// 验证显式重写目标的正确性
					if (targetDef == null || targetDef.DeclaringType != targetTable.Def)
					{
						throw new TypeLoadException(
							string.Format("Illegal explicit overriding target in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}
					if (!targetDef.IsVirtual)
					{
						throw new TypeLoadException(
							string.Format("Explicit overriding target must be virtual in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}

					var targetEntry = new TableMethodPair(targetTable, targetDef);

					MethodDef implDef = overImpl.ResolveMethodDef();
					Debug.replacedert(metDef == implDef);

					// 同一个类内重复的显式重写, 以及重写存在重写的方法, 视为错误
					if ((targetTable == this && targetDef.HasOverrides) ||
						expOverTargets.Contains(targetEntry))
					{
						throw new TypeLoadException(
							string.Format("Explicit overriding target has been overridden in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}
					expOverTargets.Add(targetEntry);

					if (targetTable.Def.IsInterface)
					{
						// 接口方法显式重写
						ExplicitOverride(targetEntry, metNameKey);
					}
					else
					{
						// 相同类型的需要添加到替换映射, 以便非虚调用时处理替换
						if (targetTable == this)
							SameTypeReplaceMap[targetDef] = new TableMethodPair(this, implDef);
						else
						{
							var vslot = SlotMap[metNameKey];
							Debug.replacedert(vslot != null);
							SetEntryMap(targetEntry, vslot.Implemented);
						}
					}
				}
			}
			expOverTargets = null;

			// 接口不需要展开入口
			if (thisIsInterface)
				return;

			// 展开新建槽位映射
			foreach (var kv in SlotMap)
			{
				var entries = kv.Value.Entries;
				var newSlotEntry = kv.Value.NewSlotEntry;
				Debug.replacedert(newSlotEntry.Item2.IsNewSlot);

				foreach (TableMethodPair entry in entries)
				{
					var entryDef = entry.Item2;
					if (entryDef.IsReuseSlot && entryDef != newSlotEntry.Item2)
						NewSlotEntryMap[entryDef] = newSlotEntry;
				}
			}

			// 对于非抽象类需要检查是否存在实现
			if (!thisIsAbstract)
			{
				foreach (var kv in EntryMap)
				{
					if (kv.Value == null)
					{
						throw new TypeLoadException(
							string.Format("Interface/abstract method not implemented in type {0}: {1} -> {2}",
								GetNameKey(),
								kv.Key.Item1.GetNameKey(),
								kv.Key.Item2.FullName));
					}
				}
			}
		}

19 Source : MethodTable.cs
with GNU General Public License v3.0
from anydream

private VirtualSlot ProcessMethod(
			string metNameKey,
			MethodDef metDef,
			MethodTable baseTable,
			List<Tuple<string, MethodDef>> expOverrides)
		{
			Debug.replacedert(metDef.IsVirtual);

			// 记录显式重写方法
			if (metDef.HasOverrides)
				expOverrides.Add(new Tuple<string, MethodDef>(metNameKey, metDef));

			var entry = new TableMethodPair(this, metDef);
			var impl = Def.IsInterface ? null : entry;

			VirtualSlot vslot;
			if (metDef.IsReuseSlot)
			{
				// 对于重写槽方法, 如果不存在可重写的槽则转换为新建槽方法
				if (baseTable == null)
					metDef.IsNewSlot = true;
				else if (!baseTable.SlotMap.TryGetValue(metNameKey, out vslot))
					metDef.IsNewSlot = true;
				else
				{
					vslot = new VirtualSlot(vslot, impl);
					vslot.Entries.Add(entry);
					vslot.Implemented = impl;
					SlotMap[metNameKey] = vslot;
					ApplyVirtualSlot(vslot);
					return vslot;
				}
			}

			Debug.replacedert(metDef.IsNewSlot);
			vslot = new VirtualSlot(impl);
			vslot.Entries.Add(entry);
			vslot.Implemented = impl;
			SlotMap[metNameKey] = vslot;
			ApplyVirtualSlot(vslot);
			return vslot;
		}

19 Source : AStarPathfinder.cs
with MIT License
from ApmeM

public static bool Search<T>( IAstarGraph<T> graph, T start, T goal, out Dictionary<T,T> cameFrom )
        {
            var foundPath = false;
            cameFrom = new Dictionary<T, T> { { start, start } };

            var costSoFar = new Dictionary<T, int>();
            var frontier = new List<Tuple<int, T>> { new Tuple<int, T>(0, start) };

            costSoFar[start] = 0;

            while( frontier.Count > 0 )
            {
                var current = frontier[0];
                frontier.RemoveAt(0);

                if ( current.Item2.Equals( goal ) )
                {
                    foundPath = true;
                    break;
                }

                foreach( var next in graph.GetNeighbors( current.Item2) )
                {
                    var newCost = costSoFar[current.Item2] + graph.Cost( current.Item2, next );
                    if( !costSoFar.ContainsKey( next ) || newCost < costSoFar[next] )
                    {
                        costSoFar[next] = newCost;
                        var priority = newCost + graph.Heuristic( next, goal );
                        frontier.Add(new Tuple<int, T>(priority, next));
                        cameFrom[next] = current.Item2;
                    }
                }

                frontier.Sort(new TupleComparer<T>());
            }

            return foundPath;
        }

19 Source : WeightedPathfinder.cs
with MIT License
from ApmeM

public static bool Search<T>( IWeightedGraph<T> graph, T start, T goal, out Dictionary<T,T> cameFrom )
        {
            var foundPath = false;
            cameFrom = new Dictionary<T,T>();
            cameFrom.Add( start, start );

            var costSoFar = new Dictionary<T, int>();
            var frontier = new List<Tuple<int, T>> { new Tuple<int, T>(0, start) };

            costSoFar[start] = 0;

            while( frontier.Count > 0 )
            {
                var current = frontier[0];
                frontier.RemoveAt(0);

                if ( current.Item2.Equals( goal ) )
                {
                    foundPath = true;
                    break;
                }

                foreach( var next in graph.GetNeighbors( current.Item2) )
                {
                    var newCost = costSoFar[current.Item2] + graph.Cost( current.Item2, next );
                    if( !costSoFar.ContainsKey( next ) || newCost < costSoFar[next] )
                    {
                        costSoFar[next] = newCost;
                        var priority = newCost;
                        frontier.Add( new Tuple<int, T>(priority, next));
                        cameFrom[next] = current.Item2;
                    }
                }

                frontier.Sort(new TupleComparer<T>());
            }

            return foundPath;
        }

19 Source : Calculation.cs
with Apache License 2.0
from Appdynamics

[TestMethod, Ignore]
        public void CalulationValidationExcel()
        {
#if Core
            var dir = AppContext.BaseDirectory;
            dir = Directory.GetParent(dir).Parent.Parent.Parent.FullName;
#else
            var dir = AppDomain.CurrentDomain.BaseDirectory;
#endif
            var pck = new ExcelPackage(new FileInfo(Path.Combine(dir, "Workbooks", "FormulaTest.xlsx")));

            var ws = pck.Workbook.Worksheets["ValidateFormulas"];
            var fr = new Dictionary<string, object>();
            foreach (var cell in ws.Cells)
            {
                if (!string.IsNullOrEmpty(cell.Formula))
                {
                    fr.Add(cell.Address, cell.Value);
                }
            }
            pck.Workbook.Calculate();
            var nErrors = 0;
            var errors = new List<Tuple<string, object, object>>();
            foreach (var adr in fr.Keys)
            {
                try
                {
                    if (fr[adr] is double && ws.Cells[adr].Value is double)
                    {
                        var d1 = Convert.ToDouble(fr[adr]);
                        var d2 = Convert.ToDouble(ws.Cells[adr].Value);
                        if (Math.Abs(d1 - d2) < 0.0001)
                        {
                            continue;
                        }
                        else
                        {
                            replacedert.AreEqual(fr[adr], ws.Cells[adr].Value);
                        }
                    }
                    else
                    {
                        replacedert.AreEqual(fr[adr], ws.Cells[adr].Value);
                    }
                }
                catch
                {
                    errors.Add(new Tuple<string, object, object>(adr, fr[adr], ws.Cells[adr].Value));
                    nErrors++;
                }
            }
		}

19 Source : Cooking.cs
with MIT License
from ArchaicQuest

public void Cook(Player player, Room room)
        {
            if(room.Items.FirstOrDefault(x => x.ItemType == Item.Item.ItemTypes.Cooking) == null)
            {
                _writeToClient.WriteLine($"<p>You require a fire and a cooking pot before you can cook.</p>",
                    player.ConnectionId);

                return;
            }

            var pot = room.Items.FirstOrDefault(x => x.ItemType == Item.Item.ItemTypes.Cooking);

            // What happens if player throws in random replaced which is not a food item
            var items = pot.Container.Items.Where(x => x.ItemType == Item.Item.ItemTypes.Food).ToList();

            if(items.Count < 3)
            {
                _writeToClient.WriteLine("<p>You need 3 raw ingredients before you can cook.</p>",
                    player.ConnectionId);
              

                if (pot.Container.Items.FirstOrDefault(x => x.ItemType != Item.Item.ItemTypes.Food) != null)
                {
                    _writeToClient.WriteLine($"<p>The following ingredients cannot be cooked with.</p>",
                        player.ConnectionId);

                    var sb = new StringBuilder();
                    sb.Append("<p>");
                    foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                    {
                        sb.Append($"{invalidItem.Name}, ");
                    }
                    sb.Append("</p>");

                    _writeToClient.WriteLine(sb.ToString(),
                        player.ConnectionId);

                    return;
                }

                return;
            }


            if (items.Count > 3)
            {
                _writeToClient.WriteLine("<p>You can only cook with 3 raw food ingredients. The following ingredients are not raw food and can't be cooked.</p>",
                    player.ConnectionId);

                var sb = new StringBuilder();
                    sb.Append("<p>");
                foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                {
                    sb.Append($"{invalidItem.Name}, ");
                }
                sb.Append("</p>");

                _writeToClient.WriteLine(sb.ToString(),
                    player.ConnectionId);

                return;
            }

            if (items.Count == 3 && pot.Container.Items.FirstOrDefault(x => x.ItemType != Item.Item.ItemTypes.Food) != null)
            {
                _writeToClient.WriteLine($"<p>You can only cook with 3 raw ingredients. The following ingredients cannot be cooked with.</p>",
                    player.ConnectionId);

                var sb = new StringBuilder();
                sb.Append("<p>");
                foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                {
                    sb.Append($"{invalidItem.Name}, ");
                }
                sb.Append("</p>");

                _writeToClient.WriteLine(sb.ToString(),
                    player.ConnectionId);

                return;
            }


            var ingredients = new List<Tuple<Item.Item, int>>();

            foreach (var item in items)
            {
                var ingredient = ingredients.FirstOrDefault(x => x.Item1.Name.Equals(item.Name));
                if (ingredient != null)
                {
                    var index = ingredients.FindIndex(x => x.Item1.Name.Equals(ingredient.Item1.Name));

                    var count = ingredient.Item2 + 1;
                    ingredients[index] = Tuple.Create(item, count);
                }
                else
                {
                    ingredients.Add(new Tuple<Item.Item, int>(item, 1));
                }

            }

            pot.Container.Items = new ItemList();
            var cookedItem = GenerateCookedItem(player, room, ingredients);
            _writeToClient.WriteLine("<p>You begin cooking.</p>",
                player.ConnectionId);
           _writeToClient.WriteLine("<p>You stir the ingredients.</p>",
                player.ConnectionId, 1000);

            _writeToClient.WriteLine("<p>You taste and season the dish.</p>",
                player.ConnectionId, 2500);

            _writeToClient.WriteLine("<p>You stir the ingredients.</p>",
                player.ConnectionId, 5000);

            var success = _skills.SuccessCheck(player, "cooking");

            if (success)
            {

                _writeToClient.WriteLine(
                    $"<p clreplaced='improve'>You have successfully created {Helpers.AddArticle(cookedItem.Name).ToLower()}.</p>",
                    player.ConnectionId, 6000);

                foreach (var pc in room.Players)
                {
                    if (pc.Name == player.Name)
                    {
                        continue;
                    }

                    _writeToClient.WriteLine($"<p>{player.Name} has cooked {cookedItem.Name}</p>",
                        pc.ConnectionId, 6000);

                }

                player.Inventory.Add(cookedItem);
                player.Weight += cookedItem.Weight;
               

            }
            else
            {
                _writeToClient.WriteLine(
                    $"<p clreplaced='improve'>You have fail to create {Helpers.AddArticle(cookedItem.Name).ToLower()}.</p>",
                    player.ConnectionId, 6000);

                foreach (var pc in room.Players)
                {
                    if (pc.Name == player.Name)
                    {
                        continue;
                    }

                    _writeToClient.WriteLine($"<p>{player.Name} fails to cook {cookedItem.Name}</p>",
                        pc.ConnectionId, 6000);

                }

                _skills.LearnMistakes(player, "Cooking", 6000);
            }
            _clientUi.UpdateInventory(player);
            _clientUi.UpdateScore(player);
        }

See More Examples