public Hashtable LookupProfiles() { if (!StartService(SVC_MCINSTALL)) { return(null); } Dictionary <string, object> dict = new Dictionary <string, object> { { "RequestType", "GetProfileList" } }; Dictionary <string, object> received = TransferPlist(dict); Flush(); List <object> keys = received[MobileDevice.OrderedIdentifiers] as List <object>; int length = keys.Count; Dictionary <string, object> metas = received[MobileDevice.ProfileMetadata] as Dictionary <string, object>; Hashtable profiles = new Hashtable(); for (int i = 0; i < length; i++) { string identifier = keys[i] as string; Dictionary <string, object> meta = metas[identifier] as Dictionary <string, object>; string displayname = meta.Find(MobileDevice.PayloadDisplayName) as string; string organization = meta.Find(MobileDevice.PayloadOrganization) as string; Hashtable m = new Hashtable(); m.Add(MobileDevice.PayloadIdentifier, identifier); m.Add(MobileDevice.PayloadDisplayName, displayname); m.Add(MobileDevice.PayloadOrganization, organization); profiles.Add(identifier, m); } return(profiles); }
public object Value(object item, bool isRef = false) { if (item == null) { return(null); } var type = item.GetType(); if (IsPrimitiveType(type)) { return(item); } var childs = Properties(type); var idProperty = childs.FirstOrDefault(child => child.Name == IdPropertyByType.Find(type)); var refProperties = Type_References.Find(type); return(SaveId(item, idProperty)); //return new QSharp.QNode(, // isRef // ? Array<QSharp.QNode>.Empty // : childs // .Where(child => child != idProperty) // .Select(prop => // { // var value = SaveProp(item, prop, refProperties.Find(prop.Name) != null); // return value != null && value.Any() ? new QSharp.QNode(prop.Name, value) : null; // }) // .Where(value => value != null) // .ToArray() //); }
public static Map Load(string path, IModHelper helper) { Dictionary <TileSheet, Texture2D> tilesheets = Helper.Reflection.GetField <Dictionary <TileSheet, Texture2D> >(Game1.mapDisplayDevice, "m_tileSheetTextures").GetValue(); Map map = tmx2map(Path.Combine(helper.DirectoryPath, path)); string fileName = new FileInfo(path).Name; foreach (TileSheet t in map.TileSheets) { string[] seasons = new string[] { "summer_", "fall_", "winter_" }; string tileSheetPath = path.Replace(fileName, t.ImageSource + ".png"); FileInfo tileSheetFile = new FileInfo(Path.Combine(helper.DirectoryPath, tileSheetPath)); FileInfo tileSheetFileVanilla = new FileInfo(Path.Combine(PyUtils.getContentFolder(), "Content", t.ImageSource + ".xnb")); if (tileSheetFile.Exists && !tileSheetFileVanilla.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource).Key == null) { helper.Content.Load <Texture2D>(tileSheetPath).inject(t.ImageSource); if (t.ImageSource.Contains("spring_")) { foreach (string season in seasons) { string seasonPath = path.Replace(fileName, t.ImageSource.Replace("spring_", season)); FileInfo seasonFile = new FileInfo(Path.Combine(helper.DirectoryPath, seasonPath + ".png")); if (seasonFile.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource.Replace("spring_", season)).Key == null) { helper.Content.Load <Texture2D>(seasonPath + ".png").inject(t.ImageSource.Replace("spring_", season)); helper.Content.Load <Texture2D>(seasonPath + ".png").inject("Maps/" + t.ImageSource.Replace("spring_", season)); } } } } } map.LoadTileSheets(Game1.mapDisplayDevice); return(map); }
public static Map Load(string path, IModHelper helper, bool syncTexturesToClients, IContentPack contentPack) { Dictionary <TileSheet, Texture2D> tilesheets = Helper.Reflection.GetField <Dictionary <TileSheet, Texture2D> >(Game1.mapDisplayDevice, "m_tileSheetTextures").GetValue(); Map map = tmx2map(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, path)); string fileName = new FileInfo(path).Name; Monitor.Log(path); foreach (TileSheet t in map.TileSheets) { t.ImageSource = t.ImageSource.Replace(".png", ""); string[] seasons = new string[] { "summer_", "fall_", "winter_" }; string tileSheetPath = path.Replace(fileName, t.ImageSource + ".png"); FileInfo tileSheetFile = new FileInfo(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, tileSheetPath)); FileInfo tileSheetFileVanilla = new FileInfo(Path.Combine(PyUtils.getContentFolder(), "Content", t.ImageSource + ".xnb")); if (tileSheetFile.Exists && !tileSheetFileVanilla.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource).Key == null) { Texture2D tilesheet = contentPack != null?contentPack.LoadAsset <Texture2D>(tileSheetPath) : helper.Content.Load <Texture2D>(tileSheetPath); tilesheet.inject(t.ImageSource); tilesheet.inject("Maps/" + t.ImageSource); if (syncTexturesToClients && Game1.IsMultiplayer && Game1.IsServer) { foreach (Farmer farmhand in Game1.otherFarmers.Values) { PyNet.sendGameContent(t.ImageSource, tilesheet, farmhand, (b) => Monitor.Log("Syncing " + t.ImageSource + " to " + farmhand.Name + ": " + (b ? "successful" : "failed"), b ? LogLevel.Info : LogLevel.Warn)); } } if (t.ImageSource.Contains("spring_")) { foreach (string season in seasons) { string seasonPath = path.Replace(fileName, t.ImageSource.Replace("spring_", season)); FileInfo seasonFile = new FileInfo(Path.Combine(contentPack != null ? contentPack.DirectoryPath : helper.DirectoryPath, seasonPath + ".png")); if (seasonFile.Exists && tilesheets.Find(k => k.Key.ImageSource == t.ImageSource.Replace("spring_", season)).Key == null) { Texture2D seasonTilesheet = contentPack != null?contentPack.LoadAsset <Texture2D>(seasonPath + ".png") : helper.Content.Load <Texture2D>(seasonPath + ".png"); string seasonTextureName = t.ImageSource.Replace("spring_", season); seasonTilesheet.inject(seasonTextureName); seasonTilesheet.inject("Maps/" + seasonTextureName); if (syncTexturesToClients && Game1.IsMultiplayer && Game1.IsServer) { foreach (Farmer farmhand in Game1.otherFarmers.Values) { PyNet.sendGameContent(new string[] { seasonTextureName, "Maps/" + seasonTextureName }, seasonTilesheet, farmhand, (b) => Monitor.Log("Syncing " + seasonTextureName + " to " + farmhand.Name + ": " + (b ? "successful" : "failed"), b ? LogLevel.Info : LogLevel.Warn)); } } } } } } } map.LoadTileSheets(Game1.mapDisplayDevice); return(map); }
private static void CopyTypeMembers( TypeDefinition sourceType, TypeDefinition targetType, Dictionary <IMemberDefinition, IMemberDefinition> memberMap) { var targetModule = targetType.Module; foreach (var attr in sourceType.CustomAttributes) { var newAttr = new CustomAttribute(targetModule.ImportReference(attr.Constructor), attr.GetBlob()); targetType.CustomAttributes.Add(newAttr); } foreach (var ifaceRef in sourceType.Interfaces) { var newIface = new InterfaceImplementation(targetModule.ImportReference(ifaceRef.InterfaceType)); targetType.Interfaces.Add(newIface); } foreach (var fieldDef in sourceType.Fields) { var newFieldDef = new FieldDefinition( fieldDef.Name, fieldDef.Attributes, memberMap.Find(fieldDef.FieldType) as TypeReference ?? targetModule.ImportReference(fieldDef.FieldType)); memberMap.Add(fieldDef, newFieldDef); targetType.Fields.Add(newFieldDef); } foreach (var methodDef in sourceType.Methods) { var newMethodDef = new MethodDefinition( methodDef.Name, methodDef.Attributes, memberMap.Find(methodDef.ReturnType) as TypeReference ?? targetModule.ImportReference(methodDef.ReturnType)); memberMap.Add(methodDef, newMethodDef); targetType.Methods.Add(newMethodDef); } foreach (var propDef in sourceType.Properties) { var newPropDef = new PropertyDefinition( propDef.Name, propDef.Attributes, memberMap.Find(propDef.PropertyType) as TypeReference ?? targetModule.ImportReference(propDef.PropertyType)); memberMap.Add(propDef, newPropDef); targetType.Properties.Add(newPropDef); } foreach (var eventDef in sourceType.Events) { var newEventDef = new EventDefinition( eventDef.Name, eventDef.Attributes, memberMap.Find(eventDef.EventType) as TypeReference ?? targetModule.ImportReference(eventDef.EventType)); memberMap.Add(eventDef, newEventDef); targetType.Events.Add(newEventDef); } foreach (var nestedTypeDef in sourceType.NestedTypes) { var newNestedTypeDef = (TypeDefinition)memberMap[nestedTypeDef]; CopyTypeMembers(nestedTypeDef, newNestedTypeDef, memberMap); } }
public string ProcessRequest(Dictionary<string, string> parameters, JsonData json) { var uri = parameters.Find("SCRIPT_NAME") + parameters.Find("PATH_INFO"); var queryString = parameters.Find("QUERY_STRING"); Console.WriteLine("{0} {1}, {2}", uri, queryString, Handlers.Select(pair => pair.Key).FirstOrDefault()); var handlerPair = Handlers.FirstOrDefault(pair => uri?.StartsWith(pair.Key) ?? false); if (handlerPair.Value == null) { return "<html><body>invalid page</body></html>"; } var handler = handlerPair.Value; var pageName = handlerPair.Key; if (uri.EndsWith(".js")) { var query = queryString.OrEmpty().Split('&').Select(pair => pair.Split('=')) .ToDictionary(ss => ss.FirstOrDefault(), ss => ss.ElementAtOrDefault(1)); var prevCycle = int.Parse(query.Find("cycle")); var prevUpdate = Updates.FirstOrDefault(_update => _update.Cycle == prevCycle); var prevPage = prevUpdate != null ? prevUpdate.Page : null; var update = PushUpdate(null); var result = handler(pageName, update.Cycle, json); //lock (locker) //{ // update.Page = result.Html; //} var page = result.Html; var commands = HtmlJavaScriptDiffer.JsSync(new HElementProvider(), prevPage == null ? null : prevPage.Element("body"), page.Element("body")).ToArray(); var jupdate = new Dictionary<string, object>() { { "cycle", update.Cycle }, { "prev_cycle", prevCycle }, { "commands", commands } }; var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return jsSerializer.Serialize(jupdate); } else { var update = PushUpdate(null); var result = handler(pageName, update.Cycle, json); var page = result.Html; if (!uri.EndsWith(".raw.html")) page = h.Html(new HRaw(page.Element("head")?.ToString()), h.Body()); //lock (locker) //{ // update.Page = page; //} return page.ToString(); } }
public void Initial(Receive behavior) { Requires.NotNull(behavior, nameof(behavior)); var name = behavior.Method.Name; var configured = states.Find(name); Initial(configured ?? new State(name, behavior)); }
/// <summary> /// 向微信发送消息 /// </summary> /// <param name="userAccounts">接收人员帐号,|分开</param> /// <param name="contentJson">消息内容JSON</param> /// <param name="msgType">消息类型(text,image,voice,video,file,textcard,news,mpnews)</param> /// <param name="agentId">接收消息的应用Id(如果为0则从数据字典应用中找标题为包含消息的应用)</param> /// <returns>返回空字符串表示成功,其它为错误信息</returns> public static string SendMessage(string userAccounts, JObject contentJson, string msgType = "text", int agentId = 0) { var dicts = new Dictionary().GetChilds("EnterpriseWeiXin"); if (!dicts.Any()) { return("未在数据字典中设置微信应用"); } string corpsecret = string.Empty; if (agentId == 0) { var msgDict = dicts.Find(p => p.Title.Contains("消息")); if (null != msgDict) { agentId = msgDict.Value.ToInt(); corpsecret = msgDict.Note.Trim1(); } else { return("未找到接收消息的应用"); } } else { var dict = dicts.Find(p => p.Value.Equals(agentId.ToString())); if (null == dict) { return("未找到" + agentId + "对应的应用"); } corpsecret = dict.Note.Trim1(); } string access_token = GetAccessToken(corpsecret); string url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token; JObject jObject = new JObject { { "msgtype", msgType }, { "agentid", agentId }, { msgType, contentJson }, { "safe", 0 }, { "touser", userAccounts } }; string postJson = jObject.ToString(Newtonsoft.Json.Formatting.None); string returnJson = HttpHelper.HttpPost(url, postJson); JObject returnObject = JObject.Parse(returnJson); int errcode = returnObject.Value <int>("errcode"); if (0 != errcode) { Log.Add("发送企业微信消息发生了错误", postJson, others: "返回:" + returnJson + " URL:" + url); return(returnObject.Value <string>("errmsg")); } else { return(string.Empty); } }
public string GetActualSFPath(string sfPath) { ScriptFile overwriteSF = _overwriteSFList.Find(a => a.SFPath.EqualCode(sfPath)); if (overwriteSF != null) { sfPath = overwriteSF.SFPath; } return(sfPath); }
static void Register(ActorInterface @interface) { var registered = interfaces.Find(@interface.name); if (registered != null) { throw new ArgumentException( $"An actor with type '{@interface.name}' has been already registered"); } interfaces.Add(@interface.name, @interface); }
public static XSample LoadByDictionary(XmlReader reader) { var converterIndex = new Dictionary <string, Func <string, object> >(StringComparer.InvariantCultureIgnoreCase) { { "X", s => Convert.ToInt32(s) }, { "Y", s => s }, { "Z", s => s }, }; var index = new Dictionary <string, object>(); for (; reader.Read();) { if (reader.NodeType == XmlNodeType.Element) { reader.Read(); break; } } for (;;) { if (reader.NodeType == XmlNodeType.EndElement || reader.NodeType == XmlNodeType.None) { break; } switch (reader.NodeType) { case XmlNodeType.Element: var tag = reader.Name; reader.Read(); var converter = converterIndex.Find(tag); if (converter != null) { index[tag] = converter(reader.ReadContentAsString()); } reader.ReadOuterXml(); //var xml = reader.ReadOuterXml(); //Console.WriteLine(xml); break; default: Console.WriteLine($"{reader.NodeType}:{reader.Value}"); reader.Read(); break; } } return(new XSample(x: (int?)index.Find("X"), y: (string)index.Find("Y"), z: (string)index.Find("Z"))); }
internal void Register(IEnumerable <StreamSubscriptionSpecification> specifications) { foreach (var each in specifications) { var provider = providerSubscriptions.Find(each.Provider); if (provider == null) { provider = new List <StreamSubscriptionSpecification>(); providerSubscriptions.Add(each.Provider, provider); } provider.Add(each); } }
internal static void Register(ActorType type) { foreach (var specification in StreamSubscriptionSpecification.From(type)) { var specifications = configuration.Find(specification.Provider); if (specifications == null) { specifications = new List <StreamSubscriptionSpecification>(); configuration.Add(specification.Provider, specifications); } specifications.Add(specification); } }
internal static void Register(IEnumerable <StreamSubscriptionSpecification> specifications) { foreach (var specification in specifications) { var existent = configuration.Find(specification.Provider); if (existent == null) { existent = new List <StreamSubscriptionSpecification>(); configuration.Add(specification.Provider, existent); } existent.Add(specification); } }
public static ActorInterface Of(string name) { Requires.NotNull(name, nameof(name)); var result = names.Find(name); if (result == null) { throw new InvalidOperationException( $"Unable to map actor type name '{name}' to the corresponding actor. " + "Make sure that you've registered an actor type or the assembly containing this type"); } return(result); }
public void TestFind() { Dictionary <Type, object> dictionary = new Dictionary <Type, object>(); Assert.Null(dictionary.Find <TestClass>()); var testValue = new TestClass(); dictionary.Add(typeof(TestClass), testValue); Assert.Same(testValue, dictionary.Find <TestClass>()); dictionary.Remove(typeof(TestClass)); Assert.Null(dictionary.Find <TestClass>()); }
public static Ref Deserialize(string path, Type type) { if (type == typeof(ClientRef)) { return(ClientRef.Deserialize(path)); } if (type == typeof(ActorRef)) { return(ActorRef.Deserialize(path)); } if (type == typeof(StreamRef)) { return(StreamRef.Deserialize(path)); } var deserializer = deserializers.Find(type); if (deserializer != null) { return(deserializer(path)); } throw new InvalidOperationException("Unknown ref type: " + type); }
private SpawnRequest ServerCreateSpawnRequestForPreset( ObjectSpawnPreset preset, SpawnConfig config, IServerZone zone, int zonePositionsCount, Dictionary <ObjectSpawnPreset, int> spawnedObjectsCount) { var currentCount = spawnedObjectsCount.Find(preset); var density = preset.Density * config.DensityMultiplier; var desiredCount = this.SharedCalculatePresetDesiredCount( preset, zone, currentCount, desiredCountByDensity: (int)(density * zonePositionsCount)); var countToSpawn = Math.Max(0, desiredCount - currentCount); if (preset.SpawnLimitPerIteration.HasValue) { countToSpawn = Math.Min(countToSpawn, preset.SpawnLimitPerIteration.Value); } var useSectorDensity = preset.PresetUseSectorDensity && (density * SpawnZoneAreaSize * SpawnZoneAreaSize >= SectorDensityThreshold); return(new SpawnRequest(preset, desiredCount, currentCount, countToSpawn, density, useSectorDensity)); }
public static void GetMovieData(ref Dictionary <string, MovieData> __result) { foreach (var movie in allTheMovies.Values) { if (__result.Exists(d => d.Value.Tags.Contains("CMovieID:" + movie.Id))) { if (__result.Find(d => d.Value.Tags.Contains("CMovieID:" + movie.Id)) is KeyValuePair <string, MovieData> md && !PyTK.PyUtils.checkEventConditions(movie.Conditions, Game1.MasterPlayer)) { __result.Remove(md.Key); } continue; } if (!PyTK.PyUtils.checkEventConditions(movie.Conditions, Game1.MasterPlayer)) { continue; } if (movie.FixedMovieID != null) { MovieData fixedData = movie.GetFixedData(); fixedData.ID = movie.FixedMovieID; __result.AddOrReplace(fixedData.ID, fixedData); continue; } } }
public Func <Type, QSharp.QNode, Dictionary <string, Dictionary <object, object> >, object> GetLoader(Type type) { var loader = LoaderIndex.Find(type); if (loader == null) { if (IsNullableType(type)) { var sourceType = type.GetGenericArguments().First(); var sourceLoader = GetLoader(sourceType); loader = (_type, _q, _data) => sourceLoader(sourceType, _q, _data); } else { var uniLoader = UniLoaders.FirstOrDefault(_uniLoader => _uniLoader.IsTypeLoading(type)); if (uniLoader != null) { loader = uniLoader.Load; } else { loader = LoadStructure; } } LoaderIndex[type] = loader; } return(loader); }
private object Load_Ref(string targetRef, Type type, QSharp.QNode[] qs, Dictionary <string, Dictionary <object, object> > data) { if (IsCollectionType(type)) { if (qs == null) { return(null); } var element_type = Collection_ElementType(type); var array = Array.CreateInstance(element_type, qs.Length); for (var i = 0; i < array.Length; ++i) { array.SetValue(Load_Ref(targetRef, element_type, new[] { qs[i] }, data), i); } return(array); } var typeInfo = SerializeInfoByType(type); //var childs = Properties(type); //var idPropertyName = IdPropertyByType.Find(type); //var idProperty = childs.FirstOrDefault(child => child.Name == idPropertyName); return(data.Find(targetRef).Find(Load_s(typeInfo.IdProperty.Type, qs, data))); }
public void Find_CollectionEmpty() { Dictionary <int, int> dictionary = new Dictionary <int, int>(); KeyValuePair <int, int>?foundItem = dictionary.Find(new Predicate <KeyValuePair <int, int> >((kvp) => { return(false); })); Assert.IsTrue(foundItem.HasValue == false); }
static ActorType RegisterThis(Type actor) { var type = ActorType.From(actor); var registered = codes.Find(type.Code); if (registered != null) { throw new ArgumentException( $"The type {actor} has been already registered " + $"under the code {registered.Code}"); } codes.Add(type.Code, type); types.Add(actor, type); return(type); }
public WhenFindingAnInvalidKey() { var dictionary = new Dictionary <string, int> { ["Badger"] = 42 }; _result = dictionary.Find("Not A Badger"); }
public void FindReturnsValueOfPresentKey() { var dict = new Dictionary <int, string> { { 42, "fourty two" } }; Assert.Equal("fourty two", dict.Find(42)); }
public void WhenDictionaryContainsEntry_ThenReturnsValue() { var dictionary = new Dictionary<string, int>(); dictionary.Add("foo", 25); var value = dictionary.Find("foo"); Assert.Equal(25, value); }
public void WhenDictionaryDoesNotContainEntry_ThenReturnsNull() { var dictionary = new Dictionary<string, int>(); dictionary.Add("foo", 25); var value = dictionary.Find("bar"); Assert.Equal(default(int), value); }
public void Remove(T cell) { KeyValuePair <Vector3Int, T> result; if (cells.Find(x => x == cell, out result)) { cells.Remove(result.Key); } }
// // см. также Global.Application_AuthenticateRequest // public static NitroBolt.Wui.HtmlResult <HElement> HView(object _state, JsonData[] jsons, HttpRequestMessage request) { Action <HttpResponseMessage> cookieSetter = null; var logins = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase) { { "Demo", "demodemo" }, { "Test", "test" } }; foreach (var json in jsons.OrEmpty()) { switch (json.JPath("data", "command")?.ToString()) { case "login": { var login = json.JPath("data", "login")?.ToString(); var password = json.JPath("data", "password")?.ToString(); if (logins.Find(login) == password) { cookieSetter = request.SetUserAndGetCookieSetter(login); } else { //display error } } break; case "logout": cookieSetter = request.SetUserAndGetCookieSetter(null); break; default: break; } if (request.UserName() != null) { switch (json.JPath("data", "command")?.ToString()) { default: break; } } } var account = request.UserName(); var page = Page(logins, account, request); return(new HtmlResult { Html = page, State = null, ResponseProcessor = cookieSetter, }); }
public void WhenDictionaryDoesNotContainEntry_ThenReturnsNull() { var dictionary = new Dictionary <string, int>(); dictionary.Add("foo", 25); var value = dictionary.Find("bar"); Assert.Equal(default(int), value); }
private static void ResetCoreDefinitions() { AddDefinitions(DefaultDefinitionFactory.CreateAllDefaultDefinitions()); missingActorDefinition = nameToDefinition.Find(missingActorName).Value; if (missingActorDefinition == null) { throw new NullReferenceException($"Core definition for unknown '{missingActorName}' missing"); } }
public void WhenDictionaryContainsEntry_ThenReturnsValue() { var dictionary = new Dictionary <string, int>(); dictionary.Add("foo", 25); var value = dictionary.Find("foo"); Assert.Equal(25, value); }
public static void Register() { AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var reference = references.Find(new AssemblyName(args.Name).Name); return(reference != null ? Assembly.LoadFrom(reference.FullPath) : null); }; }
// // см. также Global.Application_AuthenticateRequest // public static NitroBolt.Wui.HtmlResult<HElement> HView(object _state, JsonData[] jsons, HttpRequestMessage request) { Action<HttpResponseMessage> cookieSetter = null; var logins = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { { "Demo", "demodemo" }, { "Test", "test" } }; foreach (var json in jsons.OrEmpty()) { switch (json.JPath("data", "command")?.ToString()) { case "login": { var login = json.JPath("data", "login")?.ToString(); var password = json.JPath("data", "password")?.ToString(); if (logins.Find(login) == password) cookieSetter = request.SetUserAndGetCookieSetter(login); else { //display error } } break; case "logout": cookieSetter = request.SetUserAndGetCookieSetter(null); break; default: break; } if (request.UserName() != null) { switch (json.JPath("data", "command")?.ToString()) { default: break; } } } var account = request.UserName(); var page = Page(logins, account, request); return new HtmlResult { Html = page, State = null, ResponseProcessor = cookieSetter, }; }
public void Find_PredicateNull() { Dictionary<int, int> dictionary = new Dictionary<int, int>(); dictionary.Find(null); }
public void Find_CollectionEmpty() { Dictionary<int, int> dictionary = new Dictionary<int, int>(); KeyValuePair<int, int>? foundItem = dictionary.Find(new Predicate<KeyValuePair<int, int>>((kvp) => { return false; })); Assert.IsTrue(foundItem.HasValue == false); }
static void AutoSpells(EventArgs args) { if (Player.IsDead || Player.recalling()) { return; } if (SpellSlot.E.IsReady() && CassioUtils.Active("Combo.UseE") && (CassiopeiaMenu.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Combo || CassioUtils.Active("Misc.autoe"))) { Obj_AI_Hero etarg; etarg = target; if (etarg == null) { etarg = HeroManager.Enemies.FirstOrDefault(h => h.IsValidTarget(Spells[SpellSlot.E].Range) && h.isPoisoned() && !h.IsInvulnerable && !h.IsZombie); } if (etarg != null && CassioUtils.Active("Combo.useepoison") && etarg.isPoisoned()) { if ((Utils.GameTimeTickCount - laste) > edelay) { Spells[SpellSlot.E].Cast(etarg); laste = Utils.GameTimeTickCount; } } else if (!CassioUtils.Active("Combo.useepoison")) { if ((Utils.GameTimeTickCount - laste) > edelay) { Spells[SpellSlot.E].Cast(target); laste = Utils.GameTimeTickCount; } } } /* if (SpellSlot.R.IsReady() && CassioUtils.Active("Combo.UseR") && CassiopeiaMenu.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Combo) { var targets = HeroManager.Enemies.Where(x => x.IsValidTarget(Spells[SpellSlot.R].Range) && !x.IsZombie).OrderBy(x => x.Health); foreach (var targ in targets) { var pred = Spells[SpellSlot.R].GetPrediction(targ); if (pred.Hitchance >= CassioUtils.GetHitChance("Hitchance.R")) { int enemhitpred = 0; int enemfacingpred = 0; foreach (var hero in targets) { if (Spells[SpellSlot.R].WillHit(hero, pred.CastPosition, 0, CassioUtils.GetHitChance("Hitchance.R"))) { enemhitpred++; if (hero.IsFacing(Player)) { enemfacingpred++; } } } if (enemfacingpred >= CassioUtils.GetSlider("Combo.Rcount")) { Spells[SpellSlot.R].Cast(pred.CastPosition); return; } if (enemhitpred >= CassioUtils.GetSlider("Combo.Rcountnf") && CassioUtils.Active("Combo.UseRNF")) { Spells[SpellSlot.R].Cast(pred.CastPosition); return; } } } var easycheck = HeroManager.Enemies.FirstOrDefault(x => !x.IsInvulnerable && !x.IsZombie && x.IsValidTarget(Spells[SpellSlot.R].Range) && x.IsFacing(Player) && x.isImmobile()); if (easycheck != null) { Spells[SpellSlot.R].Cast(easycheck.ServerPosition); return; } } */ /* © ® ™ Work on patented algorithms in the future! XD © ® ™ */ if (SpellSlot.R.IsReady() && CassioUtils.Active("Combo.UseR") && CassiopeiaMenu.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Combo) { var easycheck = HeroManager.Enemies.FirstOrDefault( x => !x.IsInvulnerable && !x.IsZombie && x.IsValidTarget(Spells[SpellSlot.R].Range) && x.IsFacing(Player) && x.isImmobile() && (Player.HealthPercent <= 20 || x.HealthPercent > 30)); if (easycheck != null) { Spells[SpellSlot.R].Cast(easycheck.ServerPosition); DontMove = true; Utility.DelayAction.Add(50, () => DontMove = false); return; } var targs = HeroManager.Enemies.Where(h => h.IsValidTarget(Spells[SpellSlot.R].Range)); Dictionary<Vector3, double> Hitatpos = new Dictionary<Vector3, double>(); Dictionary<Vector3, double> Hitatposfacing = new Dictionary<Vector3, double>(); foreach (var t in targs) { var pred = Spells[SpellSlot.R].GetPrediction(t, false); var enemshit = pred.CastPosition.GetEnemiesInRange(Spells[SpellSlot.R].Width).Where(x=> x.Distance(Player) <= Spells[SpellSlot.R].Range); var counthit = enemshit.Count(); var hitfacing = enemshit.Count(x => x.IsFacing(Player) && !x.IsDashing() && !x.IsZombie && !x.IsInvulnerable); var anymovingtome = enemshit.Any(x => x.isMovingToMe() || x.IsFacing(Player)); if (pred.Hitchance >= CassioUtils.GetHitChance("Hitchance.R") && anymovingtome) { Hitatposfacing.Add(pred.CastPosition, hitfacing); } if (CassioUtils.Active("Combo.UseRNF") && pred.Hitchance >= CassioUtils.GetHitChance("Hitchance.R")) { Hitatpos.Add(pred.CastPosition, counthit); } } if (Hitatposfacing.Any()) { var bestpos = Hitatposfacing.Find(pos => pos.Value.Equals(Hitatposfacing.Values.Max())).Key; if (bestpos.IsValid() && bestpos.CountEnemiesInRange(Spells[SpellSlot.R].Width) >= CassioUtils.GetSlider("Combo.Rcount")) { Spells[SpellSlot.R].Cast(bestpos); DontMove = true; Utility.DelayAction.Add(50, () => DontMove = false); } } else if (Hitatpos.Any() && CassioUtils.Active("Combo.UseRNF") && CassioUtils.GetSlider("Combo.Rcountnf") >= Hitatpos.Values.Max()) { var bestposnf = Hitatpos.Find(pos => pos.Value.Equals(Hitatpos.Values.Max())).Key; if (bestposnf.IsValid() && bestposnf.CountEnemiesInRange(Spells[SpellSlot.R].Width) >= CassioUtils.GetSlider("Combo.Rcountnf")) { Spells[SpellSlot.R].Cast(bestposnf); DontMove = true; Utility.DelayAction.Add(50, () => DontMove = false); } } } }
// // см. также Global.Application_AuthenticateRequest // public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context) { var logins = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase){{"Demo", "demodemo"}, {"Test", "test"}}; foreach (var json in jsons.Else_Empty()) { switch (json.JPath("data", "command").ToString_Fair()) { case "login": { var login = json.JPath("data", "login").ToString_Fair(); var password = json.JPath("data", "password").ToString_Fair(); if (logins.Find(login) == password) context.HttpContext.SetUserAndCookie(login); else { //display error } } break; case "logout": context.HttpContext.SetUserAndCookie(null); break; default: break; } if (context.HttpContext.UserName() != null) { switch (json.JPath("data", "command").ToString_Fair()) { case "login": { var login = json.JPath("data", "login").ToString_Fair(); var password = json.JPath("data", "password").ToString_Fair(); if (logins.Find(login) == password) context.HttpContext.SetUserAndCookie(login); else { //display error } } break; case "logout": context.HttpContext.SetUserAndCookie(null); break; default: break; } } } var account = context.HttpContext.UserName(); var page = Page(logins, account); return new HtmlResult<HElement> { Html = page, State = null, }; }
/// <summary> /// Testowanie prędkości: /// * Ładowanie słownika /// * Wyszukiwanie istnienia słów: /// - ęą /// - żyznościach /// - żywotopisarstwa /// - dwuwiosłowymi /// - żżż /// * Dopasowanie: /// - żyźnicom do m @ 7, cionyźż /// - żyźnicom do m @ 7, cio yźż /// </summary> /// <param name="D">Implementacja słownika do przetestowania</param> public static void Benchmark1(Dictionary D) { System.Diagnostics.Stopwatch SW = new System.Diagnostics.Stopwatch(); Console.WriteLine("=== {0} ===", D.GetType().Name); /////////////////////////////////////////////////////////// SW.Restart(); D.Reload(); SW.Stop(); Console.WriteLine("Load: {0}ms", SW.ElapsedMilliseconds); /////////////////////////////////////////////////////////// String[] FindWords = new string[] { "ęą", "żyznościach", "żywotopisarstwa", "dwuwiosłowymi", "żżż" }; foreach(String FindWord in FindWords) { SW.Restart(); bool Result = D.Exists(FindWord); SW.Stop(); Console.WriteLine("Exists: '{0}': {1}ms ({2})", FindWord, SW.ElapsedMilliseconds, Result); } /////////////////////////////////////////////////////////// Dictionary.AlreadySetLetters ASL = new Dictionary.AlreadySetLetters(); ASL.Set(7, 'm'); Dictionary.HeldCharacters HC1 = new Dictionary.HeldCharacters(D.GetDictionaryEncoding()); HC1.Add("cionyźż"); Dictionary.HeldCharacters HC2 = new Dictionary.HeldCharacters(D.GetDictionaryEncoding()); HC2.Add("cio yźż"); SW.Restart(); Dictionary.WordsFound WF1 = D.Find(ASL, HC1); SW.Stop(); Console.WriteLine("Find1 (m): {0}ms ({1})", SW.ElapsedMilliseconds, WF1.Count); SW.Restart(); Dictionary.WordsFound WF2 = D.Find(ASL, HC2); SW.Stop(); Console.WriteLine("Find2 (blank): {0}ms ({1})", SW.ElapsedMilliseconds, WF2.Count); /////////////////////////////////////////////////////////// foreach(Dictionary.WordFound WF in WF1) Console.Write(WF.GetWord() + ", "); Console.WriteLine(); Console.WriteLine(); foreach(Dictionary.WordFound WF in WF2) Console.Write(WF.GetWord() + ", "); /////////////////////////////////////////////////////////// Console.WriteLine(); }