Example #1
1
        public static void UpdateDiagram(IList<StateFunction> list, StateFunction fn)
        {
            if (highlightedFn != null)
            {
                string mOld = string.Empty;
                foreach (var mov in highlightedFn.Movement)
                {
                    mOld += mov;
                }
                var sOld = string.Format("({0}, {1}) = ({2}, {3}, {4})", highlightedFn.CurrentState, highlightedFn.Read, highlightedFn.NewState, highlightedFn.Write, mOld);
                //TODO
                Tools.Write(Console.WindowWidth - 50, list.IndexOf(highlightedFn), sOld);
            }

            ConsoleColor f = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Yellow;

            string m = string.Empty;
            foreach (var mov in fn.Movement)
            {
                m += mov;
            }
            var s = string.Format("({0}, {1}) = ({2}, {3}, {4})", fn.CurrentState, fn.Read, fn.NewState, fn.Write, m);
            Tools.Write(Console.WindowWidth - 50, list.IndexOf(fn), s);

            highlightedFn = fn;

            Console.ForegroundColor = f;
        }
Example #2
1
		public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
		{
			var result = from n1 in list
				from n2 in list
					where n1 + n2 == sum
				select new Tuple<int, int>(list.IndexOf(n1), list.IndexOf(n2));
			return result.FirstOrDefault();
		}
 public void Swap(IList<ITile> tiles, ITile first, ITile second)
 {
     int firstIndex = tiles.IndexOf(first);
     int secondIndex = tiles.IndexOf(second);
     if (firstIndex == -1 || secondIndex == -1)
         return;
     tiles[firstIndex] = second;
     tiles[secondIndex] = first;
 }
        protected IDictionary<string, string> GetArguments(IList<string> args)
        {
            args = args.Select(arg => arg.Replace(ARGUMENT_VALUE_PREFIX, string.Empty)).ToList();

            var indexes = args.Where(a => a.StartsWith(ARGUMENT_PREFIX)).Select(arg => new { Key = arg, Index = args.IndexOf(arg) });

            return
                (from arg in args.Where(a => a.StartsWith(ARGUMENT_PREFIX))
                let index = args.IndexOf(arg)
                let others = indexes.SkipWhile(a => a.Key != arg).Skip(1)
                let next = others.Any() ? others.First().Index : args.Count
                let val = string.Join(FRAGMENT_DELIMITER, args.Skip(index + 1).Take(next - index - 1).ToArray())
                let cleanedArg = arg.Replace(ARGUMENT_PREFIX, string.Empty)
                select new KeyValuePair<string, string>(cleanedArg, val)).ToDictionary(x => x.Key, x => x.Value);
        }
Example #5
1
        public void SyncTestItemsIList(ref IList<TestItem> source, ref IList<TestItem> destination)
        {
            foreach (var item in source)
            {
                var dest = destination.SingleOrDefault(d => d.Id == item.Id);
                if (dest == null)
                {
                    destination.Add(item);
                }
                else
                {
                    if (dest.Sync < item.Sync)
                    {
                         destination[destination.IndexOf(dest)] = item.Clone();
                    }
                }
            }

            foreach (var item in destination)
            {
                var sour = source.SingleOrDefault(s => s.Id == item.Id);
                if (sour == null)
                {
                    source.Add(item);
                }
                else
                {
                    if (sour.Sync < item.Sync)
                    {
                        source[source.IndexOf(sour)] = item.Clone();
                    }
                }
            }
        }
