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; }
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); }
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 }); }
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(); } } } }
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; }
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]; } }
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(); }
/// <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> /// 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 }
void OnItemAppearing(object sender, ItemVisibilityEventArgs e) { int position = itemsSource?.IndexOf(e.Item) ?? 0; if (itemsSource != null) { // preloadIndex should never end up to be equal to itemsSource.Count otherwise // LoadMoreItems would not be called if (PreloadCount <= 0) { PreloadCount = 1; } int preloadIndex = Math.Max(itemsSource.Count - PreloadCount, 0); if ((position > lastPosition || (position == itemsSource.Count - 1)) && (position >= preloadIndex)) { lastPosition = position; if (!incrementalLoading.IsLoadingIncrementally && !IsRefreshing && incrementalLoading.HasMoreItems) { LoadMoreItems(); } } } }
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); } }
/// <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; }
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]; }
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--; } } }
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; }
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; }
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; }); }
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 void TestIndexOf() { list = new List<int>(); for (int i = 0; i < 10; i++) { list.Add(i); Assert.AreEqual(i, list.IndexOf(i)); } }
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(); }
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; }
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 }); } }
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(); }
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 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; } }
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; } }
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); } }
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; }
private protected int IndexOfCore(object value) { if (m_vectorView is not null) { return(m_vectorView.IndexOf(value)); } else { return(m_vector?.IndexOf(value) ?? -1); } }
/// <summary> /// Initializes a new instance of read-data event argument. /// </summary> /// <param name="readDataMode">ReadData Mode.</param> /// <param name="columns">List of all the columns in the grid.</param> /// <param name="sortByColumns">List of all the columns by which we're sorting the grid.</param> /// <param name="page">Page number at the moment of initialization.</param> /// <param name="pageSize">Maximum number of items per page.</param> /// <param name="virtualizeOffset">Requested data start index by Virtualize.</param> /// <param name="virtualizeCount">Max number of items requested by Virtualize.</param> /// <param name="cancellationToken">Cancellation token.</param> public DataGridReadDataEventArgs( DataGridReadDataMode readDataMode, IEnumerable <DataGridColumn <TItem> > columns, IList <DataGridColumn <TItem> > sortByColumns, int page, int pageSize, int virtualizeOffset, int virtualizeCount, CancellationToken cancellationToken = default) { Page = page; PageSize = pageSize; Columns = columns?.Select(x => new DataGridColumnInfo( x.Field, x.Filter?.SearchValue, x.CurrentSortDirection, sortByColumns?.IndexOf(x) ?? -1, x.ColumnType)); CancellationToken = cancellationToken; VirtualizeOffset = virtualizeOffset; VirtualizeCount = virtualizeCount; ReadDataMode = readDataMode; }
public int IndexOf(T item) { lock (list) { return(list.IndexOf(item)); } }
public ModelInfo(TypeDef type) { OwnerList = type.DeclaringType == null ? type.Module.Types : type.DeclaringType.NestedTypes; Index = OwnerList.IndexOf(type); Debug.Assert(Index >= 0); }
public static int?SearchMark <T>(this IList <T> source, int offset, int length, T[] mark, int matched, out int parsedLength) where T : IEquatable <T> { int num = offset; int num2 = offset + length - 1; int num3 = matched; parsedLength = 0; if (matched > 0) { for (int i = num3; i < mark.Length; i++) { if (!source[num++].Equals(mark[i])) { break; } num3++; if (num > num2) { if (num3 == mark.Length) { parsedLength = mark.Length - matched; return(offset); } return(-num3); } } if (num3 == mark.Length) { parsedLength = mark.Length - matched; return(offset); } num = offset; num3 = 0; } while (true) { num = source.IndexOf(mark[num3], num, length - num + offset); if (num < 0) { return(null); } num3++; for (int j = num3; j < mark.Length; j++) { int num5 = num + j; if (num5 > num2) { return(-num3); } if (!source[num5].Equals(mark[j])) { break; } num3++; } if (num3 == mark.Length) { break; } num++; num3 = 0; } parsedLength = num - offset + mark.Length; return(num); }
public static IList <T> Filter <T>(this IList <T> collection, FilterCallback <T> callback) => ( from T item in collection where callback(item, collection.IndexOf(item), collection) select item ).ToList();
public int IndexOf(T item) { return(_real.IndexOf(item)); }
/// <inheritdoc /> public void ReadDelta(Stream stream, bool keepDirtyDelta) { using (PooledBitReader reader = PooledBitReader.Get(stream)) { ushort deltaCount = reader.ReadUInt16Packed(); for (int i = 0; i < deltaCount; i++) { NetworkedListEvent <T> .EventType eventType = (NetworkedListEvent <T> .EventType)reader.ReadBits(3); switch (eventType) { case NetworkedListEvent <T> .EventType.Add: { list.Add((T)reader.ReadObjectPacked(typeof(T))); //BOX if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, index = list.Count - 1, value = list[list.Count - 1] }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType, index = list.Count - 1, value = list[list.Count - 1] }); } } break; case NetworkedListEvent <T> .EventType.Insert: { int index = reader.ReadInt32Packed(); list.Insert(index, (T)reader.ReadObjectPacked(typeof(T))); //BOX if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, index = index, value = list[index] }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType, index = index, value = list[index] }); } } break; case NetworkedListEvent <T> .EventType.Remove: { T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX int index = list.IndexOf(value); list.RemoveAt(index); if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, index = index, value = value }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType, index = index, value = value }); } } break; case NetworkedListEvent <T> .EventType.RemoveAt: { int index = reader.ReadInt32Packed(); T value = list[index]; list.RemoveAt(index); if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, index = index, value = value }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType, index = index, value = value }); } } break; case NetworkedListEvent <T> .EventType.Value: { int index = reader.ReadInt32Packed(); T value = (T)reader.ReadObjectPacked(typeof(T)); //BOX if (index < list.Count) { list[index] = value; } if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, index = index, value = value }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType, index = index, value = value }); } } break; case NetworkedListEvent <T> .EventType.Clear: { //Read nothing list.Clear(); if (OnListChanged != null) { OnListChanged(new NetworkedListEvent <T> { eventType = eventType, }); } if (keepDirtyDelta) { dirtyEvents.Add(new NetworkedListEvent <T>() { eventType = eventType }); } } break; } } } }
async Task InvokeRequestResponseService() { using (var client = new HttpClient()) { var scoreRequest = new { Inputs = new Dictionary <string, StringTable>() { { "input1", new StringTable() { //ColumnNames = new string[] { "age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "income"}, ColumnNames = new string[] { "Age", "Workclass", "Fnlwgt", "Education", "Education-num", "Marital-status", "Occupation", "Relationship", "Race", "Sex", "Capital-gain", "Capital-loss", "Hours-per-week", "Native-country", "Income" }, //Values = new string[,] { { "0", "value", "0", "value", "0", "value", "value", "value", "value", "value", "0", "0", "0", "value", "value" }, { "0", "value", "0", "value", "0", "value", "value", "value", "value", "value", "0", "0", "0", "value", "value" } } Values = new string[, ] { { "52", "Self-emp-not-inc", "209642", "HS-grad", "12", "Married-civ-spouse", "Exec-managerial", "Husband", "White", "Male", "0", "0", "45", "United-States", "0" } } } } }, GlobalParameters = new Dictionary <string, string>() { } }; const string apiKey = "gE7GS0g98G/Kcpy/F1oWSC23BYhWIvB7rKIVv9WcXFMPFTT1jnesknXmNSYKkop6XLI0valyd/Va1s32ek5sSQ=="; client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/46ac4bd491e14dc8b1edbcbb921dcea5/services/4e38080d3670486c81aac3f571d471b0/execute?api-version=2.0&details=true"); HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); //Console.WriteLine("Result: {0}", result); JObject json = JObject.Parse(result); JObject results = (JObject)json["Results"]; JObject output1 = (JObject)results["output1"]; JObject value = (JObject)output1["value"]; JArray columnNames = (JArray)value["ColumnNames"]; IList <string> columnNamesList = columnNames.Select(c => (string)c).ToList(); JArray values = (JArray)value["Values"]; foreach (JArray array in values) { string scoredLabel = array[columnNamesList.IndexOf("Scored Labels")].Value <string>(); double scoredProb = array[columnNamesList.IndexOf("Scored Probabilities")].Value <double>(); lblResult.Text = "Prediction=" + scoredLabel + ", Confidence=" + scoredProb; lblRawResult.Text = result; } } else { //Console.WriteLine("Failed with status code: {0}", response.StatusCode); lblResult.Text = "Failed with status code:" + response.StatusCode; } //Console.ReadLine(); } return; }
public static int Main() { int result = 0; int i, index = 0; bool bRes = false; try { //Part 1 - GenClass <int> Console.WriteLine("\ntest GenClass<int>"); GenClass <int> obj1; obj1 = new GenClass <int>(); obj1.fld = 3; Console.WriteLine(obj1.fld); GenClass <int>[] arGen; arGen = new GenClass <int> [5]; for (i = 0; i < 5; i++) { arGen[i] = new GenClass <int>(); arGen[i].fld = i; Console.Write(arGen[i].fld + "\t"); } Console.WriteLine(); IList interf1 = (IList)arGen; Console.WriteLine("testing IList.Contains"); bRes = interf1.Contains(arGen[2]); if (bRes != true) { Console.WriteLine("unexpected result: {0} \n test failed", bRes); return(110); } bRes = interf1.Contains(obj1); if (bRes != false) { Console.WriteLine("unexpected result: {0} \n test failed", bRes); return(110); } Console.WriteLine("testing IList.IndexOf"); index = interf1.IndexOf(arGen[2]); if (index != 2) { Console.WriteLine("unexpected result: {0} \n test failed", index); return(110); } Console.WriteLine("testing IList.Clear"); interf1.Clear(); for (i = 0; i < 5; i++) { if (arGen[i] != null) { Console.WriteLine("unexpected result: element {0} is not null \n test failed", i); return(110); } } //Part 2 - GenClass <string> Console.WriteLine("\ntest GenClass<string>"); GenClass <string> obj2; obj2 = new GenClass <string>(); obj2.fld = "name"; Console.WriteLine(obj2.fld); GenClass <string>[] arGenS; arGenS = new GenClass <string> [5]; string aux = "none"; for (i = 0; i < 5; i++) { arGenS[i] = new GenClass <string>(); aux = Convert.ToString(i); arGenS[i].fld = aux; Console.Write(arGenS[i].fld + "\t"); } Console.WriteLine(); IList interf2 = (IList)arGenS; Console.WriteLine("testing IList.Contains"); bRes = interf2.Contains(arGenS[2]); if (bRes != true) { Console.WriteLine("unexpected result: {0} \n test failed", bRes); return(110); } bRes = interf2.Contains(obj2); if (bRes != false) { Console.WriteLine("unexpected result: {0} \n test failed", bRes); return(110); } bRes = interf2.Contains(obj1); if (bRes != false) { Console.WriteLine("unexpected result: {0} \n test failed", bRes); return(110); } Console.WriteLine("testing IList.IndexOf"); index = interf2.IndexOf(arGenS[2]); if (index != 2) { Console.WriteLine("unexpected result: {0} \n test failed", index); return(110); } Console.WriteLine("testing IList.Clear"); interf2.Clear(); for (i = 0; i < 5; i++) { if (arGenS[i] != null) { Console.WriteLine("unexpected result: element {0} is not null \n test failed", i); return(110); } } result = 100; //pass } catch (Exception e) { Console.WriteLine("unexpected exception.."); Console.WriteLine(e); Console.WriteLine("test failed"); return(101); } if (result == 100) { Console.WriteLine("test passed"); } else { Console.WriteLine("test failed"); } return(result); }
public static IEnumerable <byte> GetResponse(IList <byte> bytes) { if (!IsGoodQuality(bytes, BroadcastAddr, false)) { return(new byte[0]); } var i = bytes.IndexOf(CommandByte); var b = (AvrTbCmdType)bytes[i + 3]; IEnumerable <byte> GetAnswer() { var lst = new List <byte>() { (byte)AvrTbCmdType.sendAnswer }; Trace.WriteLine($"TbProtocol.GetResponse for {b.ToString()} command..."); bool isOk = false; switch (b) { case AvrTbCmdType.getAddress: case AvrTbCmdType.setClock: case AvrTbCmdType.changeOut: isOk = true; break; case AvrTbCmdType.getSensors: void addSensor(int value) { lst.Add((byte)(value >> 8)); lst.Add((byte)(value & 0xFF)); } addSensor(105); //10.5 addSensor(231); addSensor(124); addSensor(549); break; } if (lst.Count > 1 || isOk) { lst.AddRange(Encoding.ASCII.GetBytes("OK")); return(lst); } throw new NotImplementedException(); } var answer = GetAnswer(); //var toAddr = ExtractAddressFrom(bytes); var fromAddr = bytes[i + 1]; var bt = GetParcel(fromAddr, CommonAnswerAddr, 1, true, answer); //fix repeatCountPart //var i2 = bytes.IndexOf(CommandByte); //bt[i2 + 2] = bytes[i + 2]; return(bt); }
int IList <string> .IndexOf(string item) { return(_items.IndexOf(item)); }
int IBindableListAdapter.GetItemPosition(object item) { int result = list?.IndexOf((TItem)item) ?? -1; return(result); }
/// <include file="../../docs/Microsoft.Maui.Controls/VisualStateGroupList.xml" path="//Member[@MemberName='IndexOf']/Docs" /> public int IndexOf(VisualStateGroup item) { return(_internalList.IndexOf(item)); }
private static void Clone <T>(this IList <T> source, Change <T> item, IEqualityComparer <T> equalityComparer) { var changeAware = source as ChangeAwareList <T>; switch (item.Reason) { case ListChangeReason.Add: { var change = item.Item; var hasIndex = change.CurrentIndex >= 0; if (hasIndex) { source.Insert(change.CurrentIndex, change.Current); } else { source.Add(change.Current); } break; } case ListChangeReason.AddRange: { source.AddOrInsertRange(item.Range, item.Range.Index); break; } case ListChangeReason.Clear: { source.ClearOrRemoveMany(item); break; } case ListChangeReason.Replace: { var change = item.Item; if (change.CurrentIndex >= 0 && change.CurrentIndex == change.PreviousIndex) { source[change.CurrentIndex] = change.Current; } else { if (change.PreviousIndex == -1) { source.Remove(change.Previous.Value); } else { //is this best? or replace + move? source.RemoveAt(change.PreviousIndex); } if (change.CurrentIndex == -1) { source.Add(change.Current); } else { source.Insert(change.CurrentIndex, change.Current); } } break; } case ListChangeReason.Refresh: { if (changeAware != null) { changeAware.RefreshAt(item.Item.CurrentIndex); } else { source.RemoveAt(item.Item.CurrentIndex); source.Insert(item.Item.CurrentIndex, item.Item.Current); } break; } case ListChangeReason.Remove: { var change = item.Item; bool hasIndex = change.CurrentIndex >= 0; if (hasIndex) { source.RemoveAt(change.CurrentIndex); } else { if (equalityComparer != null) { int index = source.IndexOf(change.Current, equalityComparer); if (index > -1) { source.RemoveAt(index); } } else { source.Remove(change.Current); } } break; } case ListChangeReason.RemoveRange: { //ignore this case because WhereReasonsAre removes the index [in which case call RemoveMany] //if (item.Range.Index < 0) // throw new UnspecifiedIndexException("ListChangeReason.RemoveRange should not have an index specified index"); if (item.Range.Index >= 0 && (source is IExtendedList <T> || source is List <T>)) { source.RemoveRange(item.Range.Index, item.Range.Count); } else { source.RemoveMany(item.Range); } break; } case ListChangeReason.Moved: { var change = item.Item; bool hasIndex = change.CurrentIndex >= 0; if (!hasIndex) { throw new UnspecifiedIndexException("Cannot move as an index was not specified"); } var extendedList = source as IExtendedList <T>; var observableCollection = source as ObservableCollection <T>; if (extendedList != null) { extendedList.Move(change.PreviousIndex, change.CurrentIndex); } else if (observableCollection != null) { observableCollection.Move(change.PreviousIndex, change.CurrentIndex); } else { //check this works whatever the index is source.RemoveAt(change.PreviousIndex); source.Insert(change.CurrentIndex, change.Current); } break; } } }
public int IndexOf(T item) { return(Parent.IndexOf(item)); }
private void gridControl_CurrentCellKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F4) { Shortcut(sender, e); return; } if (KeyPressHelper.IsEnter(e)) { if (lblKembalian.Text.Length > 0) { lblKembalian.Text = ""; } var grid = (GridControl)sender; var rowIndex = grid.CurrentCell.RowIndex; var colIndex = grid.CurrentCell.ColIndex; IProdukBll bll = new ProdukBll(_log); Produk produk = null; GridCurrentCell cc; switch (colIndex) { case 2: // kode produk cc = grid.CurrentCell; var kodeProduk = cc.Renderer.ControlValue.ToString(); if (kodeProduk.Length == 0) // kode produk kosong { // fokus ke kolom nama produk GridListControlHelper.SetCurrentCell(grid, rowIndex, colIndex + 1); } else { // pencarian berdasarkan kode produk produk = bll.GetByKode(kodeProduk); if (produk == null) { ShowMessage("Data produk tidak ditemukan", true); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); return; } if (!_pengaturanUmum.is_stok_produk_boleh_minus) { if (produk.is_stok_minus) { ShowMessage("Maaf stok produk tidak boleh minus", true); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); return; } } ShowMessage(""); double diskon = 0; if (_customer != null) { diskon = _customer.diskon; } if (!(diskon > 0)) { var diskonProduk = GetDiskonJualFix(produk, 1, produk.diskon); diskon = diskonProduk > 0 ? diskonProduk : produk.Golongan.diskon; } // cek item produk sudah diinputkan atau belum ? var itemProduk = GetExistItemProduk(produk.produk_id); if (itemProduk != null) // sudah ada, tinggal update jumlah { var index = _listOfItemJual.IndexOf(itemProduk); UpdateItemProduk(grid, index); cc.Renderer.ControlText = string.Empty; } else { SetItemProduk(grid, rowIndex, produk, diskon: diskon); if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } } grid.Refresh(); RefreshTotal(); if (_pengaturanUmum.is_tampilkan_keterangan_tambahan_item_jual) { // fokus ke kolom keterangan GridListControlHelper.SetCurrentCell(grid, rowIndex, 4); } else { if (_pengaturanUmum.is_fokus_input_kolom_jumlah) { GridListControlHelper.SetCurrentCell(grid, rowIndex, 5); // fokus ke kolom jumlah } else { GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); // pindah kebaris berikutnya } } } break; case 3: // pencarian berdasarkan nama produk cc = grid.CurrentCell; var namaProduk = cc.Renderer.ControlValue.ToString(); var listOfProduk = bll.GetByName(namaProduk); if (listOfProduk.Count == 0) { ShowMessage("Data produk tidak ditemukan", true); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); } else if (listOfProduk.Count == 1) { ShowMessage(""); produk = listOfProduk[0]; if (!_pengaturanUmum.is_stok_produk_boleh_minus) { if (produk.is_stok_minus) { ShowMessage("Maaf stok produk tidak boleh minus", true); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); return; } } double diskon = 0; if (_customer != null) { diskon = _customer.diskon; } if (!(diskon > 0)) { var diskonProduk = GetDiskonJualFix(produk, 1, produk.diskon); diskon = diskonProduk > 0 ? diskonProduk : produk.Golongan.diskon; } // cek item produk sudah diinputkan atau belum ? var itemProduk = GetExistItemProduk(produk.produk_id); if (itemProduk != null) // sudah ada, tinggal update jumlah { var index = _listOfItemJual.IndexOf(itemProduk); UpdateItemProduk(grid, index); cc.Renderer.ControlText = string.Empty; } else { SetItemProduk(grid, rowIndex, produk, diskon: diskon); if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } } grid.Refresh(); RefreshTotal(); if (_pengaturanUmum.is_tampilkan_keterangan_tambahan_item_jual) { // fokus ke kolom keterangan GridListControlHelper.SetCurrentCell(grid, rowIndex, 4); } else { if (_pengaturanUmum.is_fokus_input_kolom_jumlah) { GridListControlHelper.SetCurrentCell(grid, rowIndex, 5); // fokus ke kolom jumlah } else { GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); // pindah kebaris berikutnya } } } else // data lebih dari satu { ShowMessage(""); _rowIndex = rowIndex; _colIndex = colIndex; var frmLookup = new FrmLookupReferensi("Data Produk", listOfProduk); frmLookup.Listener = this; frmLookup.ShowDialog(); } break; case 4: // keterangan if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } if (_pengaturanUmum.is_fokus_input_kolom_jumlah) { GridListControlHelper.SetCurrentCell(grid, rowIndex, 5); // fokus ke kolom jumlah } else { GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); // pindah kebaris berikutnya } break; case 5: // jumlah if (!_pengaturanUmum.is_stok_produk_boleh_minus) { gridControl_CurrentCellValidated(sender, new EventArgs()); var itemJual = _listOfItemJual[rowIndex - 1]; produk = itemJual.Produk; var isValidStok = (produk.sisa_stok - itemJual.jumlah) >= 0; if (!isValidStok) { ShowMessage("Maaf stok produk tidak boleh minus", true); GridListControlHelper.SelectCellText(grid, rowIndex, colIndex); return; } } if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); // pindah kebaris berikutnya break; case 6: // diskon if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); break; case 7: if (grid.RowCount == rowIndex) { _listOfItemJual.Add(new ItemJualProduk()); grid.RowCount = _listOfItemJual.Count; } GridListControlHelper.SetCurrentCell(grid, _listOfItemJual.Count, 2); // fokus ke kolom kode produk break; default: break; } } }
/// <summary> /// Writes a Graphviz dot specification of the specified closure to the specified <see cref="TextWriter"/> /// </summary> /// <param name="closure">The closure of all states</param> /// <param name="writer">The writer</param> /// <param name="options">A <see cref="DotGraphOptions"/> instance with any options, or null to use the defaults</param> static void _WriteDotTo(IList <FA <char, TAccept> > closure, TextWriter writer, DotGraphOptions options = null) { if (null == options) { options = new DotGraphOptions(); } string spfx = null == options.StatePrefix ? "q" : options.StatePrefix; writer.WriteLine("digraph FA {"); writer.WriteLine("rankdir=LR"); writer.WriteLine("node [shape=circle]"); var finals = new List <FA <char, TAccept> >(); var neutrals = new List <FA <char, TAccept> >(); var accepting = FillAcceptingStates(closure, null); foreach (var ffa in closure) { if (ffa.IsFinal && !ffa.IsAccepting) { finals.Add(ffa); } } IList <FA <char, TAccept> > fromStates = null; IList <FA <char, TAccept> > toStates = null; char tchar = default(char); if (null != options.DebugString) { toStates = closure[0].FillEpsilonClosure(); if (null == fromStates) { fromStates = toStates; } foreach (char ch in options.DebugString) { tchar = ch; toStates = FillMove(fromStates, ch); if (0 == toStates.Count) { break; } fromStates = toStates; } } if (null != toStates) { toStates = FillEpsilonClosure(toStates, null); } int i = 0; foreach (var ffa in closure) { if (!finals.Contains(ffa)) { if (ffa.IsAccepting) { accepting.Add(ffa); } else if (ffa.IsNeutral) { neutrals.Add(ffa); } } var rngGrps = ((CharFA <TAccept>)ffa).FillInputTransitionRangesGroupedByState(null); foreach (var rngGrp in rngGrps) { var di = closure.IndexOf(rngGrp.Key); writer.Write(spfx); writer.Write(i); writer.Write("->"); writer.Write(spfx); writer.Write(di.ToString()); writer.Write(" [label=\""); var sb = new StringBuilder(); foreach (var range in rngGrp.Value) { _AppendRangeTo(sb, range); } if (sb.Length != 1 || " " == sb.ToString()) { writer.Write('['); writer.Write(_EscapeLabel(sb.ToString())); writer.Write(']'); } else { writer.Write(_EscapeLabel(sb.ToString())); } writer.WriteLine("\"]"); } // do epsilons foreach (var fffa in ffa.EpsilonTransitions) { writer.Write(spfx); writer.Write(i); writer.Write("->"); writer.Write(spfx); writer.Write(closure.IndexOf(fffa)); writer.WriteLine(" [style=dashed,color=gray]"); } ++i; } string delim = ""; i = 0; foreach (var ffa in closure) { writer.Write(spfx); writer.Write(i); writer.Write(" ["); if (null != options.DebugString) { if (null != toStates && toStates.Contains(ffa)) { writer.Write("color=green,"); } else if (null != fromStates && fromStates.Contains(ffa) && (null == toStates || !toStates.Contains(ffa))) { writer.Write("color=darkgreen,"); } } writer.Write("label=<"); writer.Write("<TABLE BORDER=\"0\"><TR><TD>"); writer.Write(spfx); writer.Write("<SUB>"); writer.Write(i); writer.Write("</SUB></TD></TR>"); if (null != options.DebugString && null != options.DebugSourceNfa && null != ffa.Tag) { var tags = ffa.Tag as IEnumerable; if (null != tags || ffa.Tag is FA <char, TAccept> ) { writer.Write("<TR><TD>{"); if (null == tags) { writer.Write(" q<SUB>"); writer.Write(options.DebugSourceNfa.FillClosure().IndexOf((FA <char, TAccept>)ffa.Tag).ToString()); writer.Write("</SUB>"); } else { delim = ""; foreach (var tag in tags) { writer.Write(delim); if (tag is FA <char, TAccept> ) { writer.Write(delim); writer.Write(" q<SUB>"); writer.Write(options.DebugSourceNfa.FillClosure().IndexOf((FA <char, TAccept>)tag).ToString()); writer.Write("</SUB>"); // putting a comma here is what we'd like // but it breaks dot no matter how its encoded delim = @" "; } } } writer.Write(" }</TD></TR>"); } } if (ffa.IsAccepting) { writer.Write("<TR><TD>"); writer.Write(Convert.ToString(ffa.AcceptSymbol).Replace("\"", """)); writer.Write("</TD></TR>"); } writer.Write("</TABLE>"); writer.Write(">"); bool isfinal = false; if (accepting.Contains(ffa) || (isfinal = finals.Contains(ffa))) { writer.Write(",shape=doublecircle"); } if (isfinal || neutrals.Contains(ffa)) { if ((null == fromStates || !fromStates.Contains(ffa)) && (null == toStates || !toStates.Contains(ffa))) { writer.Write(",color=gray"); } } writer.WriteLine("]"); ++i; } delim = ""; if (0 < accepting.Count) { foreach (var ntfa in accepting) { writer.Write(delim); writer.Write(spfx); writer.Write(closure.IndexOf(ntfa)); delim = ","; } writer.WriteLine(" [shape=doublecircle]"); } delim = ""; if (0 < neutrals.Count) { foreach (var ntfa in neutrals) { if ((null == fromStates || !fromStates.Contains(ntfa)) && (null == toStates || !toStates.Contains(ntfa)) ) { writer.Write(delim); writer.Write(spfx); writer.Write(closure.IndexOf(ntfa)); delim = ","; } } writer.WriteLine(" [color=gray]"); delim = ""; } delim = ""; if (0 < finals.Count) { foreach (var ntfa in finals) { writer.Write(delim); writer.Write(spfx); writer.Write(closure.IndexOf(ntfa)); delim = ","; } writer.WriteLine(" [shape=doublecircle,color=gray]"); } writer.WriteLine("}"); }
/// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> public int IndexOf(T item) { return(_innerList.IndexOf(item)); }
public int IndexOf(T item) { lock (__InternalListLock) return(InternalList.IndexOf(item)); }
private void TreeView_ItemDropping(object sender, TreeViewItemDroppingEventArgs e) { var dragSource = e.DragSource as SfTreeView; var dropSource = sender as SfTreeView; IList sourceCollection = null; if (dragSource == null || (dragSource != dropSource)) { var item = e.Data.GetData("ListViewRecords") as ObservableCollection <object>; var record = item[0] as Folder; var dropPosition = e.DropPosition.ToString(); var folderData = new Folder(); var fileData = new File(); if (e.TargetNode != null) { var itemInfo = AssociatedObject.treeView.GetItemInfo(e.TargetNode.Content); int rowIndex = (int)itemInfo.ItemIndex; if (dropPosition != "None" && rowIndex != -1) { var treeViewNode = AssociatedObject.treeView.GetNodeAtRowIndex(rowIndex); if (treeViewNode == null) { return; } var data = treeViewNode.Content; var itemIndex = -1; TreeViewNode parentNode = null; if (dropPosition == "DropBelow" || dropPosition == "DropAbove") { parentNode = treeViewNode.ParentNode; if (parentNode == null) { folderData = new Folder() { FileName = record.FileName, ImageIcon = record.ImageIcon } } ; else { fileData = new File() { FileName = record.FileName, ImageIcon = record.ImageIcon }; } } else if (dropPosition == "DropAsChild") { if (!treeViewNode.IsExpanded) { AssociatedObject.treeView.ExpandNode(treeViewNode); } parentNode = treeViewNode; if (treeViewNode.Level == 0) { fileData = new File() { FileName = record.FileName, ImageIcon = record.ImageIcon }; } } if (dropPosition == "DropBelow" || dropPosition == "DropAbove") { if (treeViewNode.ParentNode != null) { IEnumerable collection = null; if (AssociatedObject.treeView.HierarchyPropertyDescriptors != null && AssociatedObject.treeView.HierarchyPropertyDescriptors.Count > 0) { foreach (var propertyDescriptor in AssociatedObject.treeView.HierarchyPropertyDescriptors) { if (propertyDescriptor.TargetType == treeViewNode.ParentNode.Content.GetType()) { var descriptors = TypeDescriptor.GetProperties(treeViewNode.ParentNode.Content.GetType()); var tempItem = descriptors.Find(AssociatedObject.treeView.ChildPropertyName, true); if (tempItem != null) { collection = tempItem.GetValue(treeViewNode.ParentNode.Content) as IEnumerable; } break; } } } else { var descriptors = TypeDescriptor.GetProperties(treeViewNode.ParentNode.Content.GetType()); var tempItem = descriptors.Find(AssociatedObject.treeView.ChildPropertyName, true); if (tempItem != null) { collection = tempItem.GetValue(treeViewNode.ParentNode.Content) as IEnumerable; } } sourceCollection = GetSourceListCollection(collection); } else { sourceCollection = GetSourceListCollection(null); } itemIndex = sourceCollection.IndexOf(data); if (dropPosition == "DropBelow") { itemIndex += 1; } } else if (dropPosition == "DropAsChild") { var descriptors = TypeDescriptor.GetProperties(treeViewNode.Content.GetType()); if (parentNode != null && parentNode.IsExpanded) { IEnumerable collection = null; var tempItem = descriptors.Find(AssociatedObject.treeView.ChildPropertyName, true); if (tempItem != null) { collection = tempItem.GetValue(treeViewNode.Content) as IEnumerable; } sourceCollection = GetSourceListCollection(collection); } if (sourceCollection == null) { var type = data.GetType().GetProperty(AssociatedObject.treeView.ChildPropertyName).PropertyType; var paramExp = System.Linq.Expressions.Expression.Parameter(type, type.Name); var instance = System.Linq.Expressions.Expression.MemberInit(System.Linq.Expressions.Expression.New(type), new List <MemberBinding>()); var lambda = System.Linq.Expressions.Expression.Lambda(instance, paramExp); var delg = lambda.Compile(); var list = delg.DynamicInvoke(new object[] { null }) as IList; if (list != null) { var tempitem = descriptors.Find(AssociatedObject.treeView.ChildPropertyName, true); tempitem.SetValue(treeViewNode.Content, list); sourceCollection = list; } } itemIndex = sourceCollection.Count; } if (parentNode != null) { sourceCollection.Insert(itemIndex, fileData); } else { sourceCollection.Insert(itemIndex, folderData); } (AssociatedObject.listView.ItemsSource as ObservableCollection <Folder>).Remove(record as Folder); e.Handled = true; } } else { sourceCollection = GetSourceListCollection(null); sourceCollection.Insert(0, record); (AssociatedObject.listView.ItemsSource as ObservableCollection <Folder>).Remove(record as Folder); } } }
/// <summary> /// Gets the index of the given child node. /// </summary> /// <param name="child">The child node.</param> /// <returns>The index.</returns> public int IndexOf(ReactShadowNode child) { return(_children?.IndexOf(child) ?? -1); }
public static double perm(List <double> F1, List <double> F2, List <double> F3, List <double> EP1, List <double> EP2, List <double> EP3) { int i, j, k; for (i = 0; i < F1.Count; i++) { for (j = 0; j < F2.Count; j++) { for (k = 0; k < F3.Count; k++) { a1[k] = Math.Round((double)F1[i] + F2[j], 4); MxratioMy[k] = Math.Round((double)F1[i] / F3[k], 4); a2[k] = Math.Round((double)F2[j] + F3[k], 4); b1[k] = Math.Round((double)(F1[i] * F2[j]) / F3[k], 4); b2[k] = Math.Round((double)(F2[j] * F3[k]) / F1[i], 4); Mx[k] = Math.Round((double)-a2[k] / b2[k], 4); My[k] = Math.Round((double)-b1[k] / a1[k], 4); Maxtrack[k] = Math.Round((double)F1[i] + 2 * F2[j] + F3[k] + (F2[j] * (((F3[k] * MxratioMy[k]) / F1[i]) + F1[i] / (F3[k] * MxratioMy[k]))), 4); templist.Add(Maxtrack[k]); if ((Mx[k] > MxratioMy[k]) && (MxratioMy[k] > My[k]) && (InputMax <= Mx[k]) && (InputMin >= My[k]) && (InputMax > InputMin) && (InputMin < InputMax) && (EPD1[k] > EPDConstrain) && (EPD1[k] == EPD2[k])) { F1List.Add(F1[i]); F2List.Add(F2[j]); F3List.Add(F3[k]); MaxtrackList.Add(Maxtrack[k]); MxList.Add(Mx[k]); MyList.Add(My[k]); } else if ((MxratioMy[k] > Mx[k]) || (My[k] > MxratioMy[k]) || (InputMax > Mx[k]) || (InputMin < My[k]) || (InputMax < InputMin) || (EPD1[k] < EPDConstrain) || (EPD1[k] != EPD2[k])) { // Do nothing here just ignore the values } } } } //check for emptiness of a List for no suitable combination of focal length if (!MaxtrackList.Any()) { Console.WriteLine("There is no suitable focal length in database for this configuration \n"); return(0); } else { // Display Tracklengths only once last element in the list is reached for (int p = 0; p < MaxtrackList.Count; p++) { if (p == MaxtrackList.Count - 1) { // Get Maximum and Minimum value of Tracklength with respective Focal lengths Console.WriteLine("Maxtrackvalue = {0} with F1 = {1}, F2 = {2} and F3 = {3} \n", MaxtrackList.Max(), F1List[MaxtrackList.IndexOf(MaxtrackList.Max())], F2List[MaxtrackList.IndexOf(MaxtrackList.Max())], F3List[MaxtrackList.IndexOf(MaxtrackList.Max())]); Console.WriteLine("The Maxtrackvalue can provide Max Magnifiaction = {0} and Min Magnification = {1} \n", MxList[MaxtrackList.IndexOf(MaxtrackList.Max())], MyList[MaxtrackList.IndexOf(MaxtrackList.Max())]); Console.WriteLine("Mintrackvalue = {0} with F1 = {1}, F2 = {2} and F3 = {3} \n", MaxtrackList.Min(), F1List[MaxtrackList.IndexOf(MaxtrackList.Min())], F2List[MaxtrackList.IndexOf(MaxtrackList.Min())], F3List[MaxtrackList.IndexOf(MaxtrackList.Min())]); Console.WriteLine("The Mintrackvalue can provide Max Magnifiaction = {0} and Min Magnification = {1} \n", MxList[MaxtrackList.IndexOf(MaxtrackList.Min())], MyList[MaxtrackList.IndexOf(MaxtrackList.Min())]); Console.WriteLine("\nRecommended option is b \n\n"); } } } Console.WriteLine("\n"); return(userinputs(F1, F2, F3, EP1, EP2, EP3)); }
private static void Main() { try { Console.Write("\n\nConnecting to {0} {1}Net via RPC at {2}...", CoinService.Parameters.CoinLongName, (CoinService.Parameters.UseTestnet ? "Test" : "Main"), CoinService.Parameters.SelectedDaemonUrl); // Network difficulty var networkDifficulty = CoinService.GetDifficulty(); Console.WriteLine("[OK]\n\n{0} Network Difficulty: {1}", CoinService.Parameters.CoinLongName, networkDifficulty.ToString("#,###", CultureInfo.InvariantCulture)); // Mining info var miningInfo = CoinService.GetMiningInfo(); Console.WriteLine("[OK]\n\n{0} NetworkHashPS: {1}", CoinService.Parameters.CoinLongName, miningInfo.NetworkHashPS.ToString("#,###", CultureInfo.InvariantCulture)); // My balance var myBalance = CoinService.GetBalance(); Console.WriteLine("\nMy balance: {0} {1}", myBalance, CoinService.Parameters.CoinShortName); // Current block Console.WriteLine("Current block: {0}", CoinService.GetBlockCount().ToString("#,#", CultureInfo.InvariantCulture)); // Wallet state Console.WriteLine("Wallet state: {0}", CoinService.IsWalletEncrypted() ? "Encrypted" : "Unencrypted"); // Keys and addresses if (myBalance > 0) { // My non-empty addresses Console.WriteLine("\n\nMy non-empty addresses:"); var myNonEmptyAddresses = CoinService.ListReceivedByAddress(); foreach (var address in myNonEmptyAddresses) { Console.WriteLine("\n--------------------------------------------------"); Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(address.Account) ? "(no label)" : address.Account)); Console.WriteLine("Address: " + address.Address); Console.WriteLine("Amount: " + address.Amount); Console.WriteLine("Confirmations: " + address.Confirmations); Console.WriteLine("--------------------------------------------------"); } // My private keys if (bool.Parse(ConfigurationManager.AppSettings["ExtractMyPrivateKeys"]) && myNonEmptyAddresses.Count > 0 && CoinService.IsWalletEncrypted()) { const short secondsToUnlockTheWallet = 30; Console.Write("\nWill now unlock the wallet for " + secondsToUnlockTheWallet + ((secondsToUnlockTheWallet > 1) ? " seconds" : " second") + "..."); CoinService.WalletPassphrase(CoinService.Parameters.WalletPassword, secondsToUnlockTheWallet); Console.WriteLine("[OK]\n\nMy private keys for non-empty addresses:\n"); foreach (var address in myNonEmptyAddresses) { Console.WriteLine("Private Key for address " + address.Address + ": " + CoinService.DumpPrivKey(address.Address)); } Console.Write("\nLocking wallet..."); CoinService.WalletLock(); Console.WriteLine("[OK]"); } // My transactions Console.WriteLine("\n\nMy transactions: "); var myTransactions = CoinService.ListTransactions(null, int.MaxValue, 0); foreach (var transaction in myTransactions) { Console.WriteLine("\n---------------------------------------------------------------------------"); Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(transaction.Account) ? "(no label)" : transaction.Account)); Console.WriteLine("Address: " + transaction.Address); Console.WriteLine("Category: " + transaction.Category); Console.WriteLine("Amount: " + transaction.Amount); Console.WriteLine("Fee: " + transaction.Fee); Console.WriteLine("Confirmations: " + transaction.Confirmations); Console.WriteLine("BlockHash: " + transaction.BlockHash); Console.WriteLine("BlockIndex: " + transaction.BlockIndex); Console.WriteLine("BlockTime: " + transaction.BlockTime + " - " + UnixTime.UnixTimeToDateTime(transaction.BlockTime)); Console.WriteLine("TxId: " + transaction.TxId); Console.WriteLine("Time: " + transaction.Time + " - " + UnixTime.UnixTimeToDateTime(transaction.Time)); Console.WriteLine("TimeReceived: " + transaction.TimeReceived + " - " + UnixTime.UnixTimeToDateTime(transaction.TimeReceived)); if (!string.IsNullOrWhiteSpace(transaction.Comment)) { Console.WriteLine("Comment: " + transaction.Comment); } if (!string.IsNullOrWhiteSpace(transaction.OtherAccount)) { Console.WriteLine("Other Account: " + transaction.OtherAccount); } if (transaction.WalletConflicts != null && transaction.WalletConflicts.Any()) { Console.Write("Conflicted Transactions: "); foreach (var conflictedTxId in transaction.WalletConflicts) { Console.Write(conflictedTxId + " "); } Console.WriteLine(); } Console.WriteLine("---------------------------------------------------------------------------"); } // Transaction Details Console.WriteLine("\n\nMy transactions' details:"); foreach (var transaction in myTransactions) { // Move transactions don't have a txId, which this logic fails for if (transaction.Category == "move") { continue; } var localWalletTransaction = CoinService.GetTransaction(transaction.TxId); IEnumerable <PropertyInfo> localWalletTrasactionProperties = localWalletTransaction.GetType().GetProperties(); IList <GetTransactionResponseDetails> localWalletTransactionDetailsList = localWalletTransaction.Details.ToList(); Console.WriteLine("\nTransaction\n-----------"); foreach (var propertyInfo in localWalletTrasactionProperties) { var propertyInfoName = propertyInfo.Name; if (propertyInfoName != "Details" && propertyInfoName != "WalletConflicts") { Console.WriteLine(propertyInfoName + ": " + propertyInfo.GetValue(localWalletTransaction, null)); } } foreach (var details in localWalletTransactionDetailsList) { IEnumerable <PropertyInfo> detailsProperties = details.GetType().GetProperties(); Console.WriteLine("\nTransaction details " + (localWalletTransactionDetailsList.IndexOf(details) + 1) + " of total " + localWalletTransactionDetailsList.Count + "\n--------------------------------"); foreach (var propertyInfo in detailsProperties) { Console.WriteLine(propertyInfo.Name + ": " + propertyInfo.GetValue(details, null)); } } } // Unspent transactions Console.WriteLine("\nMy unspent transactions:"); var unspentList = CoinService.ListUnspent(); foreach (var unspentResponse in unspentList) { IEnumerable <PropertyInfo> detailsProperties = unspentResponse.GetType().GetProperties(); Console.WriteLine("\nUnspent transaction " + (unspentList.IndexOf(unspentResponse) + 1) + " of " + unspentList.Count + "\n--------------------------------"); foreach (var propertyInfo in detailsProperties) { Console.WriteLine(propertyInfo.Name + " : " + propertyInfo.GetValue(unspentResponse, null)); } } } Console.ReadLine(); } catch (RpcInternalServerErrorException exception) { var errorCode = 0; var errorMessage = string.Empty; if (exception.RpcErrorCode.GetHashCode() != 0) { errorCode = exception.RpcErrorCode.GetHashCode(); errorMessage = exception.RpcErrorCode.ToString(); } Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty); } catch (Exception exception) { Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception); } }
public int indexOfSearchPath(String pathname) { return(searchPaths.IndexOf(pathname)); }
/// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"></see>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"></see>.</param> /// <returns> /// The index of item if found in the list; otherwise, -1. /// </returns> public int IndexOf(T item) { Load("IndexOf"); return(_list.IndexOf(item)); }
public int IndexOf(T item) => objects.IndexOf(item);
private protected override int IndexOfCore(object value) { return(m_vector?.IndexOf(value) ?? -1); }
public int IndexOf(DiffLine item) { return(_lines.IndexOf(item)); }