/// <summary> /// Safe conversion to array of values /// </summary> /// <returns></returns> public TValue[] SafeGetValueArray() { lock (_syncObject) { return(ArrayExt.ToArray <TValue>(base.Values)); } }
public static IEnumerable <MemberInfo> GetMembers(this Type type, bool includeProperties = true, bool includeFields = false, bool includeNonPublic = false) { BindingFlags flags = (BindingFlags.Public | BindingFlags.Instance); if (includeNonPublic) { flags |= BindingFlags.NonPublic; } if (includeProperties && includeFields) { MemberInfo[] properties = type.GetProperties(flags).Where(x => x.CanRead).ToArray <MemberInfo>(); MemberInfo[] fields = type.GetNonStaticFields(flags); MemberInfo[] allValues = ArrayExt.Combine(properties, fields); return(allValues); } if (includeProperties) { MemberInfo[] properties = type.GetProperties(flags).Where(x => x.CanRead).ToArray <MemberInfo>(); return(properties); } if (includeFields) { MemberInfo[] fields = type.GetNonStaticFields(flags); return(fields); } return(null); }
public void ShrinkTest() { string[] test; string[] expected; string[] actual; test = new string[] { }; actual = ArrayExt.Shrink(test, 0, 0); expected = new string[] { }; Assert.AreEqual(0, actual.Length); test = new string[] { "Hi", "Bye" }; actual = ArrayExt.Shrink(test, 0, 1); expected = new string[] { "Hi", "Bye" }; AssertEx.AreEqual(expected, actual); test = new string[] { "Hi", "Bye" }; actual = ArrayExt.Shrink(test, 0, 0); expected = new string[] { "Hi" }; AssertEx.AreEqual(expected, actual); test = new string[] { "Hi", "Bye" }; actual = ArrayExt.Shrink(test, 1, 1); expected = new string[] { "Bye" }; AssertEx.AreEqual(expected, actual); }
/// <summary> /// Safe conversion to array of keys /// </summary> /// <returns></returns> public TKey[] SafeGetKeyArray() { lock (_syncObject) { return(ArrayExt.ToArray <TKey>(base.Keys)); } }
public void MaxValueItems_ReturnIntMaxVal() { int[] sourceArray = new int[5] { 3, 4565, int.MaxValue, 654, 12 }; Assert.AreEqual(int.MaxValue, ArrayExt.MaxValueItems(sourceArray)); }
public void SendUdp(EndPoint endPoint, Socket socket, ref Byte[] buffer, ISerializer messageContents) { UInt32 messageContentLength = (messageContents == null) ? 0 : messageContents.SerializationLength(); UInt32 totalMessageLength = SerializationLength() + messageContentLength; ArrayExt.EnsureCapacityNoCopy(ref buffer, totalMessageLength); if (RpcPerformanceLog.rpcMessageSerializationLogger != null) { RpcPerformanceLog.StartSerialize(); } UInt32 offset = Serialize(buffer, 0); if (messageContents != null) { offset = messageContents.Serialize(buffer, offset); } if (RpcPerformanceLog.rpcMessageSerializationLogger != null) { RpcPerformanceLog.StopSerializationAndLog("RpcSerializationTime"); } if (offset != totalMessageLength) { throw new InvalidOperationException(String.Format("[CodeBug] The caclulated serialization length of RpcMessage '{0}' was {1} but actual size was {2}", DataStringBuilder.DataString(this, new StringBuilder()), totalMessageLength, offset)); } socket.SendTo(buffer, 0, (Int32)totalMessageLength, SocketFlags.None, endPoint); }
IEnumerable <MemberInfoWithMeta> GetIndexedTypeMembers(Type type) { List <KeyValuePair <int, MemberInfoWithMeta> > indexedMemberInfo = new List <KeyValuePair <int, MemberInfoWithMeta> >(20); var flags = (BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); MemberInfo[] properties = type.GetProperties(flags).Where(x => x.CanRead).ToArray(); MemberInfo[] fields = type.GetFields(flags).Where(x => !x.Name.EndsWith("k__BackingField") && x.IsStatic == false).ToArray(); MemberInfo[] allValues = ArrayExt.Combine(properties, fields); foreach (MemberInfo property in allValues) { object[] attributes = property.GetCustomAttributes(true); int index = -1; bool skipType = false; bool skipIsNull = false; foreach (Attribute eachAttr in attributes) { if (eachAttr is Ignore) { index = -1; break; } Index indexAttr = eachAttr as Index; if (indexAttr != null) { index = indexAttr.Value; continue; } SkipMetaData skipAttr = eachAttr as SkipMetaData; if (skipAttr != null) { skipType = skipAttr.Type; skipIsNull = skipAttr.IsNull; } } if (index != -1) { MemberInfoWithMeta memberInfo = new MemberInfoWithMeta(); memberInfo.Info = property; memberInfo.SkipIsNull = skipIsNull; memberInfo.SkipType = skipType; indexedMemberInfo.Add(new KeyValuePair <int, MemberInfoWithMeta>(index, memberInfo)); } } indexedMemberInfo.Sort((x, y) => x.Key.CompareTo(y.Key)); var members = new List <MemberInfoWithMeta>(indexedMemberInfo.Count); foreach (KeyValuePair <int, MemberInfoWithMeta> kvp in indexedMemberInfo) { members.Add(kvp.Value); } return(members); }
public override string[] GetAllBindingNames() { if (!ReferenceEquals(_bindingObject, null)) { return(_bindingObject.GetOwnProperties().Select(x => x.Key).ToArray()); } return(ArrayExt.Empty <string>()); }
public void FindIndex_ArgumentOutOfRangeException_Test() { Assert.Throws <ArgumentOutOfRangeException>(() => ArrayExt.FindIndex(new double[5] { 25.65467, 65.6546587, 42.654654, 45.654654, 7.65498 }, -0.0001)); Assert.Throws <ArgumentOutOfRangeException>(() => ArrayExt.FindIndex(new double[5] { 25.65467, 65.6546587, 42.654654, 45.654654, 7.65498 }, 2)); }
public void GenericConvertTest() { string[] arr = new string[] { "1", "2", "3" }; Type elementType = typeof(int); int[] expected = new int[] { 1, 2, 3 }; int[] actual; actual = ArrayExt.Convert <int>(arr); AssertEx.AreEqual(expected, actual); }
public void StandardConvertTest() { string[] arr = new string[] { "1", "2", "3" }; Type elementType = typeof(int); int[] expected = new int[] { 1, 2, 3 }; int[] actual; actual = (int[])ArrayExt.Convert(arr, elementType); AssertEx.AreEqual(expected, actual); }
public override void Run() { base.Run(); try { RiotSpawn riot = null; if (riots.Count > 0) { foreach (RiotSpawn riotSpawn in riots) { if (riotSpawn.rioters.Count < Settings.riotMaxSize) { riot = riotSpawn; } } } if (riot == null) { riot = new RiotSpawn(GetRallyPoint(Util.GetPlayerStartLandmass())); } ArrayExt <Villager> villagers = World.inst.GetVillagersForLandMass(Util.GetPlayerStartLandmass()); int numRioters = Settings.riotStartSize; int num = (int)((float)numRioters / Settings.riotMaxSize); for (int k = 0; k < num + 1; k++) { while (riot.rioters.Count < Settings.riotMaxSize && numRioters > 0) { Villager vil = Player.inst.Workers.data[SRand.Range(0, Player.inst.Workers.Count - 1)]; RioterJob newRioter = new RioterJob(riot); newRioter.AssignEmployee(vil); newRioter.employer = riot; JobSystem.inst.AddNewJob(newRioter, JobCategory.Homemakers); numRioters -= 1; } if (numRioters > 0) { riots.Add(riot); riot = new RiotSpawn(GetRallyPoint(Util.GetPlayerStartLandmass())); } else { break; } } KingdomLog.TryLog("riotAssembling", "My Lord, a riot has begun to assemble!", KingdomLog.LogStatus.Important, 20, riot.GetRallyPoint().Center); }catch (Exception ex) { KingdomLog.TryLog("Exception-" + SRand.Range(0, 100), ex.Message + "\n" + ex.StackTrace, KingdomLog.LogStatus.Neutral); } }
public string[] GetKeys(string section) { if (!_ini.ContainsKey(section)) { return(ArrayExt.Empty <string>()); } return(!_ini.ContainsKey(section) ? ArrayExt.Empty <string>() : _ini[section].Keys.ToArray()); }
public static void Sample_Einsteins_Puzzle() { //this example shows how to solve Einstein's puzzle //go to http://en.wikipedia.org/wiki/Einstein's_Puzzle for more information on puzzle var solutions = from n in ArrayExt.Enum <Nationality>().ToConstraintList(5) from c in ArrayExt.Enum <HouseColor>().ToConstraintList(5) from s in ArrayExt.Enum <Smoke>().ToConstraintList(5) from d in ArrayExt.Enum <Drink>().ToConstraintList(5) from p in ArrayExt.Enum <Pet>().ToConstraintList(5) from i in 0.To(4).ToConstraintIndex() where Constraint.AllDifferent(n) where Constraint.AllDifferent(c) where Constraint.AllDifferent(s) where Constraint.AllDifferent(d) where Constraint.AllDifferent(p) where n[0] == Nationality.Norwegian where d[2] == Drink.Milk where (n[i] == Nationality.British) == (c[i] == HouseColor.Red) where (n[i] == Nationality.German) == (s[i] == Smoke.Prince) where (c[i] == HouseColor.Yellow) == (s[i] == Smoke.DunHill) where (n[i] == Nationality.Danish) == (d[i] == Drink.Tea) where (c[i] == HouseColor.Green) == (d[i] == Drink.Coffee) where (s[i] == Smoke.BlueMaster) == (d[i] == Drink.Beer) where (n[i] == Nationality.Swedish) == (p[i] == Pet.Dog) where (s[i] == Smoke.PallMall) == (p[i] == Pet.Bird) where (c[i] == HouseColor.Green) == (c[i + 1] == HouseColor.White) where (p[i] == Pet.Cat) ? (s[i - 1] == Smoke.Blend || s[i + 1] == Smoke.Blend) : true where ((p[i] == Pet.Horse) ? (s[i - 1] == Smoke.DunHill || s[i + 1] == Smoke.DunHill) : true) where ((n[i] == Nationality.Norwegian) ? (c[i - 1] == HouseColor.Blue || c[i + 1] == HouseColor.Blue) : true) where ((s[i] == Smoke.Blend) ? (d[i - 1] == Drink.Water || d[i + 1] == Drink.Water) : true) select 0.To(4).Select(x => new { Nationality = n[x], HouseColor = c[x], Smoke = s[x], Drink = d[x], Pet = p[x] }); //show results Console.WriteLine("\tNationality\tHouseColor\tSmoke\t\tDrink\t\tPet"); Console.WriteLine(new string('-', 80)); solutions.First().ForEach((man, i) => Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", i + 1, man.Nationality.ToString().PadRight(12), man.HouseColor.ToString().PadRight(12), man.Smoke.ToString().PadRight(12), man.Drink.ToString().PadRight(12), man.Pet.ToString().PadRight(12)) ); }
/// <summary> /// 使用指定的类型转换器初始化 <see cref="ConverterProvider"/> 类的新实例。 /// </summary> /// <param name="converter">类型转换器。</param> /// <param name="inputType">类型转换器的输入类型。</param> /// <param name="outputType">类型转换器的输出类型。</param> public ConverterProvider(Delegate converter, Type inputType, Type outputType) { Contract.Requires(converter != null && inputType != null && outputType != null); originType = inputType; toDict = new Dictionary <Type, Delegate>(1) { { outputType, converter } }; fromDict = new Dictionary <Type, Delegate>(); toDict = new Dictionary <Type, Delegate>(); subProvider = ArrayExt.Empty <IConverterProvider>(); }
private ThroneRoom FindTargetTreasury() { ThroneRoom best = null; if (Player.inst.DoesAnyBuildingHaveUniqueNameOnLandMass("throneroom", Host.landMass)) { ArrayExt <Building> throneRooms = Player.inst.GetBuildingListForLandMass(Host.landMass, "throneroom".GetHashCode()); best = throneRooms.RandomElement().GetComponent <ThroneRoom>(); } return(best); }
//public methods public BitArray SolveNonogram(int[][] rows, int[][] cols) { var length = rows.Length * cols.Length; var solutions = CollectionExt.Booleans.Backtrack( new NonogramState(new int[cols.Length], ArrayExt.Create(cols.Length, -1), 0, -1, new BitArray(length), 0), (state, b, i) => state.AssignValue(rows, cols, b), state => state.Position == length); solutions.AppendConstraint(state => b => state.TestValue(rows, cols, b)); return(solutions.SelectResults(set => set.Table).First()); }
public static JsValue[] Skip(this JsValue[] args, int count) { var newLength = args.Length - count; if (newLength <= 0) { return(ArrayExt.Empty <JsValue>()); } var array = new JsValue[newLength]; Array.Copy(args, count, array, 0, newLength); return(array); }
static Rotator() { var rotation = ArrayExt.Range(0, MaxPositions); var sideLength = MathF.Sqrt(MaxPositions).RoundToInt(); for (var rot = 0; rot < MaxRotations; rot++) { for (var pos = 0; pos < MaxPositions; pos++) { RotationsArray[pos * MaxRotations + rot] = rotation[pos]; } rotation = rotation.RotateClockwise(sideLength); } }
static void Main() { int[] arrayInt = RandomExt.GetRandomArrayInt(10, -30, 30); ArrayExt.Sort(arrayInt, (a, b) => ((IComparable)a).CompareTo(b) == -1); ConsoleExt.WriteArrayIFormattable(arrayInt); Console.WriteLine(); double[] arrayDouble = RandomExt.GetRandomArrayDouble(5); ArrayExt.Sort(arrayDouble, (a, b) => ((IComparable)a).CompareTo(b) == 1); ConsoleExt.WriteArrayIFormattable(arrayDouble); Console.ReadKey(); }
/// <summary> /// 使用指定的错误消息和对导致此异常的内部异常的引用初始化 <see cref="AggregateSourceException"/> 类的新实例。 /// </summary> /// <param name="message">解释异常原因的错误消息。</param> /// <param name="innerException">导致当前异常的异常。</param> public AggregateSourceException(string message, SourceException innerException) : base(message, innerException) { if (innerException == null) { this.innerExps = ArrayExt.Empty <SourceException>(); this.innerExpsCollection = ReadOnlyCollection <SourceException> .Empty; } else { this.innerExps = new[] { innerException }; this.innerExpsCollection = new ReadOnlyCollection <SourceException>(innerExps); } }
private static byte[] ReadFirstTwoByteOfFile(string fileName) { byte[] firstTwoByte = ArrayExt.Empty <byte>(); try { using (var iniFile = File.OpenRead(fileName)) { firstTwoByte = new byte[2]; iniFile.Read(firstTwoByte, 0, 2); } } catch { /* ignored */ } return(firstTwoByte); }
IEnumerable <MemberInfoWithMeta> GetTypeMembers(Type type, bool includeFields = false, bool includeNonPublic = false) { var members = new List <MemberInfoWithMeta>(); var flags = (BindingFlags.Public | BindingFlags.Instance); if (IncludeNonPublicProperties) { flags |= BindingFlags.NonPublic; } MemberInfo[] properties = type.GetProperties(flags).Where(x => x.CanRead).ToArray(); MemberInfo[] fields = type.GetFields(flags).Where(x => !x.Name.EndsWith("k__BackingField") && x.IsStatic == false).ToArray(); MemberInfo[] allValues = ArrayExt.Combine(properties, fields); foreach (MemberInfo property in allValues) { object[] attributes = property.GetCustomAttributes(true); MemberInfoWithMeta memberInfo = new MemberInfoWithMeta(); memberInfo.Info = property; bool ignore = false; foreach (Attribute eachAttr in attributes) { if (eachAttr is Ignore) { ignore = true; break; } SkipMetaData skipAttr = eachAttr as SkipMetaData; if (skipAttr == null) { continue; } memberInfo.SkipType = skipAttr.Type; memberInfo.SkipIsNull = skipAttr.IsNull; } if (ignore) { continue; } members.Add(memberInfo); } return(members); }
public static void Main(string[] args) { var arr2 = new[] { 7, 1, 2, 3, 4, 5, 6, 7, 68, 69, 70, 15, 17 }; int[] arr = new int[10]; Random rnd = new Random(); for (int i = 0; i < arr.Length; i++) { arr[i] = rnd.Next(-100000, 100000); } Console.WriteLine($"max item {ArrayExt.MaxValueItems(arr)}"); Console.WriteLine(); Console.ReadKey(); }
private static void SetChunkVert(TerrainChunk chunk, int gridX, int gridZ, float y) { ArrayExt <ArrayExt <int> > indexLookup = typeof(TerrainChunk).GetProperty("indexLookup", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(chunk) as ArrayExt <ArrayExt <int> >; int meshSizeX = (int)typeof(TerrainChunk).GetProperty("meshSizeX", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(chunk); ArrayExt <int> arrayExt = indexLookup.data[gridX + gridZ * meshSizeX]; int i = 0; int count = arrayExt.Count; while (i < count) { int num = arrayExt.data[i]; //Vector3 vector = chunk.verticies[num]; //chunk.verticies[num] = new Vector3(vector.x, y, vector.z); i++; } chunk.dirtyVerts = true; }
/// <summary> /// 使用指定的错误消息和对导致此异常的内部异常的引用初始化 <see cref="AggregateSourceException"/> 类的新实例。 /// </summary> /// <param name="message">解释异常原因的错误消息。</param> /// <param name="innerException">导致当前异常的异常。</param> public AggregateSourceException(string message, Exception innerException) : base(message, innerException) { if (innerException == null) { this.innerExps = ArrayExt.Empty <SourceException>(); this.innerExpsCollection = ReadOnlyCollection <SourceException> .Empty; } else { SourceException sourceExp = innerException as SourceException; if (sourceExp == null) { throw CommonExceptions.InvalidCast(innerException.GetType(), typeof(SourceException)); } this.innerExps = new[] { sourceExp }; this.innerExpsCollection = new ReadOnlyCollection <SourceException>(innerExps); } }
static public void OpenGreatLibrary() { if (greatLibrary == null) { for (int landMassIndex = 0; landMassIndex < Player.inst.PlayerLandmassOwner.ownedLandMasses.Count; landMassIndex++) { ArrayExt <Building> greatLibraries = Player.inst.GetBuildingListForLandMass(Player.inst.PlayerLandmassOwner.ownedLandMasses.data[landMassIndex], World.greatLibraryName.GetHashCode()); if (greatLibraries.Count > 0) { greatLibrary = greatLibraries.data[0]; break; } } } if (greatLibrary != null) { GameUI.inst.SelectBuilding(greatLibrary); } }
static public void OpenAdvisers() { if (keep == null) { for (int landMassIndex = 0; landMassIndex < Player.inst.PlayerLandmassOwner.ownedLandMasses.Count; landMassIndex++) { ArrayExt <Building> keeps = Player.inst.GetBuildingListForLandMass(Player.inst.PlayerLandmassOwner.ownedLandMasses.data[landMassIndex], World.keepHash); if (keeps.Count > 0) { keep = keeps.data[0]; break; } } } if (keep != null) { GameUI.inst.SelectBuilding(keep); } }
/// <summary> /// 将当前类型转换器提供者与指定的 <see cref="ConverterProvider"/> 合并。 /// </summary> /// <param name="provider">要合并的类型转换器提供者。</param> private void CombineWith(ConverterProvider provider) { Contract.Requires(provider != null && OriginType == provider.OriginType); foreach (var pair in provider.fromDict) { fromDict.Add(pair.Key, pair.Value); } foreach (var pair in provider.toDict) { toDict.Add(pair.Key, pair.Value); } if (subProvider.Length == 0) { subProvider = provider.subProvider; } else if (provider.subProvider.Length > 0) { subProvider = ArrayExt.Combine(subProvider, provider.subProvider); } }
/// <summary> /// 将当前类型转换器提供者与指定的 <see cref="ConverterProvider"/> 合并。 /// </summary> /// <param name="provider">要合并的类型转换器提供者。</param> private void CombineWith(ConverterProvider provider) { Contract.Requires(provider != null && this.OriginType == provider.OriginType); foreach (KeyValuePair <Type, Delegate> pair in provider.fromDict) { this.fromDict.Add(pair.Key, pair.Value); } foreach (KeyValuePair <Type, Delegate> pair in provider.toDict) { this.toDict.Add(pair.Key, pair.Value); } if (this.subProvider.Length == 0) { this.subProvider = provider.subProvider; } else if (provider.subProvider.Length > 0) { this.subProvider = ArrayExt.Combine(this.subProvider, provider.subProvider); } }