Example #6
1
    public static bool SrotingButtons(object currentObject, IList ObjectsList)
    {
        int ObjectIndex = ObjectsList.IndexOf(currentObject);
        if(ObjectIndex == 0) {
            GUI.enabled = false;
        }

        bool up 		= GUILayout.Button("↑", EditorStyles.miniButtonLeft, GUILayout.Width(20));
        if(up) {
            object c = currentObject;
            ObjectsList[ObjectIndex]  		= ObjectsList[ObjectIndex - 1];
            ObjectsList[ObjectIndex - 1] 	=  c;
        }

        if(ObjectIndex >= ObjectsList.Count -1) {
            GUI.enabled = false;
        } else {
            GUI.enabled = true;
        }

        bool down 		= GUILayout.Button("↓", EditorStyles.miniButtonMid, GUILayout.Width(20));
        if(down) {
            object c = currentObject;
            ObjectsList[ObjectIndex] =  ObjectsList[ObjectIndex + 1];
            ObjectsList[ObjectIndex + 1] = c;
        }

        GUI.enabled = true;
        bool r 			= GUILayout.Button("-", EditorStyles.miniButtonRight, GUILayout.Width(20));
        if(r) {
            ObjectsList.Remove(currentObject);
        }

        return r;
    }
        private List<Expression> GetDominatedExpressions(BinaryExpression assignment, IList<Expression> blockExpressions)
        {
            int assignmentIndex = blockExpressions.IndexOf(assignment);
            Expression assignedValue = assignment.Right;
            List<Expression> result = new List<Expression>();
            //ExpressionTreeVisitor etv = new ExpressionTreeVisitor();
            //IEnumerable<VariableReference> variablesUsed = etv.GetUsedVariables(assignedValue);
            //ICollection<ParameterReference> argumentsUsed = etv.GetUsedArguments(assignedValue);

            /// If this is some form of autoassignment
            if (ChangesAssignedExpression(assignment.Right, assignment.Left, assignment.Left))
            {
                return result;
            }

            for (int i = assignmentIndex + 1; i < blockExpressions.Count; i++)
            {
                //TODO: Add breaks and checks
                Expression currentExpression = blockExpressions[i];
                if (ChangesAssignedExpression(currentExpression, assignedValue, assignment.Left))
                {
                    break;
                }
                result.Add(blockExpressions[i]);
            }
            return result;
        }
 private void ParseRealization(IList<Double> realization)
 {
     Double repeatedValue = realization.Last(); // last value it's the same as cycle start value
     Int32 cycleStartIndex = realization.IndexOf(repeatedValue);
     Appendix = realization.Take(cycleStartIndex).ToList();
     Cycle = realization.Skip(cycleStartIndex).Take(realization.Count - cycleStartIndex - 1).ToList();
 }
 protected static void GuerillaPreProcessMethod(BinaryReader binaryReader, IList<tag_field> fields)
 {
     var index = (from field in fields
                  where field.Name == "Object Data"
                  select fields.IndexOf(field)).Single();
     fields.Insert(++index, new tag_field() { type = field_type._field_pad, Name = "indexer", definition = 4 });
 }
Example #10
1
        public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes)
        {
            if (numInputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}.");

            if (numOutputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}.");

            if (hiddenLayerSizes == null || !hiddenLayerSizes.Any())
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty.");

            if (hiddenLayerSizes.Any(h => h <= 0))
            {
                var badSize = hiddenLayerSizes.First(h => h <= 0);
                var index = hiddenLayerSizes.IndexOf(badSize);
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " +
                                                $"values; was {badSize} at index {index}.");
            }

            NumInputs = numInputs;
            NumOutputs = numOutputs;
            HiddenLayerSizes = hiddenLayerSizes.ToArray();

            Weights = new double[hiddenLayerSizes.Count + 1][];

            for (var i = 0; i < hiddenLayerSizes.Count + 1; i++)
            {
                if (i == 0)
                    Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]];
                else if (i < hiddenLayerSizes.Count)
                    Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]];
                else
                    Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs];
            }
        }
 static Instruction getInstruction(IList<Instruction> instrs, Instruction source, int displ)
 {
     int sourceIndex = instrs.IndexOf(source);
     if (sourceIndex < 0)
         throw new ApplicationException("Could not find source instruction");
     return instrs[sourceIndex + displ];
 }
        /// <summary>
        /// FPS command implementation.
        /// </summary>
        private void CommandExecute(IDebugCommandHost host, string command, IList<string> arguments)
        {
            foreach (string arg in arguments) { arg.ToLower(); }

            if (arguments.Contains("list")) { ShowList(); }

            if (arguments.Contains("open"))
            {
                int index = arguments.IndexOf("open");
                string sceneToOpen = arguments[index + 1];

                if (sceneManager.ContainsScene(sceneToOpen))
                {
                    // activate the selected scene
                    sceneManager.ActivateScene(sceneToOpen);
                }
            }

            if (arguments.Contains("close"))
            {
                int index = arguments.IndexOf("close");
                string sceneToClose = arguments[index + 1];

                if (sceneManager.ContainsScene(sceneToClose))
                {
                    sceneManager.ExitScene(sceneToClose);
                }
            }
            // TODO: allow loading and disposing of scenes
        }
 public static void GetValue(ImportExportItem data, IList<string> rowData, IList<string> columnNames)
 {
     foreach (var item in typeof(ImportExportItem).GetProperties())
     {
         item.SetValue(data, ConvertType(item.PropertyType, rowData[columnNames.IndexOf(item.Name.ToLower())]), null);
     }
 }
Example #14
0
        /// <summary>
        /// Convert output combo items list
        /// </summary>
        /// <param name="target">List master code</param>
        /// <param name="selectedValue">Selected value</param>
        /// <returns>List ListItem</returns>
        public static ComboModel ToComboItems(IList<MCode> target, string selectedValue)
        {
            // Local variable declaration
            ComboModel comboModel = null;
            IList<ComboItem> listComboItems = null;

            // Variable initialize
            listComboItems = new List<ComboItem>();
            comboModel = new ComboModel();

            // Get data
            var val = string.Empty;
            foreach (var obj in target)
            {
                var combo = new ComboItem();
                combo.Code = DataHelper.ToString(obj.CodeCd);
                combo.Name = DataHelper.ToString(obj.CodeName);
                if (combo.Code == selectedValue
                    || (DataCheckHelper.IsNull(selectedValue) && target.IndexOf(obj) == 0))
                    val = combo.Code;
                listComboItems.Add(combo);
            }

            // Set value
            comboModel.SeletedValue = val;
            comboModel.ListItems = listComboItems;

            return comboModel;
        }
		/// <summary>
		/// Determines if the specified plugin order is valid.
		/// </summary>
		/// <param name="p_lstPlugins">The plugins whose order is to be validated.</param>
		/// <returns><c>true</c> if the given plugins are in a valid order;
		/// <c>false</c> otherwise.</returns>
		public bool ValidateOrder(IList<Plugin> p_lstPlugins)
		{
			if (p_lstPlugins.Count < OrderedCriticalPluginNames.Length)
				return false;
			for (Int32 i = 0; i < OrderedCriticalPluginNames.Length; i++)
				if (!p_lstPlugins[i].Filename.Equals(OrderedCriticalPluginNames[i], StringComparison.OrdinalIgnoreCase))
					return false;
			bool booIsPreviousMaster = true;
			foreach (GamebryoPlugin plgPlugin in p_lstPlugins)
			{
				if (!booIsPreviousMaster && plgPlugin.IsMaster)
					return false;
				booIsPreviousMaster = plgPlugin.IsMaster;
			}
			for (Int32 i = p_lstPlugins.Count - 1; i >= 0; i--)
				if (p_lstPlugins[i].HasMasters)
					foreach (string pluginName in p_lstPlugins[i].Masters)
					{
						Int32 masterIndex = p_lstPlugins.IndexOf(p => Path.GetFileName(p.Filename).Equals(pluginName, StringComparison.OrdinalIgnoreCase));
						if (i < masterIndex)
							return false;
					}

			return true;
		}
		public void Apply(IList<Commit> commitStream)
		{
			int destLocation = commitStream.IndexOf(m_finalCommit);
			int searchStart = destLocation;
			var commits = m_files.Keys.OrderBy(c => c.Index).ToList();

			Dump();
			m_log.WriteLine("Applying:");

			using (m_log.Indent())
			{
				// handle in reverse order
				for (int i = commits.Count - 1; i >= 0; i--)
				{
					var commitToMove = commits[i];
					int location = commitStream.IndexOfFromEnd(commitToMove, searchStart);
					if (location < 0)
					{
						// assume already moved
						m_log.WriteLine("Skip moving {0} after {1}", commitToMove.ConciseFormat, m_finalCommit.ConciseFormat);
						continue;
					}

					// does the commit need splitting?
					var files = m_files[commitToMove];
					if (files.Count() < commitToMove.Count())
					{
						m_log.WriteLine("Split {0}", commitToMove.CommitId);

						using (m_log.Indent())
						{
							int index = commitToMove.Index;
							Commit splitCommitNeedMove;
							Commit splitCommitNoMove;
							SplitCommit(commitToMove, files, out splitCommitNeedMove, out splitCommitNoMove);

							commitStream[location] = splitCommitNoMove;
							commitStream.Insert(location + 1, splitCommitNeedMove);
							destLocation++;

							if (m_finalCommit == commitToMove)
								m_finalCommit = splitCommitNeedMove;
							commitToMove = splitCommitNeedMove;

							// update Commit indices
							for (int j = location; j < commitStream.Count; j++)
								commitStream[j].Index = index++;

							location++;
						}
					}

					m_log.WriteLine("Move {0}({1}) after {2}({3})", commitToMove.ConciseFormat, location,
								m_finalCommit.ConciseFormat, destLocation);
					commitStream.Move(location, destLocation);
					destLocation--;
				}
			}
		}
Example #17
0
 internal int GetIndex(IList<CommandLineOption> options, CommandLineOption @delegate)
 {
     foreach (var item in options.Where(item => item.Name == @delegate.Name))
     {
         return options.IndexOf(item);
     }
     return -1;
 }
Example #18
0
 public StructureValueCollection Serialize(IList<ITagClass> classList)
 {
     var result = new StructureValueCollection();
     result.SetInteger("memory address", (MetaLocation != null) ? MetaLocation.AsPointer() : 0);
     result.SetInteger("class index", (Class != null) ? (uint) classList.IndexOf(Class) : 0xFFFFFFFF);
     result.SetInteger("datum index salt", Index.Salt);
     return result;
 }
 public void TestIndexOf()
 {
     list = new List<int>();
     for (int i = 0; i < 10; i++)
     {
         list.Add(i);
         Assert.AreEqual(i, list.IndexOf(i));
     }
 }
Example #20
0
		public static void UpdateLights(IHueClient client, IList<Light> list)
		{
			Parallel.ForEach(list, light =>
			{
				Light initLight = client.GetLightAsync(light.Id).Result;
				initLight.Id = light.Id;
				list[list.IndexOf(light)] = initLight;
			});
		}
Example #21
0
    public override void Load()
    {
      _multisampleTypes = new List<MultisampleType>(GraphicsDevice.Setup.MultisampleTypes);
      MultisampleType selectedMsType = SettingsManager.Load<AppSettings>().MultisampleType;
      Selected = _multisampleTypes.IndexOf(selectedMsType);

      // Fill items
      _items = _multisampleTypes.Select(mst => LocalizationHelper.CreateStaticString(mst.ToString())).ToList();
    }
Example #22
0
 public static Object HandleLocations(IList<Declaration> locations)
 {
     var tuples = from d in locations
                select new { filename = d.Filename,
                             line = d.Line,
                             col = d.Col,
                             index = locations.IndexOf(d) };
       return tuples;
 }
        public static void ReorderableList(IList list, System.Action<int> GUICallback, UnityObject unityObject = null)
        {
            if (list.Count == 1){
                GUICallback(0);
                return;
            }

            if (!pickedObjectList.ContainsKey(list))
                pickedObjectList[list] = null;

            var e = Event.current;
            var lastRect = new Rect();
            var picked = pickedObjectList[list];
            GUILayout.BeginVertical();
            for (var i= 0; i < list.Count; i++){

                GUILayout.BeginVertical();
                GUICallback(i);
                GUILayout.EndVertical();

                GUI.color = Color.white;
                GUI.backgroundColor = Color.white;

                lastRect = GUILayoutUtility.GetLastRect();
                EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.MoveArrow);

                if (picked != null && picked == list[i])
                    GUI.Box(lastRect, "");

                if (picked != null && lastRect.Contains(e.mousePosition) && picked != list[i]){

                    var markRect = new Rect(lastRect.x,lastRect.y-2,lastRect.width, 2);
                    if (list.IndexOf(picked) < i)
                        markRect.y = lastRect.yMax - 2;

                    GUI.Box(markRect, "");
                    if (e.type == EventType.MouseUp){
                        if (unityObject != null)
                            Undo.RecordObject(unityObject, "Reorder");
                        list.Remove(picked);
                        list.Insert(i, picked);
                        pickedObjectList[list] = null;
                        if (unityObject != null)
                            EditorUtility.SetDirty(unityObject);
                    }
                }

                if (lastRect.Contains(e.mousePosition) && e.type == EventType.MouseDown)
                    pickedObjectList[list] = list[i];
            }

            GUILayout.EndVertical();

            if (e.type == EventType.MouseUp)
                pickedObjectList[list] = null;
        }
Example #24
0
 public CharacterData(Character character, IList<Achievement> allAchievements)
 {
     Character = character;
     _achievementList = new double[allAchievements.Count];
     foreach (var individualAchivement in character.Achievements)
     {
         int fieldIndex = allAchievements.IndexOf(allAchievements.First(a => a.AchievementID == individualAchivement.AchievementID));
         _achievementList[fieldIndex] = 1;
     }
 }
Example #25
0
        protected override void OnCustomizeLanguages(IList<string> languages)
        {
            string userLanguageName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            if (userLanguageName != "en-US" && languages.IndexOf(userLanguageName) == -1)
            {
                languages.Add(userLanguageName);
            }

            base.OnCustomizeLanguages(languages);
        }
    public override void Load()
    {
      _suspendLevels = Enum.GetValues(typeof(SuspendLevel)).Cast<SuspendLevel>().ToList();
      SuspendLevel selectedSuspendLevel = SettingsManager.Load<AppSettings>().SuspendLevel;
      Selected = _suspendLevels.IndexOf(selectedSuspendLevel);

      // Fill items
      _items = _suspendLevels.Select(level => LocalizationHelper.CreateResourceString(
          '[' + RES_SUSPEND_LEVEL_PREFIX + '.' + level.ToString() + ']')).ToList();
    }
		Instruction GetFirstInstruction(IList<Instruction> instrs, int index) {
			try {
				var instr = instrs[index];
				if (!instr.IsBr())
					return null;
				instr = instr.Operand as Instruction;
				if (instr == null)
					return null;
				if (!instr.IsLdcI4() || instr.GetLdcI4Value() != 0)
					return null;
				instr = instrs[instrs.IndexOf(instr) + 1];
				if (!instr.IsBrtrue())
					return null;
				return instrs[instrs.IndexOf(instr) + 1];
			}
			catch {
				return null;
			}
		}
Example #28
0
        private static int GetCurrentThemeIndex(IList<Theme> allThemes, string currentThemeName)
        {
            var currentTheme = allThemes.FirstOrDefault(x => x.Name == currentThemeName);

            var idx = -1;
            if (currentTheme != null)
                idx = allThemes.IndexOf(currentTheme);

            return idx;
        }
Example #29
0
 public static void EscapeDataContainingUrlSegments(IList<object> segments)
 {
     var names = segments.Where(s => _escapeSegments.IsMatch(s.ToString()));
     var indexes = names.Select(n => segments.IndexOf(n) + 1).ToList();
     for (var i = 0; i < indexes.Count(); i++)
     {
         var value = segments[indexes[i]].ToString();
         segments[indexes[i]] = Uri.EscapeDataString(value);
     }
 }
        protected static void GuerillaPreProcessMethod(BinaryReader binaryReader, IList<tag_field> fields)
        {
            var index = (from field in fields
                         where field.Name == "WDP fields"
                         select fields.IndexOf(field)).Single();
            var wdpFields = fields.Where(x => fields.IndexOf(x) >= index && fields.IndexOf(x) < index + 5).ToArray();
            var dataFields = fields.Where(x => x.type == field_type._field_data).ToArray();

            for (int i = 0; i < wdpFields.Count(); i++)
            {
                fields.Remove(wdpFields[i]);
            }
            for (int i = 0; i < dataFields.Count(); i++)
            {
                index = fields.IndexOf(dataFields[i]);
                fields.RemoveAt(index);
                fields.Insert(index, new tag_field() { type = field_type._field_skip, Name = "data", definition = 8 });
            }
        }