public void SetUp() { this.widgetSpecification = new WidgetSpecification("widgetName"); var placeholder = new Placeholder("area 1"); this.widgetSpecification.Insert(0, placeholder); }
protected void BtnSave_Click(object sender, EventArgs e) { //rempoved 20130610 OnClientClick="MyObject.UpdateEditorFormValue();" LblErr.Text = ""; LblOk.Text = ""; try { Placeholder p1 = new Placeholder(); if (TxtId.Text == string.Empty) { form2obj(p1); p1 = new PlaceholdersManager().Insert(p1); } else { p1 = new PlaceholdersManager().GetByName(TxtName.Text);//precarico i campi esistenti e nn gestiti dal form form2obj(p1); new PlaceholdersManager().Update(p1); } new CacheManager<Placeholder>("PigeonCms.Placeholder").Remove(p1.Name); Grid1.DataBind(); LblOk.Text = RenderSuccess(Utility.GetLabel("RECORD_SAVED_MSG")); MultiView1.ActiveViewIndex = 0; } catch (Exception e1) { LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString()); } finally { } }
public void SetUp() { var placeholder1 = new Placeholder("area 1"); var placeholder2 = new Placeholder("area 2"); var widgetSpecification = new WidgetSpecification("widget"); widgetSpecification.Insert(0, placeholder1); widgetSpecification.Insert(1, placeholder2); var area = new Area("area 1"); var widget = new Widget("widget", new[] { area }); var buildContext = new BuildData(Enumerable.Empty<IContextItem>()); var builder = new Builder(RenderingInstructions.BuildForPreview(), w => widgetSpecification, null); var instance = widget.Build(builder, new[] { 0 }, buildContext); var rendererFactory = MockRepository.GenerateStub<IRendererFactory>(); this.viewHelper = MockRepository.GenerateStub<IViewHelper>(); var multiRenderer = new MultiRenderer(rendererFactory); KolaConfigurationRegistry.RegisterRenderer(multiRenderer); this.result = instance.Render(multiRenderer); }
protected override void CreateChildControls() { Sitecore.Diagnostics.Tracer.Debug("DynamicKeyPlaceholder: Adding dynamic placeholder with Key " + DynamicKey); _placeholder = new Placeholder(); _placeholder.Key = this.DynamicKey; this.Controls.Add(_placeholder); _placeholder.Expand(); }
public static SignatureBuilder AcceptanceFor(Placeholder roleId) { return new SignatureBuilder(roleId) .WithStyle(SignatureStyle.ACCEPTANCE) .WithSize(0, 0) .AtPosition(0, 0) .OnPage(0); }
void ReplacePlaceholder(Placeholder ps, ProgBlock pg) { //TODO: allow middle placeholders ps.transform.SetParent(null); pg.transform.SetParent(this.transform); ps.transform.SetParent(this.transform); RecursiveLayout (); }
public void Compose_Object_With_Contract_And_Metadata() { // create placeholder var p = new Placeholder(); // perfrom composition Compose(p); // composition has occureed Assert.AreEqual(7, p.ClassWithInteger.IntegerValue); }
public static void InsertPlaceholders(this Page page, Placeholder placeholder) { if (!Placeholders.ContainsKey(page)) Placeholders.Add(page, new Dictionary<string, string>()); InternalInsertPlaceholder(page, placeholder, Placeholder.ExternalLinks); InternalInsertPlaceholder(page, placeholder, Placeholder.InternalLinks); InternalInsertPlaceholder(page, placeholder, Placeholder.InterwikiLinks); InternalInsertPlaceholder(page, placeholder, Placeholder.Categorys); InternalInsertPlaceholder(page, placeholder, Placeholder.Templates); InternalInsertPlaceholder(page, placeholder, Placeholder.Nowiki); InternalInsertPlaceholder(page, placeholder, Placeholder.Noinclude); InternalInsertPlaceholder(page, placeholder, Placeholder.Includeonly); InternalInsertPlaceholder(page, placeholder, Placeholder.Comments); }
public void SetUp() { var container = new Container( "container", new[] { new Property("property-name", "property-type", new InheritedPropertyValue("property-alias")) }); var placeholder = new Placeholder("area 1"); var widgetSpecification = new WidgetSpecification( "widget", new[] { new PropertySpecification("property-alias", "property-type", string.Empty) }, new[] { placeholder }); var buildContext = new BuildData(Enumerable.Empty<IContextItem>()); var widget = widgetSpecification.Create(); widget.FindOrCreateProperty(new PropertySpecification("property-alias", "property-type", string.Empty)); widget.Properties.Single().Value = new FixedPropertyValue("property-value"); widget.Areas.Single().Insert(0, container); var builder = new Builder(RenderingInstructions.BuildForPreview(), w => widgetSpecification, null); this.instance = widget.Build(builder, new[] { 0 }, buildContext); }
private SignerBuilder(Placeholder roleId) { this.signerEmail = null; this.groupId = null; this.id = roleId.Id; }
public bool Activate(RealmTime time, Item item, UseItemPacket pkt) { bool endMethod = false; Position target = pkt.ItemUsePos; Mp -= item.MpCost; IContainer con = Owner.GetEntity(pkt.SlotObject.ObjectId) as IContainer; if (con == null) return true; if (pkt.SlotObject.SlotId != 255 && pkt.SlotObject.SlotId != 254 && con.Inventory[pkt.SlotObject.SlotId] != item) { Entity.logger.FatalFormat("Cheat engine detected for player {0},\nItem should be {1}, but its {2}.", Name, Inventory[pkt.SlotObject.SlotId].ObjectId, item.ObjectId); foreach (Player player in Owner.Players.Values) if (player.Client.Account.Rank >= 2) player.SendInfo(String.Format("Cheat engine detected for player {0},\nItem should be {1}, but its {2}.", Name, Inventory[pkt.SlotObject.SlotId].ObjectId, item.ObjectId)); Client.Disconnect(); return true; } if (item.IsBackpack) { if (HasBackpack) return true; Client.Character.Backpack = new[] { -1, -1, -1, -1, -1, -1, -1, -1 }; HasBackpack = true; Client.Character.HasBackpack = 1; Manager.Database.DoActionAsync(db => db.SaveBackpacks(Client.Character, Client.Account)); Array.Resize(ref inventory, 20); int[] slotTypes = Utils.FromCommaSepString32( Manager.GameData.ObjectTypeToElement[ObjectType].Element("SlotTypes").Value); Array.Resize(ref slotTypes, 20); for (int i = 0; i < slotTypes.Length; i++) if (slotTypes[i] == 0) slotTypes[i] = 10; SlotTypes = slotTypes; return false; } if (item.XpBooster) { if (!XpBoosted) { XpBoostTimeLeft = (float)item.Timer; XpBoosted = item.XpBooster; xpFreeTimer = (float)item.Timer == -1.0 ? false : true; return false; } else { SendInfo("You have already an active XP Booster."); return true; } } if (item.LootDropBooster) { if (!LootDropBoost) { LootDropBoostTimeLeft = (float)item.Timer; lootDropBoostFreeTimer = (float)item.Timer == -1.0 ? false : true; return false; } else { SendInfo("You have already an active Loot Drop Booster."); return true; } } if (item.LootTierBooster) { if (!LootTierBoost) { LootTierBoostTimeLeft = (float)item.Timer; lootTierBoostFreeTimer = (float)item.Timer == -1.0 ? false : true; return false; } else { SendInfo("You have already an active Loot Tier Booster."); return true; } } foreach (ActivateEffect eff in item.ActivateEffects) { switch (eff.Effect) { case ActivateEffects.BulletNova: { ProjectileDesc prjDesc = item.Projectiles[0]; //Assume only one Packet[] batch = new Packet[21]; uint s = Random.CurrentSeed; Random.CurrentSeed = (uint)(s * time.tickTimes); for (int i = 0; i < 20; i++) { Projectile proj = CreateProjectile(prjDesc, item.ObjectType, (int)StatsManager.GetAttackDamage(prjDesc.MinDamage, prjDesc.MaxDamage), time.tickTimes, target, (float)(i * (Math.PI * 2) / 20)); Owner.EnterWorld(proj); FameCounter.Shoot(proj); batch[i] = new Shoot2Packet() { BulletId = proj.ProjectileId, OwnerId = Id, ContainerType = item.ObjectType, StartingPos = target, Angle = proj.Angle, Damage = (short)proj.Damage }; } Random.CurrentSeed = s; batch[20] = new ShowEffectPacket() { EffectType = EffectType.Trail, PosA = target, TargetId = Id, Color = new ARGB(0xFFFF00AA) }; BroadcastSync(batch, p => this.Dist(p) < 35); } break; case ActivateEffects.Shoot: { ActivateShoot(time, item, target); } break; case ActivateEffects.StatBoostSelf: { int idx = -1; if (eff.Stats == StatsType.MaximumHP) idx = 0; else if (eff.Stats == StatsType.MaximumMP) idx = 1; else if (eff.Stats == StatsType.Attack) idx = 2; else if (eff.Stats == StatsType.Defense) idx = 3; else if (eff.Stats == StatsType.Speed) idx = 4; else if (eff.Stats == StatsType.Vitality) idx = 5; else if (eff.Stats == StatsType.Wisdom) idx = 6; else if (eff.Stats == StatsType.Dexterity) idx = 7; List<Packet> pkts = new List<Packet>(); ActivateBoostStat(this, idx, pkts); int OGstat = oldstat; int bit = idx + 39; int s = eff.Amount; Boost[idx] += s; ApplyConditionEffect(new ConditionEffect { DurationMS = eff.DurationMS, Effect = (ConditionEffectIndex)bit }); UpdateCount++; Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { Boost[idx] = OGstat; UpdateCount++; })); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Potion, TargetId = Id, Color = new ARGB(0xffffffff) }, null); } break; case ActivateEffects.StatBoostAura: { int idx = -1; if (eff.Stats == StatsType.MaximumHP) idx = 0; if (eff.Stats == StatsType.MaximumMP) idx = 1; if (eff.Stats == StatsType.Attack) idx = 2; if (eff.Stats == StatsType.Defense) idx = 3; if (eff.Stats == StatsType.Speed) idx = 4; if (eff.Stats == StatsType.Vitality) idx = 5; if (eff.Stats == StatsType.Wisdom) idx = 6; if (eff.Stats == StatsType.Dexterity) idx = 7; int bit = idx + 39; var amountSBA = eff.Amount; var durationSBA = eff.DurationMS; var rangeSBA = eff.Range; if (eff.UseWisMod) { amountSBA = (int)UseWisMod(eff.Amount, 0); durationSBA = (int)(UseWisMod(eff.DurationSec) * 1000); rangeSBA = UseWisMod(eff.Range); } this.Aoe(rangeSBA, true, player => { // TODO support for noStack StatBoostAura attribute (paladin total // hp increase / insta heal) ApplyConditionEffect(new ConditionEffect { DurationMS = durationSBA, Effect = (ConditionEffectIndex)bit }); (player as Player).Boost[idx] += amountSBA; player.UpdateCount++; Owner.Timers.Add(new WorldTimer(durationSBA, (world, t) => { (player as Player).Boost[idx] -= amountSBA; player.UpdateCount++; })); }); BroadcastSync(new ShowEffectPacket() { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position() { X = rangeSBA } }, p => this.Dist(p) < 25); } break; case ActivateEffects.ConditionEffectSelf: { var durationCES = eff.DurationMS; if (eff.UseWisMod) durationCES = (int)(UseWisMod(eff.DurationSec) * 1000); var color = 0xffffffff; switch (eff.ConditionEffect.Value) { case ConditionEffectIndex.Damaging: color = 0xffff0000; break; case ConditionEffectIndex.Berserk: color = 0x808080; break; } ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = durationCES }); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(color), PosA = new Position { X = 2 } }, null); } break; case ActivateEffects.ConditionEffectAura: { var durationCEA = eff.DurationMS; var rangeCEA = eff.Range; if (eff.UseWisMod) { durationCEA = (int)(UseWisMod(eff.DurationSec) * 1000); rangeCEA = UseWisMod(eff.Range); } this.Aoe(rangeCEA, true, player => { player.ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = durationCEA }); }); var color = 0xffffffff; switch (eff.ConditionEffect.Value) { case ConditionEffectIndex.Damaging: color = 0xffff0000; break; case ConditionEffectIndex.Berserk: color = 0x808080; break; } BroadcastSync(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(color), PosA = new Position { X = rangeCEA } }, p => this.Dist(p) < 25); } break; case ActivateEffects.Heal: { List<Packet> pkts = new List<Packet>(); ActivateHealHp(this, eff.Amount, pkts); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.HealNova: { var amountHN = eff.Amount; var rangeHN = eff.Range; if (eff.UseWisMod) { amountHN = (int)UseWisMod(eff.Amount, 0); rangeHN = UseWisMod(eff.Range); } List<Packet> pkts = new List<Packet>(); this.Aoe(rangeHN, true, player => { ActivateHealHp(player as Player, amountHN, pkts); }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = rangeHN } }); BroadcastSync(pkts, p => this.Dist(p) < 25); } break; case ActivateEffects.Magic: { List<Packet> pkts = new List<Packet>(); ActivateHealMp(this, eff.Amount, pkts); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.MagicNova: { List<Packet> pkts = new List<Packet>(); this.Aoe(eff.Range / 2, true, player => { ActivateHealMp(player as Player, eff.Amount, pkts); }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range } }); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Teleport: { Move(target.X, target.Y); UpdateCount++; Owner.BroadcastPackets(new Packet[] { new GotoPacket { ObjectId = Id, Position = new Position { X = X, Y = Y } }, new ShowEffectPacket { EffectType = EffectType.Teleport, TargetId = Id, PosA = new Position { X = X, Y = Y }, Color = new ARGB(0xFFFFFFFF) } }, null); } break; case ActivateEffects.VampireBlast: { List<Packet> pkts = new List<Packet>(); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Trail, TargetId = Id, PosA = target, Color = new ARGB(0xFFFF0000) }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Diffuse, Color = new ARGB(0xFFFF0000), TargetId = Id, PosA = target, PosB = new Position { X = target.X + eff.Radius, Y = target.Y } }); int totalDmg = 0; List<Enemy> enemies = new List<Enemy>(); Owner.Aoe(target, eff.Radius, false, enemy => { enemies.Add(enemy as Enemy); totalDmg += (enemy as Enemy).Damage(this, time, eff.TotalDamage, false); }); List<Player> players = new List<Player>(); this.Aoe(eff.Radius, true, player => { players.Add(player as Player); ActivateHealHp(player as Player, totalDmg, pkts); }); if (enemies.Count > 0) { Random rand = new Random(); for (int i = 0; i < 5; i++) { Enemy a = enemies[rand.Next(0, enemies.Count)]; Player b = players[rand.Next(0, players.Count)]; pkts.Add(new ShowEffectPacket { EffectType = EffectType.Flow, TargetId = b.Id, PosA = new Position { X = a.X, Y = a.Y }, Color = new ARGB(0xffffffff) }); } } BroadcastSync(pkts, p => this.Dist(p) < 25); } break; case ActivateEffects.Trap: { BroadcastSync(new ShowEffectPacket { EffectType = EffectType.Throw, Color = new ARGB(0xff9000ff), TargetId = Id, PosA = target }, p => this.Dist(p) < 25); Owner.Timers.Add(new WorldTimer(1500, (world, t) => { Trap trap = new Trap( this, eff.Radius, eff.TotalDamage, eff.ConditionEffect ?? ConditionEffectIndex.Slowed, eff.EffectDuration); trap.Move(target.X, target.Y); world.EnterWorld(trap); })); } break; case ActivateEffects.StasisBlast: { List<Packet> pkts = new List<Packet>(); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Concentrate, TargetId = Id, PosA = target, PosB = new Position { X = target.X + 3, Y = target.Y }, Color = new ARGB(0xFF00D0) }); Owner.Aoe(target, 3, false, enemy => { if (IsSpecial(enemy.ObjectType)) return; if (enemy.HasConditionEffect(ConditionEffectIndex.StasisImmune)) { if (!enemy.HasConditionEffect(ConditionEffectIndex.Invincible)) { pkts.Add(new NotificationPacket { ObjectId = enemy.Id, Color = new ARGB(0xff00ff00), Text = "{\"key\":\"blank\",\"tokens\":{\"data\":\"Immune\"}}" }); } } else if (!enemy.HasConditionEffect(ConditionEffectIndex.Stasis)) { enemy.ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.Stasis, DurationMS = eff.DurationMS }); Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { enemy.ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.StasisImmune, DurationMS = 3000 }); })); pkts.Add(new NotificationPacket { ObjectId = enemy.Id, Color = new ARGB(0xffff0000), Text = "{\"key\":\"blank\",\"tokens\":{\"data\":\"Stasis\"}}" }); } }); BroadcastSync(pkts, p => this.Dist(p) < 25); } break; case ActivateEffects.Decoy: { Decoy decoy = new Decoy(Manager, this, eff.DurationMS, StatsManager.GetSpeed()); decoy.Move(X, Y); Owner.EnterWorld(decoy); } break; case ActivateEffects.Lightning: { Enemy start = null; double angle = Math.Atan2(target.Y - Y, target.X - X); double diff = Math.PI / 3; Owner.Aoe(target, 6, false, enemy => { if (!(enemy is Enemy)) return; double x = Math.Atan2(enemy.Y - Y, enemy.X - X); if (Math.Abs(angle - x) < diff) { start = enemy as Enemy; diff = Math.Abs(angle - x); } }); if (start == null) break; Enemy current = start; Enemy[] targets = new Enemy[eff.MaxTargets]; for (int i = 0; i < targets.Length; i++) { targets[i] = current; Enemy next = current.GetNearestEntity(8, false, enemy => enemy is Enemy && Array.IndexOf(targets, enemy) == -1 && this.Dist(enemy) <= 6) as Enemy; if (next == null) break; current = next; } List<Packet> pkts = new List<Packet>(); for (int i = 0; i < targets.Length; i++) { if (targets[i] == null) break; if (targets[i].HasConditionEffect(ConditionEffectIndex.Invincible)) continue; Entity prev = i == 0 ? (Entity)this : targets[i - 1]; targets[i].Damage(this, time, eff.TotalDamage, false); if (eff.ConditionEffect != null) targets[i].ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = (int)(eff.EffectDuration * 1000) }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Lightning, TargetId = prev.Id, Color = new ARGB(0xffff0088), PosA = new Position { X = targets[i].X, Y = targets[i].Y }, PosB = new Position { X = 350 } }); } BroadcastSync(pkts, p => this.Dist(p) < 25); } break; case ActivateEffects.PoisonGrenade: { try { BroadcastSync(new ShowEffectPacket { EffectType = EffectType.Throw, Color = new ARGB(0xffddff00), TargetId = Id, PosA = target }, p => this.Dist(p) < 25); Placeholder x = new Placeholder(Manager, 1500); x.Move(target.X, target.Y); Owner.EnterWorld(x); try { Owner.Timers.Add(new WorldTimer(1500, (world, t) => { world.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, Color = new ARGB(0xffddff00), TargetId = x.Id, PosA = new Position { X = eff.Radius } }, null); world.Aoe(target, eff.Radius, false, enemy => PoisonEnemy(enemy as Enemy, eff)); })); } catch (Exception ex) { Entity.logger.ErrorFormat("Poison ShowEffect:\n{0}", ex); } } catch (Exception ex) { Entity.logger.ErrorFormat("Poisons General:\n{0}", ex); } } break; case ActivateEffects.RemoveNegativeConditions: { this.Aoe(eff.Range / 2, true, player => { ApplyConditionEffect(NegativeEffs); }); BroadcastSync(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range / 2 } }, p => this.Dist(p) < 25); } break; case ActivateEffects.RemoveNegativeConditionsSelf: { ApplyConditionEffect(NegativeEffs); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = 1 } }, null); } break; case ActivateEffects.IncrementStat: { int idx = -1; if (eff.Stats == StatsType.MaximumHP) idx = 0; else if (eff.Stats == StatsType.MaximumMP) idx = 1; else if (eff.Stats == StatsType.Attack) idx = 2; else if (eff.Stats == StatsType.Defense) idx = 3; else if (eff.Stats == StatsType.Speed) idx = 4; else if (eff.Stats == StatsType.Vitality) idx = 5; else if (eff.Stats == StatsType.Wisdom) idx = 6; else if (eff.Stats == StatsType.Dexterity) idx = 7; Stats[idx] += eff.Amount; int limit = int.Parse( Manager.GameData.ObjectTypeToElement[ObjectType].Element( StatsManager.StatsIndexToName(idx)) .Attribute("max") .Value); if (Stats[idx] > limit) Stats[idx] = limit; UpdateCount++; } break; case ActivateEffects.UnlockPortal: Portal portal = this.GetNearestEntity(5, Manager.GameData.IdToObjectType[eff.LockedName]) as Portal; Packet[] packets = new Packet[3]; packets[0] = new ShowEffectPacket { EffectType = EffectType.AreaBlast, Color = new ARGB(0xFFFFFF), PosA = new Position { X = 5 }, TargetId = Id }; if (portal == null) break; portal.Unlock(eff.DungeonName); packets[1] = new NotificationPacket { Color = new ARGB(0x00FF00), Text = "{\"key\":\"blank\",\"tokens\":{\"data\":\"Unlocked by " + Name + "\"}}", ObjectId = Id }; packets[2] = new TextPacket { BubbleTime = 0, Stars = -1, Name = "", Text = eff.DungeonName + " Unlocked by " + Name + "." }; BroadcastSync(packets); break; case ActivateEffects.Create: //this is a portal { ushort objType; if (!Manager.GameData.IdToObjectType.TryGetValue(eff.Id, out objType) || !Manager.GameData.Portals.ContainsKey(objType)) break; // object not found, ignore Entity entity = Resolve(Manager, objType); World w = Manager.GetWorld(Owner.Id); //can't use Owner here, as it goes out of scope int TimeoutTime = Manager.GameData.Portals[objType].TimeoutTime; string DungName = Manager.GameData.Portals[objType].DungeonName; ARGB c = new ARGB(0x00FF00); entity.Move(X, Y); w.EnterWorld(entity); w.BroadcastPacket(new NotificationPacket { Color = c, Text = "{\"key\":\"blank\",\"tokens\":{\"data\":\"" + DungName + " opened by " + Client.Account.Name + "\"}}", ObjectId = Client.Player.Id }, null); w.BroadcastPacket(new TextPacket { BubbleTime = 0, Stars = -1, Name = "", Text = DungName + " opened by " + Client.Account.Name }, null); w.Timers.Add(new WorldTimer(TimeoutTime * 1000, (world, t) => //default portal close time * 1000 { try { w.LeaveWorld(entity); } catch (Exception ex) //couldn't remove portal, Owner became null. Should be fixed with RealmManager implementation { logger.ErrorFormat("Couldn't despawn portal.\n{0}", ex); } })); } break; case ActivateEffects.Dye: { if (item.Texture1 != 0) { Texture1 = item.Texture1; } if (item.Texture2 != 0) { Texture2 = item.Texture2; } SaveToCharacter(); } break; case ActivateEffects.ShurikenAbility: { if (!ninjaShoot) { ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.Speedy, DurationMS = -1 }); ninjaFreeTimer = true; ninjaShoot = true; } else { ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.Speedy, DurationMS = 0 }); ushort obj; Manager.GameData.IdToObjectType.TryGetValue(item.ObjectId, out obj); if (Mp >= item.MpEndCost) { ActivateShoot(time, item, pkt.ItemUsePos); Mp -= (int)item.MpEndCost; } targetlink = target; ninjaShoot = false; } } break; case ActivateEffects.UnlockSkin: if (!Client.Account.OwnedSkins.Contains(item.ActivateEffects[0].SkinType)) { Manager.Database.DoActionAsync(db => { Client.Account.OwnedSkins.Add(item.ActivateEffects[0].SkinType); MySqlCommand cmd = db.CreateQuery(); cmd.CommandText = "UPDATE accounts SET ownedSkins=@ownedSkins WHERE id=@id"; cmd.Parameters.AddWithValue("@ownedSkins", Utils.GetCommaSepString(Client.Account.OwnedSkins.ToArray())); cmd.Parameters.AddWithValue("@id", AccountId); cmd.ExecuteNonQuery(); SendInfo( "New skin unlocked successfully. Change skins in your Vault, or start a new character to use."); Client.SendPacket(new UnlockedSkinPacket { SkinID = item.ActivateEffects[0].SkinType }); }); endMethod = false; break; } SendInfo("Error.alreadyOwnsSkin"); endMethod = true; break; case ActivateEffects.PermaPet: //Doesnt exist anymore { //psr.Character.Pet = XmlDatas.IdToType[eff.ObjectId]; //GivePet(XmlDatas.IdToType[eff.ObjectId]); //UpdateCount++; } break; case ActivateEffects.Pet: Entity en = Entity.Resolve(Manager, eff.ObjectId); en.Move(X, Y); en.SetPlayerOwner(this); Owner.EnterWorld(en); Owner.Timers.Add(new WorldTimer(30 * 1000, (w, t) => { w.LeaveWorld(en); })); break; case ActivateEffects.CreatePet: if (!Owner.Name.StartsWith("Pet Yard")) { SendInfo("server.use_in_petyard"); return true; } Pet.Create(Manager, this, item); break; case ActivateEffects.MysteryPortal: string[] dungeons = new[] { "Pirate Cave Portal", "Forest Maze Portal", "Spider Den Portal", "Snake Pit Portal", "Glowing Portal", "Forbidden Jungle Portal", "Candyland Portal", "Haunted Cemetery Portal", "Undead Lair Portal", "Davy Jones' Locker Portal", "Manor of the Immortals Portal", "Abyss of Demons Portal", "Lair of Draconis Portal", "Mad Lab Portal", "Ocean Trench Portal", "Tomb of the Ancients Portal", "Beachzone Portal", "The Shatters", "Deadwater Docks", "Woodland Labyrinth", "The Crawling Depths", "Treasure Cave Portal", "Battle Nexus Portal", "Belladonna's Garden Portal", "Lair of Shaitan Portal" }; var descs = Manager.GameData.Portals.Where(_ => dungeons.Contains<string>(_.Value.ObjectId)).Select(_ => _.Value).ToArray(); var portalDesc = descs[Random.Next(0, descs.Count())]; Entity por = Entity.Resolve(Manager, portalDesc.ObjectId); por.Move(this.X, this.Y); Owner.EnterWorld(por); Client.SendPacket(new NotificationPacket { Color = new ARGB(0x00FF00), Text = "{\"key\":\"blank\",\"tokens\":{\"data\":\"" + portalDesc.DungeonName + " opened by " + Client.Account.Name + "\"}}", ObjectId = Client.Player.Id }); Owner.BroadcastPacket(new TextPacket { BubbleTime = 0, Stars = -1, Name = "", Text = portalDesc.ObjectId + " opened by " + Name }, null); Owner.Timers.Add(new WorldTimer(portalDesc.TimeoutTime * 1000, (w, t) => //default portal close time * 1000 { try { w.LeaveWorld(por); } catch (Exception ex) { Entity.logger.ErrorFormat("Couldn't despawn portal.\n{0}", ex); } })); break; case ActivateEffects.GenericActivate: var targetPlayer = eff.Target.Equals("player"); var centerPlayer = eff.Center.Equals("player"); var duration = (eff.UseWisMod) ? (int)(UseWisMod(eff.DurationSec) * 1000) : eff.DurationMS; var range = (eff.UseWisMod) ? UseWisMod(eff.Range) : eff.Range; Owner.Aoe((eff.Center.Equals("mouse")) ? target : new Position { X = X, Y = Y }, range, targetPlayer, entity => { if (IsSpecial(entity.ObjectType)) return; if (!entity.HasConditionEffect(ConditionEffectIndex.Stasis) && !entity.HasConditionEffect(ConditionEffectIndex.Invincible)) { entity.ApplyConditionEffect( new ConditionEffect() { Effect = eff.ConditionEffect.Value, DurationMS = duration }); } }); // replaced this last bit with what I had, never noticed any issue with it. // Perhaps I'm wrong? BroadcastSync(new ShowEffectPacket() { EffectType = (EffectType)eff.VisualEffect, TargetId = Id, Color = new ARGB(eff.Color ?? 0xffffffff), PosA = centerPlayer ? new Position { X = range } : target, PosB = new Position(target.X - range, target.Y) }, p => this.DistSqr(p) < 25); /*if (eff.VisualEffect > 0) { Placeholder x = null; if (eff.Center == "mouse") { x = new Placeholder(Manager, 1500); x.Move(pkt.ItemUsePos.X, pkt.ItemUsePos.Y); Owner.EnterWorld(x); } BroadcastSync(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = x?.Id ?? Id, Color = new ARGB(eff.Color ?? 0xffffffff), PosA = new Position {X = eff.VisualEffect/2}, }, p => this.Dist(p) < 25); }*/ break; } } UpdateCount++; return endMethod; }
public static SignatureBuilder InitialsFor(Placeholder roleId) { return new SignatureBuilder(roleId).WithStyle(SignatureStyle.INITIALS); }
public SignerBuilder Replacing(Placeholder placeholder) { this.id = placeholder.Id; return(this); }
public void TestCalc2Repeaters(bool useArray) { IVectorFactory factory = useArray ? (IVectorFactory)new ArrayVectorFactory() : (IVectorFactory)new BNodeVectorFactory(); /* E ← T ((‘+’ / ‘-’) T)* T ← F (('*' / '/') F)* F ← N / '(' E ')' N ← [0-9]+ */ var eNumber = new CollapseToString(Some.OneOrMore(new LiteralAnyCharOf("0123456789"))); var factor = new Placeholder(); var term = new Placeholder(); var expr = new Placeholder(); factor.Expression = new FirstOf(eNumber, new ExtractOne(1, new Sequence(new Literal('('), expr, new Literal(')')))); Function toPrefix = z => { IVector v = (IVector)z; object v0 = v[0]; IVector v1 = (IVector)v[1]; if (v1 == factory.Empty) return v0; for (int i = 0; i < v1.Length; i++) { IVector vv = (IVector)v1[i]; v0 = factory.Create(vv[0], v0, vv[1]); } return v0; }; term.Expression = new CallbackHandler(new Sequence(factor, Some.ZeroOrMore(new Sequence(new LiteralAnyCharOf("*/"), factor))), toPrefix); expr.Expression = new CallbackHandler(new Sequence(term, Some.ZeroOrMore(new Sequence(new LiteralAnyCharOf("+-"), term))), toPrefix); { var parser = new Parser(expr, TextCursor.Create("12+3*45+6+789*(6+2)*9+0"), factory); Result r = parser.Run(); string expected = "(+ (+ (+ (+ 12 (* 3 45)) 6) (* (* 789 (+ 6 2)) 9)) 0)"; Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); Assert.AreEqual(expected, Convert.ToString(r.Value).Replace("\"", "").Replace("'", "")); object num = new CalculatorVisitor().Process(r.Value); Assert.AreEqual(Convert.ToDouble(12 + 3 * 45 + 6 + 789 * (6 + 2) * 9 + 0), num); } { var parser = new Parser(expr, TextCursor.Create("12+3*4a5+6+7*(6+2)*9+0"), factory); Result r = parser.Run(); Assert.IsNotNull(r); Assert.IsTrue(r.Cursor.CanPop()); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(6, parser.FailCursor.Position); } { var parser = new Parser(expr, TextCursor.Create("12+3*45+(6+7*(6+2)*9+0"), factory); Result r = parser.Run(); Assert.IsNotNull(r); Assert.IsTrue(r.Cursor.CanPop()); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(22, parser.FailCursor.Position); } { var parser = new Parser(expr, TextCursor.Create("(12+3*45+(6+7*(6+2)*9+0)"), factory); Result r = parser.Run(); Assert.IsNull(r); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(24, parser.FailCursor.Position); } }
public void TestNotPredicateMatcher() { {//nested comments example var allchars = new LiteralAnyCharOf("0123456789/* "); var _open = new Sequence(new LiteralAnyCharOf("/"), new LiteralAnyCharOf("*")); var _close = new Sequence(new LiteralAnyCharOf("*"), new LiteralAnyCharOf("/")); var _nested = new Placeholder(); var _block = new Sequence(_open, Some.ZeroOrMore(_nested), _close); _nested.Expression = new FirstOf(_block, new Sequence(Predicate.Not(_open), Predicate.Not(_close), allchars)); var q = new Sequence(Some.ZeroOrMore(_nested), new LiteralEOI()); { var parser = new Parser(q, TextCursor.Create(" ** /")); var r = parser.Run(); Assert.IsNotNull(r); } { var parser = new Parser(q, TextCursor.Create(" **/")); var r = parser.Run(); Assert.IsNull(r); Assert.IsNotNull(parser.FailCursor); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(3, parser.FailCursor.Position); } { var parser = new Parser(q, TextCursor.Create(" 12 34 /* 5 6 7*8/*9 0/**/ */* * */")); var r = parser.Run(); Assert.IsNotNull(r); } { var parser = new Parser(q, TextCursor.Create(" 12 34 /* 5 6 7*8/*9 0/* */* * */")); var r = parser.Run(); Assert.IsNull(r); Assert.IsNotNull(parser.FailCursor); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(33, parser.FailCursor.Position); } } }
public static SignatureBuilder SignatureFor(Placeholder roleId) { return new SignatureBuilder(roleId); }
public static SignatureBuilder SignatureFor(Placeholder roleId) { return(new SignatureBuilder(roleId)); }
private SignatureBuilder(Placeholder roleId) { this.signerEmail = null; this.groupId = null; this.roleId = roleId; }
public void TestCalc1(bool useArray) { if (useArray) LispPrinter.PrintVectorsAsLists = true;//required to compare the results IVectorFactory factory = useArray? (IVectorFactory)new ArrayVectorFactory() : (IVectorFactory)new BNodeVectorFactory(); /* Expression ← Term ((‘+’ / ‘-’) Term)* Term ← Factor (('*' / '/') Factor)* Factor ← Number / '(' Expression ')' Number ← [0-9]+ */ Rule eDigit = new LiteralAnyCharOf("0123456789"); Placeholder eNumber = new Placeholder(); //eNumber.Expression = new First(new CallbackHandler( new Sequence(eDigit, eNumber), delegate(object v){ // object[] a = (object[])v; // return string.Concat(a[0], a[1]); //}), eDigit); eNumber.Expression = new FirstOf(new CollapseToString(new Sequence(eDigit, eNumber)), new CallbackHandler(eDigit, Convert.ToString)); //eNumber.Expression = new CallbackHandler( // new First(new CollapseToString(new Sequence(eDigit, eNumber)), new CallbackHandler(eDigit, Convert.ToString)), // delegate(object v) { return Int64.Parse((string)v); }); //eNumber.Expression = new CollapseToArray(new First(new Sequence(eDigit, eNumber), new Sequence(eDigit, new TailStub()))); Placeholder eAdditive = new Placeholder(); Placeholder eMultiplicative = new Placeholder(); Rule eSingular = new FirstOf(eNumber, new ExtractOne(1, new Sequence(new Literal('('), eAdditive, new Literal(')')))); // Placeholder eAdditiveSuffix = new Placeholder(); eAdditiveSuffix.Expression = new FirstOf( new CallbackHandler(new Sequence(new LiteralAnyCharOf("+-"), eMultiplicative, eAdditiveSuffix), delegate(object v) { IVector a = (IVector)v; IVector tail = (IVector)a[2]; return factory.InsertBefore(a[0], factory.InsertBefore(a[1], tail)); //return v; //return ((object[])v)[1]; }), //new EmptyExpression(null)); new EmptyRule(factory.Empty)); //eAdditive.Expression = new CallbackHandler( new Sequence(eMultiplicative, eAdditiveSuffix), DoAdd); eAdditive.Expression = new CallbackHandler(new Sequence(eMultiplicative, eAdditiveSuffix), delegate(object v) { IVector a = (IVector)v; IVector tail = (IVector)a[1]; return factory.InsertBefore(a[0], tail); }); Placeholder eMultiplicativeSuffix = new Placeholder(); eMultiplicativeSuffix.Expression = new FirstOf( new CallbackHandler(new Sequence(new LiteralAnyCharOf("*/"), eSingular, eMultiplicativeSuffix), delegate(object v) { IVector a = (IVector)v; IVector tail = (IVector)a[2]; return factory.InsertBefore(a[0], factory.InsertBefore(a[1], tail)); //return v; //return ((object[])v)[1]; }), //new EmptyExpression(null)); new EmptyRule(factory.Empty)); //eMultiplicative.Expression = new CallbackHandler(new Sequence(eSingular, eMultiplicativeSuffix), DoMultiply); eMultiplicative.Expression = new CallbackHandler(new Sequence(eSingular, eMultiplicativeSuffix), delegate(object v) { IVector a = (IVector)v; IVector tail = (IVector)a[1]; if (tail == factory.Empty) return a[0]; return factory.InsertBefore(a[0], tail); }); Rule expr = eAdditive; { var parser = new Parser(expr, TextCursor.Create("12+3*45+6+789*(6+2)*9+0"), factory); Result r = parser.Run(); //string expected = "(+ 12 (* 3 45) 6 (* 7 8 9) 0)"; string expected = "(12 + (3 * 45) + 6 + (789 * (6 + 2) * 9) + 0)"; Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); Assert.AreEqual(expected, Convert.ToString(r.Value).Replace("\"", "").Replace("'", "")); } { var parser = new Parser(expr, TextCursor.Create("120+34*((5*6+7)*8+9)-1"), factory); Result r = parser.Run(); Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); //Assert.AreEqual(120 + 34 * ((5 * 6 + 7) * 8 + 9) - 1, r.Value); } }
private SignatureBuilder (GroupId groupId ) { this.signerEmail = null; this.groupId = groupId; this.roleId = null; }
private SignatureBuilder (string signerEmail) { this.signerEmail = signerEmail; this.groupId = null; this.roleId = null; }
public static SignatureBuilder CaptureFor(Placeholder roleId) { return new SignatureBuilder(roleId).WithStyle(SignatureStyle.HAND_DRAWN); }
private void updatePlaceholder(NSAttributedString text = null) { Placeholder.UpdateVisibility(DescriptionTextView); }
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions) { string contextName = name; string userName = null; bool explicitCreds = false; if (credentials != null && credentials.UserName != null) { if (credentials.Domain != null) userName = credentials.Domain + "\\" + credentials.UserName; else userName = credentials.UserName; explicitCreds = true; } else { userName = Utils.GetNT4UserName(); } GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}", name, userName, explicitCreds.ToString(), contextOptions.ToString()); if (!_isSAM) { // Determine the domain DNS name // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY int flags = unchecked((int)(0x40000000 | 0x00000010 | 0x00000100)); UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags); contextName = info.DomainName; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName); ManualResetEvent contextReadyEvent = null; while (true) { Hashtable credTable = null; PrincipalContext ctx = null; // Wait for the PrincipalContext to be ready if (contextReadyEvent != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting"); contextReadyEvent.WaitOne(); } contextReadyEvent = null; lock (_tableLock) { CredHolder credHolder = (CredHolder)_table[contextName]; if (credHolder != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName); credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); Debug.Assert(credTable != null); object o = credTable[userName]; if (o is Placeholder) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder"); // A PrincipalContext is currently being constructed by another thread. // Wait for it. contextReadyEvent = ((Placeholder)o).contextReadyEvent; continue; } WeakReference refToContext = o as WeakReference; if (refToContext != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null"); ctx = (PrincipalContext)refToContext.Target; // null if GC'ed // If the PrincipalContext hasn't been GCed or disposed, use it. // Otherwise, we'll need to create a new one if (ctx != null && ctx.Disposed == false) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext"); return ctx; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing"); credTable.Remove(userName); } } } // Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable // are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext. if (credHolder == null) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString()); // No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place // to store the PrincipalContext we'll be creating. credHolder = new CredHolder(); _table[contextName] = credHolder; credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); } // Put a placeholder on the contextName/userName slot, so that other threads that come along after // we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us credTable[userName] = new Placeholder(); } // Now we just need to create a PrincipalContext for the contextName and credentials GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString()); ctx = new PrincipalContext( (_isSAM ? ContextType.Machine : ContextType.Domain), contextName, null, contextOptions, (credentials != null ? credentials.UserName : null), (credentials != null ? credentials.Password : null) ); lock (_tableLock) { Placeholder placeHolder = (Placeholder)credTable[userName]; // Replace the placeholder with the newly-created PrincipalContext credTable[userName] = new WeakReference(ctx); // Signal waiting threads to continue. We do this after inserting the PrincipalContext // into the table, so that the PrincipalContext is ready as soon as the other threads wake up. // (Actually, the order probably doesn't matter, since even if we did it in the // opposite order and the other thread woke up before we inserted the PrincipalContext, it would // just block as soon as it tries to acquire the tableLock that we're currently holding.) bool f = placeHolder.contextReadyEvent.Set(); Debug.Assert(f == true); } return ctx; } }
public static SignatureBuilder MobileCaptureFor(Placeholder roleId) { return(new SignatureBuilder(roleId).WithStyle(SignatureStyle.MOBILE_CAPTURE)); }
public void LookAheadTest() { /* expr: term '+' expr | term ; term: '(' expr ')' | term '!' | NUMBER ; * '1+2' */ Placeholder expr = new Placeholder(); Placeholder term = new Placeholder(); expr.Expression = new FirstOf( new Sequence(term, new Literal('+'), expr), term); //--left recursive //term.Expression = new First( // new Sequence(new Literal('('), expr, new Literal(')')), // new Sequence(term, new Literal('!')), // new First(new Literal('1'), new Literal('2'))); //--replaced: Placeholder term_r = new Placeholder(); term.Expression = new Sequence(new FirstOf( new Sequence(new Literal('('), expr, new Literal(')')), new FirstOf(new Literal('1'), new Literal('2'))), term_r); term_r.Expression = new FirstOf( new Sequence(new Literal('!'), term_r), new EmptyRule(null)); { var parser = new Parser(expr, TextCursor.Create("1+2")); Result r = parser.Run(); Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); } { var parser = new Parser(expr, TextCursor.Create("1+2!")); Result r = parser.Run(); Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); } }
void ReleaseDesignerOutlets() { if (AddProjectOnboardingBubble != null) { AddProjectOnboardingBubble.Dispose(); AddProjectOnboardingBubble = null; } if (DescriptionRemainingLengthLabel != null) { DescriptionRemainingLengthLabel.Dispose(); DescriptionRemainingLengthLabel = null; } if (Placeholder != null) { Placeholder.Dispose(); Placeholder = null; } if (StartDateButton != null) { StartDateButton.Dispose(); StartDateButton = null; } if (TimeInput != null) { TimeInput.Dispose(); TimeInput = null; } if (TimeInputTrailingConstraint != null) { TimeInputTrailingConstraint.Dispose(); TimeInputTrailingConstraint = null; } if (TimeLabel != null) { TimeLabel.Dispose(); TimeLabel = null; } if (TimeLabelTrailingConstraint != null) { TimeLabelTrailingConstraint.Dispose(); TimeLabelTrailingConstraint = null; } if (BillableButton != null) { BillableButton.Dispose(); BillableButton = null; } if (BillableButtonWidthConstraint != null) { BillableButtonWidthConstraint.Dispose(); BillableButtonWidthConstraint = null; } if (BottomDistanceConstraint != null) { BottomDistanceConstraint.Dispose(); BottomDistanceConstraint = null; } if (BottomOptionsSheet != null) { BottomOptionsSheet.Dispose(); BottomOptionsSheet = null; } if (CloseButton != null) { CloseButton.Dispose(); CloseButton = null; } if (DateTimeButton != null) { DateTimeButton.Dispose(); DateTimeButton = null; } if (DescriptionTextView != null) { DescriptionTextView.Dispose(); DescriptionTextView = null; } if (DoneButton != null) { DoneButton.Dispose(); DoneButton = null; } if (ProjectsButton != null) { ProjectsButton.Dispose(); ProjectsButton = null; } if (SuggestionsTableView != null) { SuggestionsTableView.Dispose(); SuggestionsTableView = null; } if (TagsButton != null) { TagsButton.Dispose(); TagsButton = null; } if (AddProjectBubbleLabel != null) { AddProjectBubbleLabel.Dispose(); AddProjectBubbleLabel = null; } }
public Value(string value) : base() { data = value; }
public bool TryEvaluateFormat(IFormattingInfo formattingInfo) { var format = formattingInfo.Format; var current = formattingInfo.CurrentValue; // This method needs the Highest priority so that it comes before the PluralLocalizationExtension and ConditionalExtension // This extension requires at least IEnumerable var enumerable = current as IEnumerable; if (enumerable == null) { return(false); } // Ignore Strings, because they're IEnumerable. // This issue might actually need a solution // for other objects that are IEnumerable. if (current is string) { return(false); } // If the object is IFormattable, ignore it if (current is IFormattable) { return(false); } // This extension requires a | to specify the spacer: if (format == null) { return(false); } var parameters = format.Split('|', 4); if (parameters.Count < 2) { return(false); } // Grab all formatting options: // They must be in one of these formats: // itemFormat|spacer // itemFormat|spacer|lastSpacer // itemFormat|spacer|lastSpacer|twoSpacer var itemFormat = parameters[0]; var spacer = (parameters.Count >= 2) ? parameters[1].GetLiteralText() : ""; var lastSpacer = (parameters.Count >= 3) ? parameters[2].GetLiteralText() : spacer; var twoSpacer = (parameters.Count >= 4) ? parameters[3].GetLiteralText() : lastSpacer; // TODO: [Obsolete] Not necessary, should remove: if (!itemFormat.HasNested) { // The format is not nested, // so we will treat it as an itemFormat: var newItemFormat = new Format(itemFormat.baseString); newItemFormat.startIndex = itemFormat.startIndex; newItemFormat.endIndex = itemFormat.endIndex; newItemFormat.HasNested = true; var newPlaceholder = new Placeholder(newItemFormat, itemFormat.startIndex, 0); newPlaceholder.Format = itemFormat; newPlaceholder.endIndex = itemFormat.endIndex; newItemFormat.Items.Add(newPlaceholder); itemFormat = newItemFormat; } // Let's buffer all items from the enumerable (to ensure the Count without double-enumeration): ICollection items = current as ICollection; if (items == null) { var allItems = new List <object>(); foreach (var item in enumerable) { allItems.Add(item); } items = allItems; } int oldCollectionIndex = CollectionIndex; // In case we have nested arrays, we might need to restore the CollectionIndex CollectionIndex = -1; foreach (object item in items) { CollectionIndex += 1; // Keep track of the index // Determine which spacer to write: if (spacer == null || CollectionIndex == 0) { // Don't write the spacer. } else if (CollectionIndex < items.Count - 1) { formattingInfo.Write(spacer); } else if (CollectionIndex == 1) { formattingInfo.Write(twoSpacer); } else { formattingInfo.Write(lastSpacer); } // Output the nested format for this item: formattingInfo.Write(itemFormat, item); } CollectionIndex = oldCollectionIndex; // Restore the CollectionIndex return(true); }
public void GenerateFunction(Generator generator) { Require.False(generated); generated = true; if (redirect != null) { redirect.node.GenerateFunction(generator); } else { foreach (ConstructorNodeInvocation i in inherit) { i.node.GenerateFunction(generator); } } generator.Resolver.EnterContext(); generator.Resolver.EnterFakeContext(definition); StringBuilder sb = new StringBuilder(); //sb.Append(parentDefinition.TypeReference.TypeName.Data); sb.Append("this"); //sb.Append(definition.TypeReference.TypeName.Data); parameters.PrettyPrint(sb); string name = sb.ToString(); generator.Resolver.CurrentFieldName = name; generator.AllocateAssembler(); parameters.Generate(generator); ParameterMetadata thisParam = parameters.Find("this"); generator.Resolver.SetImplicitFields(thisParam.Slot, thisParam.TypeReference); int thisslot = generator.Resolver.ResolveSlotOffset(new Identifier(location, "this")); generator.Resolver.IncompleteSlot(thisslot, false); statement.Prepare(generator); if (redirect == null) { definition.PrepareInitializer(generator); } generator.Symbols.Source(generator.Assembler.Region.CurrentLocation, location); generator.Assembler.StartFunction(); if (redirect != null) { redirect.Call(generator); } else { foreach (ConstructorNodeInvocation i in inherit) { i.Call(generator); } definition.GenerateInitializer(generator); } statement.Generate(generator, null); int slot = generator.Resolver.ResolveSlotOffset(new Identifier(location, "this")); generator.Resolver.RetrieveSlot(location, slot, false); foreach (Field field in definition.Fields) { if (generator.Resolver.IsFieldAssigned(field)) { assignedFields.Add(field); } } generator.Resolver.LeaveFakeContext(); generator.Resolver.LeaveContext(); generator.Assembler.StopFunction(); generator.Symbols.Source(generator.Assembler.Region.CurrentLocation, location, SourceMark.EndSequence); generator.Symbols.WriteCode(generator.Assembler.Region.BaseLocation, generator.Assembler.Region.Length, "constructor:" + parentDefinition.TypeReference.TypeName.Data + "." + name); functionPointer = generator.Assembler.Region.BaseLocation; }
public LbfgsAlgorithm() : base() { Parameters.Add(new ValueParameter <IMultiAnalyzer>(AnalyzerParameterName, "The analyzers that will be executed on the solution.", new MultiAnalyzer())); Parameters.Add(new ValueParameter <IntValue>(MaxIterationsParameterName, "The maximal number of iterations for.", new IntValue(20))); Parameters.Add(new ValueParameter <IntValue>(SeedParameterName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0))); Parameters.Add(new ValueParameter <BoolValue>(SetSeedRandomlyParameterName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true))); Parameters.Add(new ValueParameter <BoolValue>(ApproximateGradientsParameterName, "Indicates that gradients should be approximated.", new BoolValue(true))); Parameters.Add(new OptionalValueParameter <DoubleValue>(GradientCheckStepSizeParameterName, "Step size for the gradient check (should be used for debugging the gradient calculation only).")); // these parameter should not be changed usually Parameters[ApproximateGradientsParameterName].Hidden = true; Parameters[GradientCheckStepSizeParameterName].Hidden = true; var randomCreator = new RandomCreator(); solutionCreator = new Placeholder(); initializer = new LbfgsInitializer(); makeStep = new LbfgsMakeStep(); var branch = new ConditionalBranch(); evaluator = new Placeholder(); updateResults = new LbfgsUpdateResults(); var analyzerPlaceholder = new Placeholder(); var finalAnalyzerPlaceholder = new Placeholder(); OperatorGraph.InitialOperator = randomCreator; randomCreator.SeedParameter.ActualName = SeedParameterName; randomCreator.SeedParameter.Value = null; randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameterName; randomCreator.SetSeedRandomlyParameter.Value = null; randomCreator.Successor = solutionCreator; solutionCreator.Name = "(Solution Creator)"; solutionCreator.Successor = initializer; initializer.IterationsParameter.ActualName = MaxIterationsParameterName; initializer.ApproximateGradientsParameter.ActualName = ApproximateGradientsParameterName; initializer.Successor = makeStep; makeStep.StateParameter.ActualName = initializer.StateParameter.Name; makeStep.Successor = branch; branch.ConditionParameter.ActualName = makeStep.TerminationCriterionParameter.Name; branch.FalseBranch = evaluator; branch.TrueBranch = finalAnalyzerPlaceholder; evaluator.Name = "(Evaluator)"; evaluator.Successor = updateResults; updateResults.StateParameter.ActualName = initializer.StateParameter.Name; updateResults.ApproximateGradientsParameter.ActualName = ApproximateGradientsParameterName; updateResults.Successor = analyzerPlaceholder; analyzerPlaceholder.Name = "(Analyzer)"; analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameterName; analyzerPlaceholder.Successor = makeStep; finalAnalyzerPlaceholder.Name = "(Analyzer)"; finalAnalyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameterName; finalAnalyzerPlaceholder.Successor = null; analyzer = new LbfgsAnalyzer(); analyzer.StateParameter.ActualName = initializer.StateParameter.Name; }
private void DataBind(DotvvmRequestContext context) { Children.Clear(); content = new HtmlGenericControl("ul"); content.SetBinding(DataContextProperty, GetDataSetBinding()); Children.Add(content); var dataSet = DataSet; if (dataSet != null) { // first button firstLi = new HtmlGenericControl("li"); var firstLink = new LinkButton(); SetButtonContent(context, firstLink, "««", FirstPageTemplate); firstLink.SetBinding(ButtonBase.ClickProperty, GoToFirstPageCommand); firstLi.Children.Add(firstLink); content.Children.Add(firstLi); // previous button previousLi = new HtmlGenericControl("li"); var previousLink = new LinkButton(); SetButtonContent(context, previousLink, "«", PreviousPageTemplate); previousLink.SetBinding(ButtonBase.ClickProperty, GoToPrevPageCommand); previousLi.Children.Add(previousLink); content.Children.Add(previousLi); // number fields numbersPlaceholder = new Placeholder(); content.Children.Add(numbersPlaceholder); var i = 0; foreach (var number in dataSet.NearPageIndexes) { var li = new HtmlGenericControl("li"); li.SetBinding(DataContextProperty, GetNearIndexesBinding(i)); if (number == dataSet.PageIndex) { li.Attributes["class"] = "active"; } var link = new LinkButton() { Text = (number + 1).ToString() }; link.SetBinding(ButtonBase.ClickProperty, GoToThisPageCommand); li.Children.Add(link); numbersPlaceholder.Children.Add(li); i++; } // next button nextLi = new HtmlGenericControl("li"); var nextLink = new LinkButton(); SetButtonContent(context, nextLink, "»", NextPageTemplate); nextLink.SetBinding(ButtonBase.ClickProperty, GoToNextPageCommand); nextLi.Children.Add(nextLink); content.Children.Add(nextLi); // last button lastLi = new HtmlGenericControl("li"); var lastLink = new LinkButton(); SetButtonContent(context, lastLink, "»»", LastPageTemplate); lastLink.SetBinding(ButtonBase.ClickProperty, GoToLastPageCommand); lastLi.Children.Add(lastLink); content.Children.Add(lastLi); } }
public Format ParseFormat(string format) { var result = new Format(format); var current = result; Placeholder currentPlaceholder = null; // Store parsing errors until the end: var parsingErrors = new ParsingErrors(result); int nestedDepth = 0; int lastI = 0; int operatorIndex = 0; int selectorIndex = 0; for (int i = 0, length = format.Length; i < length; i++) { var c = format[i]; if (currentPlaceholder == null) { if (c == '{') { // Finish the last text item: if (i != lastI) current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); lastI = i + 1; // See if this brace should be escaped: if (!this.AlternativeEscaping) { var nextI = lastI; if (nextI < length && format[nextI] == '{') { i++; continue; } } // New placeholder: nestedDepth++; currentPlaceholder = new Placeholder(current, i, nestedDepth); current.Items.Add(currentPlaceholder); current.HasNested = true; operatorIndex = i+1; selectorIndex = 0; } else if (c == '}') { // Finish the last text item: if (i != lastI) current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); lastI = i + 1; // See if this brace should be escaped: if (!this.AlternativeEscaping) { var nextI = lastI; if (nextI < length && format[nextI] == '}') { i++; continue; } } // Make sure that this is a nested placeholder before we un-nest it: if (current.parent == null) { parsingErrors.AddIssue(current, "Format string has too many closing braces", i, i + 1); continue; } // End of the placeholder's Format: nestedDepth--; current.endIndex = i; current.parent.endIndex = i + 1; current = current.parent.parent; } else if (this.AlternativeEscaping && c == this.AlternativeEscapeChar) { // See if the next char is a brace that should be escaped: var nextI = i + 1; if (nextI < length && (format[nextI] == '{' || format[nextI] == '}')) { // Finish the last text item: if (i != lastI) current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); lastI = i + 1; i++; continue; } } } else { // Placeholder is NOT null, so that means we're parsing the selectors: if (Operators.IndexOf(c) != -1) { // Add the selector: if (i != lastI) { currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); selectorIndex++; operatorIndex = i; } lastI = i + 1; } else if (c == ':') { // Add the selector: if (i != lastI) currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); else if (operatorIndex != i) { // There are trailing operators. For now, this is an error. parsingErrors.AddIssue(current, "There are trailing operators in the selector", operatorIndex, i); //var issue = "There are trailing operators in the selector"; //ParserError(format, operatorIndex, issue, result); } lastI = i + 1; // Start the format: currentPlaceholder.Format = new Format(currentPlaceholder, i + 1); current = currentPlaceholder.Format; currentPlaceholder = null; } else if (c == '}') { // Add the selector: if (i != lastI) currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); else if (operatorIndex != i) { // There are trailing operators. For now, this is an error. parsingErrors.AddIssue(current, "There are trailing operators in the selector", operatorIndex, i); //ParserError(format, operatorIndex, "There are trailing operators in the selector", result); } lastI = i + 1; // End the placeholder with no format: nestedDepth--; currentPlaceholder.endIndex = i + 1; current = currentPlaceholder.parent; currentPlaceholder = null; } else { // Let's make sure the selector characters are valid: // Make sure it's alphanumeric: if (('0' <= c && c <= '9') || (AlphanumericSelectors && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z')) || (AllowedSelectorChars.IndexOf(c) != -1)) { } else { // Invalid character in the selector. parsingErrors.AddIssue(current, "Invalid character in the selector", i, i + 1); //ParserError(format, i, "Invalid character in the selector", result); } } } } // finish the last text item: if (lastI != format.Length) current.Items.Add(new LiteralText(current, lastI) { endIndex = format.Length }); // Check that the format is finished: if (current.parent != null || currentPlaceholder != null) { //ParserError(format, format.Length, "Format string is missing a closing brace", result); parsingErrors.AddIssue(current, "Format string is missing a closing brace", format.Length, format.Length); current.endIndex = format.Length; while (current.parent != null) { current = current.parent.parent; current.endIndex = format.Length; } } // Check if there were any parsing errors: if (parsingErrors.HasIssues && ErrorAction == Core.ErrorAction.ThrowError) throw parsingErrors; return result; }
private static void InternalInsertPlaceholder(Page page, Placeholder placeholder, Placeholder p) { if (placeholder.HasFlag(p)) page.text = PlaceholderRegexes[p].Replace(page.text, match => { var x = "~:" + Placeholders[page].Count + ":~"; Placeholders[page].Add(x, match.Value); return x; }); }
private void OnReturnRibbonAndInitialTab(DataQueryResult res) { PMetrics.PerfMark(PMarker.perfCUIRibbonInitStart); RibbonBuildContext rbc = (RibbonBuildContext)res.ContextData; // Apply any extensions to the data. res.QueryData = ApplyDataExtensions(res.QueryData); Utility.EnsureCSSClassOnElement(Placeholder, "loaded"); JSObject templates = DataNodeWrapper.GetFirstChildNodeWithName(res.QueryData, DataNodeWrapper.TEMPLATES); if (!CUIUtility.IsNullOrUndefined(templates)) { TemplateManager.Instance.LoadTemplates(templates); } Ribbon = BuildRibbon(res.QueryData, rbc); Ribbon.RibbonBuilder = this; BuildClient.OnComponentCreated(Ribbon, Ribbon.Id); if (RibbonBuildOptions.Minimized) { Ribbon.MinimizedInternal = true; } else { Ribbon.MinimizedInternal = false; Tab firstTab = (Tab)Ribbon.GetChild(rbc.InitialTabId); if (!CUIUtility.IsNullOrUndefined(firstTab)) { // We need this in order to set the "ChangedByUser" property of the first // TabSwitch command that comes out of the ribbon correctly. firstTab.SelectedByUser = RibbonBuildOptions.InitialTabSelectedByUser; Ribbon.MakeTabSelectedInternal(firstTab); } } Ribbon.ClientID = RibbonBuildOptions.ClientID; bool shouldAttach = !RibbonBuildOptions.Minimized && RibbonBuildOptions.AttachToDOM; if (shouldAttach) { // Scale the ribbon to the scaling index that matches the ribbon that was // rendered by the server. This sets the in memory Ribbon structure to match // what was rendered by the server. This is needed so that Ribbon.AttachInternal() // will work properly. if (!((RibbonBuildOptions)Options).Minimized) { // We subtract one from this scaling index because internally // this scaling index is an entry into an array of "<ScaleStep>" so // the MaxSize for all the groups is actually index "-1" and the first // step is index 0. Ribbon.ScaleIndex(rbc.InitialScalingIndex - 1); } Ribbon.AttachInternal(true); // Attach to the QAT and Jewel if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowQATId)) { Ribbon.BuildAndSetQAT(RibbonBuildOptions.ShowQATId, true, DataSource); } if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowJewelId)) { Ribbon.BuildAndSetJewel(RibbonBuildOptions.ShowJewelId, true, DataSource); } #if DEBUG // Validate that the server rendered ribbon is identical to the client rendered one // for this tab. if (Options.ValidateServerRendering) { RibbonBuilder rb2 = new RibbonBuilder(this.RibbonBuildOptions, this.Placeholder, null); DataSource ds = new DataSource(this.DataSource.DataUrl, this.DataSource.Version, this.DataSource.Lcid); rb2.DataSource = ds; SPRibbon r2 = rb2.BuildRibbon(res.QueryData, rbc); r2.Id += "-client"; r2.ClientID = RibbonBuildOptions.ClientID + "-client"; r2.RibbonBuilder = this; if (!RibbonBuildOptions.Minimized) { r2.Minimized = false; } // Clone all the peripheral sections for the client-rendering version Div p_qrc = (Div)Browser.Document.GetById(RibbonBuildOptions.ClientID + "-" + RibbonPeripheralSection.QATRowCenter); Div p_qrr = (Div)Browser.Document.GetById(RibbonBuildOptions.ClientID + "-" + RibbonPeripheralSection.QATRowRight); Div p_trl = (Div)Browser.Document.GetById(RibbonBuildOptions.ClientID + "-" + RibbonPeripheralSection.TabRowLeft); Div p_trr = (Div)Browser.Document.GetById(RibbonBuildOptions.ClientID + "-" + RibbonPeripheralSection.TabRowRight); Div hiddenClonedPeripherals = new Div(); hiddenClonedPeripherals.Style.Display = "none"; Browser.Document.Body.AppendChild(hiddenClonedPeripherals); Div clone; if (null != p_qrc) { clone = (Div)p_qrc.CloneNode(true); clone.Id = clone.Id.Replace(RibbonBuildOptions.ClientID, r2.ClientID); hiddenClonedPeripherals.AppendChild(clone); } if (null != p_qrr) { clone = (Div)p_qrr.CloneNode(true); clone.Id = clone.Id.Replace(RibbonBuildOptions.ClientID, r2.ClientID); hiddenClonedPeripherals.AppendChild(clone); } if (null != p_trl) { clone = (Div)p_trl.CloneNode(true); clone.Id = clone.Id.Replace(RibbonBuildOptions.ClientID, r2.ClientID); hiddenClonedPeripherals.AppendChild(clone); } if (null != p_trr) { clone = (Div)p_trr.CloneNode(true); clone.Id = clone.Id.Replace(RibbonBuildOptions.ClientID, r2.ClientID); hiddenClonedPeripherals.AppendChild(clone); } r2.MakeTabSelectedInternal((Tab)r2.GetChild(rbc.InitialTabId)); r2.RefreshInternal(); if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowQATId)) { r2.BuildAndSetQAT(RibbonBuildOptions.ShowQATId, false, ds); } if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowJewelId)) { r2.BuildAndSetJewel(RibbonBuildOptions.ShowJewelId, false, ds); } r2.ScaleIndex(rbc.InitialScalingIndex - 1); r2.CompleteConstruction(); // If this returns a message it means that it found some inconsistencies // between the DOM Nodes CompareNodes(Ribbon.ElementInternal, r2.ElementInternal); } #endif } else { // Do the minimum amount of work necessary in order to be able to // get the outer ribbon element and to be able to attach the Jewel and QAT. Ribbon.EnsureDOMElement(); // Build the QAT and Jewel after the ribbon so that the placeholders // will have been created within the ribbon via Ribbon.RefreshInternal() if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowQATId)) { Ribbon.BuildAndSetQAT(RibbonBuildOptions.ShowQATId, false, DataSource); } if (!string.IsNullOrEmpty(RibbonBuildOptions.ShowJewelId)) { Ribbon.BuildAndSetJewel(RibbonBuildOptions.ShowJewelId, false, DataSource); } // Remove anything else that is in the placeholder in case there is a temporary // animated gif or a static ribbon in there while the ribbon is loading. // We're doing this the slow way since partners might have a reference to this node Utility.RemoveChildNodesSlow(Placeholder); Placeholder.AppendChild(Ribbon.ElementInternal); } Ribbon.Scale(); OnRootBuilt(Ribbon); BuildClient.OnComponentBuilt(Ribbon, Ribbon.Id); if (RibbonBuildOptions.LaunchedByKeyboard) { Ribbon.SetFocusOnRibbon(); } PMetrics.PerfMark(PMarker.perfCUIRibbonInitPercvdEnd); }
public void TestAndPredicateMatcher() { {//classic {a^n b^n c^n | n>=1} example var _a = new Placeholder(); _a.Expression = new Sequence(new LiteralAnyCharOf("a"), Some.Optional(_a), new LiteralAnyCharOf("b")); var _b = new Placeholder(); _b.Expression = new Sequence(new LiteralAnyCharOf("b"), Some.Optional(_b), new LiteralAnyCharOf("c")); var q = new Sequence(Predicate.And(new Sequence(_a, Predicate.Not(new LiteralAnyCharOf("b")))), Some.OneOrMore(new LiteralAnyCharOf("a")), _b, new LiteralEOI()); { var parser = new Parser(q, TextCursor.Create("aaabbbccc")); var r = parser.Run(); Assert.IsNotNull(r); } { var parser = new Parser(q, TextCursor.Create("abc")); var r = parser.Run(); Assert.IsNotNull(r); } { var parser = new Parser(q, TextCursor.Create("aabbc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabbccc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabccc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabcc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabbbc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabbbcc")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aacbb")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("aabbac")); var r = parser.Run(); Assert.IsNull(r); } { var parser = new Parser(q, TextCursor.Create("bca")); var r = parser.Run(); Assert.IsNull(r); } } }
public SignerBuilder WithRoleId(Placeholder placeholder) { return(Replacing(placeholder)); }
protected virtual Placeholder CreatePlaceholder () { Placeholder ph = new Placeholder (); ph.Show (); return ph; }
public static SignerBuilder NewSignerPlaceholder(Placeholder roleId) { return(new SignerBuilder(roleId)); }
void PlaceholderDrop (Placeholder ph, Stetic.Wrapper.Widget wrapper) { Gtk.Dialog parentDialog = Wrapped.Parent as Gtk.Dialog; if (showNonContainerWarning && (IsTopLevel || (parentDialog != null && parentDialog.VBox == Wrapped))) { if (nonContainers.Contains (wrapper.Wrapped.GetType ().ToString ())) { using (NonContainerWarningDialog dlg = new NonContainerWarningDialog ()) { int res = dlg.Run (); showNonContainerWarning = dlg.ShowAgain; if (res != (int) Gtk.ResponseType.Ok) return; } } } using (UndoManager.AtomicChange) { ReplaceChild (ph, wrapper.Wrapped, true); wrapper.Select (); } }
private void Initialize() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far.")); Parameters.Add(new LookupParameter <DoubleValue>("MoveQuality", "The value which represents the quality of a move.")); Parameters.Add(new LookupParameter <DoubleValue>("Temperature", "The current temperature.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("StartTemperature", "The initial temperature.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("EndTemperature", "The end temperature.")); Parameters.Add(new ValueLookupParameter <IntValue>("InnerIterations", "The amount of inner iterations (number of moves before temperature is adjusted again).")); Parameters.Add(new LookupParameter <IntValue>("Iterations", "The number of iterations.")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of iterations which should be processed.")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveGenerator", "The operator that generates the moves.")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveEvaluator", "The operator that evaluates a move.")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveMaker", "The operator that performs a move and updates the quality.")); Parameters.Add(new ValueLookupParameter <IOperator>("AnnealingOperator", "The operator that modifies the temperature.")); Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation.")); Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored.")); Parameters.Add(new LookupParameter <IntValue>("EvaluatedMoves", "The number of evaluated moves.")); #endregion #region Create operators Assigner temperatureInitializer = new Assigner(); ResultsCollector resultsCollector1 = new ResultsCollector(); SubScopesProcessor subScopesProcessor0 = new SubScopesProcessor(); Placeholder analyzer1 = new Placeholder(); SubScopesProcessor sssp = new SubScopesProcessor(); ResultsCollector resultsCollector = new ResultsCollector(); Placeholder annealingOperator = new Placeholder(); UniformSubScopesProcessor mainProcessor = new UniformSubScopesProcessor(); Placeholder moveGenerator = new Placeholder(); UniformSubScopesProcessor moveEvaluationProcessor = new UniformSubScopesProcessor(); Placeholder moveEvaluator = new Placeholder(); SubScopesCounter subScopesCounter = new SubScopesCounter(); ProbabilisticQualityComparator qualityComparator = new ProbabilisticQualityComparator(); ConditionalBranch improvesQualityBranch = new ConditionalBranch(); Placeholder moveMaker = new Placeholder(); SubScopesRemover subScopesRemover = new SubScopesRemover(); IntCounter iterationsCounter = new IntCounter(); Comparator iterationsComparator = new Comparator(); SubScopesProcessor subScopesProcessor1 = new SubScopesProcessor(); Placeholder analyzer2 = new Placeholder(); ConditionalBranch iterationsTermination = new ConditionalBranch(); temperatureInitializer.LeftSideParameter.ActualName = TemperatureParameter.ActualName; temperatureInitializer.RightSideParameter.ActualName = StartTemperatureParameter.Name; resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>(IterationsParameter.Name)); resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name; analyzer1.Name = "Analyzer (placeholder)"; analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name; annealingOperator.Name = "Annealing operator (placeholder)"; annealingOperator.OperatorParameter.ActualName = AnnealingOperatorParameter.Name; moveGenerator.Name = "Move generator (placeholder)"; moveGenerator.OperatorParameter.ActualName = MoveGeneratorParameter.Name; moveEvaluator.Name = "Move evaluator (placeholder)"; moveEvaluator.OperatorParameter.ActualName = MoveEvaluatorParameter.Name; subScopesCounter.Name = "Increment EvaluatedMoves"; subScopesCounter.ValueParameter.ActualName = EvaluatedMovesParameter.Name; qualityComparator.LeftSideParameter.ActualName = MoveQualityParameter.Name; qualityComparator.RightSideParameter.ActualName = QualityParameter.Name; qualityComparator.ResultParameter.ActualName = "IsBetter"; qualityComparator.DampeningParameter.ActualName = "Temperature"; improvesQualityBranch.ConditionParameter.ActualName = "IsBetter"; moveMaker.Name = "Move maker (placeholder)"; moveMaker.OperatorParameter.ActualName = MoveMakerParameter.Name; subScopesRemover.RemoveAllSubScopes = true; iterationsCounter.Name = "Increment Iterations"; iterationsCounter.Increment = new IntValue(1); iterationsCounter.ValueParameter.ActualName = IterationsParameter.Name; iterationsComparator.Name = "Iterations >= MaximumIterations"; iterationsComparator.LeftSideParameter.ActualName = IterationsParameter.Name; iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name; iterationsComparator.ResultParameter.ActualName = "Terminate"; iterationsComparator.Comparison.Value = ComparisonType.GreaterOrEqual; analyzer2.Name = "Analyzer (placeholder)"; analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name; iterationsTermination.Name = "Iterations termination condition"; iterationsTermination.ConditionParameter.ActualName = "Terminate"; #endregion #region Create operator graph OperatorGraph.InitialOperator = temperatureInitializer; temperatureInitializer.Successor = resultsCollector1; resultsCollector1.Successor = subScopesProcessor0; subScopesProcessor0.Operators.Add(analyzer1); subScopesProcessor0.Successor = sssp; analyzer1.Successor = null; sssp.Operators.Add(resultsCollector); sssp.Successor = annealingOperator; resultsCollector.Successor = null; annealingOperator.Successor = mainProcessor; mainProcessor.Operator = moveGenerator; mainProcessor.Successor = iterationsCounter; moveGenerator.Successor = moveEvaluationProcessor; moveEvaluationProcessor.Operator = moveEvaluator; moveEvaluationProcessor.Successor = subScopesCounter; moveEvaluator.Successor = qualityComparator; qualityComparator.Successor = improvesQualityBranch; improvesQualityBranch.TrueBranch = moveMaker; improvesQualityBranch.FalseBranch = null; improvesQualityBranch.Successor = null; moveMaker.Successor = null; subScopesCounter.Successor = subScopesRemover; subScopesRemover.Successor = null; iterationsCounter.Successor = iterationsComparator; iterationsComparator.Successor = subScopesProcessor1; subScopesProcessor1.Operators.Add(analyzer2); subScopesProcessor1.Successor = iterationsTermination; iterationsTermination.TrueBranch = null; iterationsTermination.FalseBranch = annealingOperator; #endregion }
private void updateCursorAndLayout() { const float cursor_width = 3; Placeholder.TextSize = CalculatedTextSize; textUpdateScheduler.Update(); float caretWidth = cursor_width; Vector2 cursorPos = Vector2.Zero; if (text.Length > 0) { cursorPos.X = getPositionAt(selectionLeft) - cursor_width / 2; } float cursorPosEnd = getPositionAt(selectionEnd); if (selectionLength > 0) { caretWidth = getPositionAt(selectionRight) - cursorPos.X; } float cursorRelativePositionAxesInBox = (cursorPosEnd - textContainerPosX) / DrawWidth; //we only want to reposition the view when the cursor reaches near the extremities. if (cursorRelativePositionAxesInBox < 0.1 || cursorRelativePositionAxesInBox > 0.9) { textContainerPosX = cursorPosEnd - DrawWidth / 2 + LeftRightPadding * 2; } textContainerPosX = MathHelper.Clamp(textContainerPosX, 0, Math.Max(0, TextFlow.DrawWidth - DrawWidth + LeftRightPadding * 2)); TextContainer.MoveToX(LeftRightPadding - textContainerPosX, 300, Easing.OutExpo); if (HasFocus) { Caret.ClearTransforms(); Caret.MoveTo(cursorPos, 60, Easing.Out); Caret.ResizeWidthTo(caretWidth, caret_move_time, Easing.Out); if (selectionLength > 0) { Caret .FadeTo(0.5f, 200, Easing.Out) .FadeColour(SelectionColour, 200, Easing.Out); } else { Caret .FadeColour(Color4.White, 200, Easing.Out) .Loop(c => c.FadeTo(0.7f).FadeTo(0.4f, 500, Easing.InOutSine)); } } if (textAtLastLayout != text) { Current.Value = text; } if (textAtLastLayout.Length == 0 || text.Length == 0) { Placeholder.FadeTo(text.Length == 0 ? 1 : 0, 200); } textAtLastLayout = text; }
public static SignatureBuilder CaptureFor(Placeholder roleId) { return(new SignatureBuilder(roleId).WithStyle(SignatureStyle.HAND_DRAWN)); }
private void Initialize() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far.")); Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "µ (mu) - the size of the population.")); Parameters.Add(new ValueLookupParameter <IntValue>("ParentsPerChild", "ρ (rho) - how many parents should be recombined.")); Parameters.Add(new ValueLookupParameter <IntValue>("Children", "λ (lambda) - the size of the offspring population.")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.")); Parameters.Add(new ValueLookupParameter <BoolValue>("PlusSelection", "True for plus selection (elitist population), false for comma selection (non-elitist population).")); Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)")); Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions.")); Parameters.Add(new ValueLookupParameter <IOperator>("Recombinator", "The operator used to cross solutions.")); Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization.")); Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored.")); Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation.")); Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated.")); Parameters.Add(new ScopeParameter("CurrentScope", "The current scope which represents a population of solutions on which the EvolutionStrategy should be applied.")); Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterManipulator", "The operator to mutate the endogeneous strategy parameters.")); Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterCrossover", "The operator to cross the endogeneous strategy parameters.")); #endregion #region Create operators VariableCreator variableCreator = new VariableCreator(); ResultsCollector resultsCollector1 = new ResultsCollector(); Placeholder analyzer1 = new Placeholder(); WithoutRepeatingBatchedRandomSelector selector = new WithoutRepeatingBatchedRandomSelector(); SubScopesProcessor subScopesProcessor1 = new SubScopesProcessor(); Comparator useRecombinationComparator = new Comparator(); ConditionalBranch useRecombinationBranch = new ConditionalBranch(); ChildrenCreator childrenCreator = new ChildrenCreator(); UniformSubScopesProcessor uniformSubScopesProcessor1 = new UniformSubScopesProcessor(); Placeholder recombinator = new Placeholder(); Placeholder strategyRecombinator = new Placeholder(); Placeholder strategyMutator1 = new Placeholder(); Placeholder mutator1 = new Placeholder(); SubScopesRemover subScopesRemover = new SubScopesRemover(); UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor(); Placeholder strategyMutator2 = new Placeholder(); Placeholder mutator2 = new Placeholder(); UniformSubScopesProcessor uniformSubScopesProcessor3 = new UniformSubScopesProcessor(); Placeholder evaluator = new Placeholder(); SubScopesCounter subScopesCounter = new SubScopesCounter(); ConditionalBranch plusOrCommaReplacementBranch = new ConditionalBranch(); MergingReducer plusReplacement = new MergingReducer(); RightReducer commaReplacement = new RightReducer(); BestSelector bestSelector = new BestSelector(); RightReducer rightReducer = new RightReducer(); IntCounter intCounter = new IntCounter(); Comparator comparator = new Comparator(); Placeholder analyzer2 = new Placeholder(); ConditionalBranch conditionalBranch = new ConditionalBranch(); ConditionalBranch reevaluateElitesBranch = new ConditionalBranch(); SubScopesProcessor subScopesProcessor2 = new SubScopesProcessor(); UniformSubScopesProcessor uniformSubScopesProcessor4 = new UniformSubScopesProcessor(); Placeholder evaluator2 = new Placeholder(); SubScopesCounter subScopesCounter2 = new SubScopesCounter(); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class EvolutionStrategy expects this to be called Generations resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations")); resultsCollector1.ResultsParameter.ActualName = "Results"; analyzer1.Name = "Analyzer (placeholder)"; analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name; selector.Name = "ES Random Selector"; selector.RandomParameter.ActualName = RandomParameter.Name; selector.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name; selector.ChildrenParameter.ActualName = ChildrenParameter.Name; useRecombinationComparator.Name = "ParentsPerChild > 1"; useRecombinationComparator.LeftSideParameter.ActualName = ParentsPerChildParameter.Name; useRecombinationComparator.RightSideParameter.Value = new IntValue(1); useRecombinationComparator.Comparison = new Comparison(ComparisonType.Greater); useRecombinationComparator.ResultParameter.ActualName = "UseRecombination"; useRecombinationBranch.Name = "Use Recombination?"; useRecombinationBranch.ConditionParameter.ActualName = "UseRecombination"; childrenCreator.ParentsPerChild = null; childrenCreator.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name; recombinator.Name = "Recombinator (placeholder)"; recombinator.OperatorParameter.ActualName = RecombinatorParameter.Name; strategyRecombinator.Name = "Strategy Parameter Recombinator (placeholder)"; strategyRecombinator.OperatorParameter.ActualName = StrategyParameterCrossoverParameter.Name; strategyMutator1.Name = "Strategy Parameter Manipulator (placeholder)"; strategyMutator1.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name; mutator1.Name = "Mutator (placeholder)"; mutator1.OperatorParameter.ActualName = MutatorParameter.Name; subScopesRemover.RemoveAllSubScopes = true; strategyMutator2.Name = "Strategy Parameter Manipulator (placeholder)"; strategyMutator2.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name; mutator2.Name = "Mutator (placeholder)"; mutator2.OperatorParameter.ActualName = MutatorParameter.Name; uniformSubScopesProcessor3.Parallel.Value = true; evaluator.Name = "Evaluator (placeholder)"; evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter.Name = "Increment EvaluatedSolutions"; subScopesCounter.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; plusOrCommaReplacementBranch.ConditionParameter.ActualName = PlusSelectionParameter.Name; bestSelector.CopySelected = new BoolValue(false); bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; bestSelector.NumberOfSelectedSubScopesParameter.ActualName = PopulationSizeParameter.Name; bestSelector.QualityParameter.ActualName = QualityParameter.Name; intCounter.Increment = new IntValue(1); intCounter.ValueParameter.ActualName = "Generations"; comparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual); comparator.LeftSideParameter.ActualName = "Generations"; comparator.ResultParameter.ActualName = "Terminate"; comparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name; analyzer2.Name = "Analyzer (placeholder)"; analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name; conditionalBranch.ConditionParameter.ActualName = "Terminate"; reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites"; reevaluateElitesBranch.Name = "Reevaluate elites ?"; uniformSubScopesProcessor4.Parallel.Value = true; evaluator2.Name = "Evaluator (placeholder)"; evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter2.Name = "Increment EvaluatedSolutions"; subScopesCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; #endregion #region Create operator graph OperatorGraph.InitialOperator = variableCreator; variableCreator.Successor = resultsCollector1; resultsCollector1.Successor = analyzer1; analyzer1.Successor = selector; selector.Successor = subScopesProcessor1; subScopesProcessor1.Operators.Add(new EmptyOperator()); subScopesProcessor1.Operators.Add(useRecombinationComparator); subScopesProcessor1.Successor = plusOrCommaReplacementBranch; useRecombinationComparator.Successor = useRecombinationBranch; useRecombinationBranch.TrueBranch = childrenCreator; useRecombinationBranch.FalseBranch = uniformSubScopesProcessor2; useRecombinationBranch.Successor = uniformSubScopesProcessor3; childrenCreator.Successor = uniformSubScopesProcessor1; uniformSubScopesProcessor1.Operator = recombinator; uniformSubScopesProcessor1.Successor = null; recombinator.Successor = strategyRecombinator; strategyRecombinator.Successor = strategyMutator1; strategyMutator1.Successor = mutator1; mutator1.Successor = subScopesRemover; subScopesRemover.Successor = null; uniformSubScopesProcessor2.Operator = strategyMutator2; uniformSubScopesProcessor2.Successor = null; strategyMutator2.Successor = mutator2; mutator2.Successor = null; uniformSubScopesProcessor3.Operator = evaluator; uniformSubScopesProcessor3.Successor = subScopesCounter; evaluator.Successor = null; subScopesCounter.Successor = null; plusOrCommaReplacementBranch.TrueBranch = reevaluateElitesBranch; reevaluateElitesBranch.TrueBranch = subScopesProcessor2; reevaluateElitesBranch.FalseBranch = null; subScopesProcessor2.Operators.Add(uniformSubScopesProcessor4); subScopesProcessor2.Operators.Add(new EmptyOperator()); uniformSubScopesProcessor4.Operator = evaluator2; uniformSubScopesProcessor4.Successor = subScopesCounter2; subScopesCounter2.Successor = null; reevaluateElitesBranch.Successor = plusReplacement; plusOrCommaReplacementBranch.FalseBranch = commaReplacement; plusOrCommaReplacementBranch.Successor = bestSelector; bestSelector.Successor = rightReducer; rightReducer.Successor = intCounter; intCounter.Successor = comparator; comparator.Successor = analyzer2; analyzer2.Successor = conditionalBranch; conditionalBranch.FalseBranch = selector; conditionalBranch.TrueBranch = null; conditionalBranch.Successor = null; #endregion }
private SignatureBuilder(Placeholder roleId) { this.roleId = roleId; }
private void Initialize() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction.")); Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions.")); Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.")); Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions.")); Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization.")); Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation.")); Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.")); Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored.")); Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation.")); Parameters.Add(new ValueLookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated.")); Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population.")); Parameters.Add(new ValueLookupParameter <IntValue>("MinimumPopulationSize", "The minimum size of the population of solutions.")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumPopulationSize", "The maximum size of the population of solutions.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("ComparisonFactor", "The comparison factor.")); Parameters.Add(new ValueLookupParameter <IntValue>("Effort", "The maximum number of offspring created in each generation.")); Parameters.Add(new ValueLookupParameter <IntValue>("BatchSize", "The number of children that should be created during one iteration of the offspring creation process.")); Parameters.Add(new ValueLookupParameter <ISolutionSimilarityCalculator>("SimilarityCalculator", "The operator used to calculate the similarity between two solutions.")); Parameters.Add(new ScopeParameter("CurrentScope", "The current scope which represents a population of solutions on which the genetic algorithm should be applied.")); #endregion #region Create operators VariableCreator variableCreator = new VariableCreator(); Assigner assigner1 = new Assigner(); ResultsCollector resultsCollector = new ResultsCollector(); Placeholder analyzer1 = new Placeholder(); Placeholder selector = new Placeholder(); SubScopesProcessor subScopesProcessor1 = new SubScopesProcessor(); ChildrenCreator childrenCreator = new ChildrenCreator(); UniformSubScopesProcessor uniformSubScopesProcessor = new UniformSubScopesProcessor(); Placeholder crossover = new Placeholder(); StochasticBranch stochasticBranch = new StochasticBranch(); Placeholder mutator = new Placeholder(); Placeholder evaluator = new Placeholder(); WeightedParentsQualityComparator weightedParentsQualityComparator = new WeightedParentsQualityComparator(); SubScopesRemover subScopesRemover = new SubScopesRemover(); IntCounter intCounter1 = new IntCounter(); IntCounter intCounter2 = new IntCounter(); ConditionalSelector conditionalSelector = new ConditionalSelector(); RightReducer rightReducer1 = new RightReducer(); DuplicatesSelector duplicateSelector = new DuplicatesSelector(); LeftReducer leftReducer1 = new LeftReducer(); ProgressiveOffspringPreserver progressiveOffspringSelector = new ProgressiveOffspringPreserver(); SubScopesCounter subScopesCounter2 = new SubScopesCounter(); ExpressionCalculator calculator1 = new ExpressionCalculator(); ConditionalBranch conditionalBranch1 = new ConditionalBranch(); Comparator comparator1 = new Comparator(); ConditionalBranch conditionalBranch2 = new ConditionalBranch(); LeftReducer leftReducer2 = new LeftReducer(); SubScopesProcessor subScopesProcessor2 = new SubScopesProcessor(); BestSelector bestSelector = new BestSelector(); RightReducer rightReducer2 = new RightReducer(); ScopeCleaner scopeCleaner = new ScopeCleaner(); ScopeRestorer scopeRestorer = new ScopeRestorer(); MergingReducer mergingReducer = new MergingReducer(); IntCounter intCounter3 = new IntCounter(); SubScopesCounter subScopesCounter3 = new SubScopesCounter(); ExpressionCalculator calculator2 = new ExpressionCalculator(); Comparator comparator2 = new Comparator(); ConditionalBranch conditionalBranch3 = new ConditionalBranch(); Placeholder analyzer2 = new Placeholder(); Comparator comparator3 = new Comparator(); ConditionalBranch conditionalBranch4 = new ConditionalBranch(); Comparator comparator4 = new Comparator(); ConditionalBranch conditionalBranch5 = new ConditionalBranch(); Assigner assigner3 = new Assigner(); Assigner assigner4 = new Assigner(); Assigner assigner5 = new Assigner(); ConditionalBranch reevaluateElitesBranch = new ConditionalBranch(); UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor(); Placeholder evaluator2 = new Placeholder(); SubScopesCounter subScopesCounter4 = new SubScopesCounter(); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class RAPGA expects this to be called Generations variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("CurrentPopulationSize", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("NumberOfCreatedOffspring", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("NumberOfSuccessfulOffspring", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <ScopeList>("OffspringList", new ScopeList())); assigner1.Name = "Initialize CurrentPopulationSize"; assigner1.LeftSideParameter.ActualName = "CurrentPopulationSize"; assigner1.RightSideParameter.ActualName = PopulationSizeParameter.Name; resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Generations")); resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("CurrentPopulationSize")); resultsCollector.ResultsParameter.ActualName = "Results"; analyzer1.Name = "Analyzer"; analyzer1.OperatorParameter.ActualName = "Analyzer"; selector.Name = "Selector"; selector.OperatorParameter.ActualName = "Selector"; childrenCreator.ParentsPerChild = new IntValue(2); uniformSubScopesProcessor.Parallel.Value = true; crossover.Name = "Crossover"; crossover.OperatorParameter.ActualName = "Crossover"; stochasticBranch.ProbabilityParameter.ActualName = "MutationProbability"; stochasticBranch.RandomParameter.ActualName = "Random"; mutator.Name = "Mutator"; mutator.OperatorParameter.ActualName = "Mutator"; evaluator.Name = "Evaluator"; evaluator.OperatorParameter.ActualName = "Evaluator"; weightedParentsQualityComparator.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name; weightedParentsQualityComparator.LeftSideParameter.ActualName = QualityParameter.Name; weightedParentsQualityComparator.MaximizationParameter.ActualName = MaximizationParameter.Name; weightedParentsQualityComparator.RightSideParameter.ActualName = QualityParameter.Name; weightedParentsQualityComparator.ResultParameter.ActualName = "SuccessfulOffspring"; subScopesRemover.RemoveAllSubScopes = true; intCounter1.Name = "Increment NumberOfCreatedOffspring"; intCounter1.ValueParameter.ActualName = "NumberOfCreatedOffspring"; intCounter1.Increment = null; intCounter1.IncrementParameter.ActualName = BatchSizeParameter.Name; intCounter2.Name = "Increment EvaluatedSolutions"; intCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; intCounter2.Increment = null; intCounter2.IncrementParameter.ActualName = BatchSizeParameter.Name; conditionalSelector.ConditionParameter.ActualName = "SuccessfulOffspring"; conditionalSelector.ConditionParameter.Depth = 1; conditionalSelector.CopySelected.Value = false; duplicateSelector.CopySelected.Value = false; progressiveOffspringSelector.OffspringListParameter.ActualName = "OffspringList"; progressiveOffspringSelector.ElitesParameter.ActualName = ElitesParameter.Name; progressiveOffspringSelector.MaximumPopulationSizeParameter.ActualName = MaximumPopulationSizeParameter.Name; subScopesCounter2.Name = "Count Successful Offspring"; subScopesCounter2.ValueParameter.ActualName = "NumberOfSuccessfulOffspring"; calculator1.Name = "NumberOfSuccessfulOffspring == MaximumPopulationSize - Elites"; calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("NumberOfSuccessfulOffspring")); calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("MaximumPopulationSize")); calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("Elites")); calculator1.ExpressionParameter.Value = new StringValue("NumberOfSuccessfulOffspring MaximumPopulationSize Elites - =="); calculator1.ExpressionResultParameter.ActualName = "Break"; conditionalBranch1.Name = "Break?"; conditionalBranch1.ConditionParameter.ActualName = "Break"; comparator1.Name = "NumberOfCreatedOffspring >= Effort"; comparator1.Comparison = new Comparison(ComparisonType.GreaterOrEqual); comparator1.LeftSideParameter.ActualName = "NumberOfCreatedOffspring"; comparator1.RightSideParameter.ActualName = EffortParameter.Name; comparator1.ResultParameter.ActualName = "Break"; conditionalBranch2.Name = "Break?"; conditionalBranch2.ConditionParameter.ActualName = "Break"; bestSelector.CopySelected = new BoolValue(false); bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; bestSelector.NumberOfSelectedSubScopesParameter.ActualName = "Elites"; bestSelector.QualityParameter.ActualName = QualityParameter.Name; intCounter3.Name = "Increment Generations"; intCounter3.Increment = new IntValue(1); intCounter3.ValueParameter.ActualName = "Generations"; subScopesCounter3.Name = "Update CurrentPopulationSize"; subScopesCounter3.ValueParameter.ActualName = "CurrentPopulationSize"; subScopesCounter3.AccumulateParameter.Value = new BoolValue(false); calculator2.Name = "Evaluate ActualSelectionPressure"; calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("NumberOfCreatedOffspring")); calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("Elites")); calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("CurrentPopulationSize")); calculator2.ExpressionParameter.Value = new StringValue("NumberOfCreatedOffspring Elites + CurrentPopulationSize /"); calculator2.ExpressionResultParameter.ActualName = "ActualSelectionPressure"; comparator2.Name = "CurrentPopulationSize < 1"; comparator2.Comparison = new Comparison(ComparisonType.Less); comparator2.LeftSideParameter.ActualName = "CurrentPopulationSize"; comparator2.RightSideParameter.Value = new IntValue(1); comparator2.ResultParameter.ActualName = "Terminate"; conditionalBranch3.Name = "Terminate?"; conditionalBranch3.ConditionParameter.ActualName = "Terminate"; analyzer2.Name = "Analyzer"; analyzer2.OperatorParameter.ActualName = "Analyzer"; comparator3.Name = "Generations >= MaximumGenerations"; comparator3.Comparison = new Comparison(ComparisonType.GreaterOrEqual); comparator3.LeftSideParameter.ActualName = "Generations"; comparator3.ResultParameter.ActualName = "Terminate"; comparator3.RightSideParameter.ActualName = MaximumGenerationsParameter.Name; conditionalBranch4.Name = "Terminate?"; conditionalBranch4.ConditionParameter.ActualName = "Terminate"; comparator4.Name = "CurrentPopulationSize < MinimumPopulationSize"; comparator4.Comparison = new Comparison(ComparisonType.Less); comparator4.LeftSideParameter.ActualName = "CurrentPopulationSize"; comparator4.RightSideParameter.ActualName = MinimumPopulationSizeParameter.Name; comparator4.ResultParameter.ActualName = "Terminate"; conditionalBranch5.Name = "Terminate?"; conditionalBranch5.ConditionParameter.ActualName = "Terminate"; assigner3.Name = "Reset NumberOfCreatedOffspring"; assigner3.LeftSideParameter.ActualName = "NumberOfCreatedOffspring"; assigner3.RightSideParameter.Value = new IntValue(0); assigner4.Name = "Reset NumberOfSuccessfulOffspring"; assigner4.LeftSideParameter.ActualName = "NumberOfSuccessfulOffspring"; assigner4.RightSideParameter.Value = new IntValue(0); assigner5.Name = "Reset OffspringList"; assigner5.LeftSideParameter.ActualName = "OffspringList"; assigner5.RightSideParameter.Value = new ScopeList(); reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites"; reevaluateElitesBranch.Name = "Reevaluate elites ?"; uniformSubScopesProcessor2.Parallel.Value = true; evaluator2.Name = "Evaluator (placeholder)"; evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter4.Name = "Increment EvaluatedSolutions"; subScopesCounter4.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; #endregion #region Create operator graph OperatorGraph.InitialOperator = variableCreator; variableCreator.Successor = assigner1; assigner1.Successor = resultsCollector; resultsCollector.Successor = analyzer1; analyzer1.Successor = selector; selector.Successor = subScopesProcessor1; subScopesProcessor1.Operators.Add(new EmptyOperator()); subScopesProcessor1.Operators.Add(childrenCreator); subScopesProcessor1.Successor = calculator1; childrenCreator.Successor = uniformSubScopesProcessor; uniformSubScopesProcessor.Operator = crossover; uniformSubScopesProcessor.Successor = intCounter1; crossover.Successor = stochasticBranch; stochasticBranch.FirstBranch = mutator; stochasticBranch.SecondBranch = null; mutator.Successor = null; stochasticBranch.Successor = evaluator; evaluator.Successor = weightedParentsQualityComparator; weightedParentsQualityComparator.Successor = subScopesRemover; intCounter1.Successor = intCounter2; intCounter2.Successor = conditionalSelector; conditionalSelector.Successor = rightReducer1; rightReducer1.Successor = duplicateSelector; duplicateSelector.Successor = leftReducer1; leftReducer1.Successor = progressiveOffspringSelector; progressiveOffspringSelector.Successor = subScopesCounter2; calculator1.Successor = conditionalBranch1; conditionalBranch1.FalseBranch = comparator1; conditionalBranch1.TrueBranch = subScopesProcessor2; comparator1.Successor = conditionalBranch2; conditionalBranch2.FalseBranch = leftReducer2; conditionalBranch2.TrueBranch = subScopesProcessor2; leftReducer2.Successor = selector; subScopesProcessor2.Operators.Add(bestSelector); subScopesProcessor2.Operators.Add(scopeCleaner); subScopesProcessor2.Successor = mergingReducer; bestSelector.Successor = rightReducer2; rightReducer2.Successor = reevaluateElitesBranch; reevaluateElitesBranch.TrueBranch = uniformSubScopesProcessor2; uniformSubScopesProcessor2.Operator = evaluator2; uniformSubScopesProcessor2.Successor = subScopesCounter4; evaluator2.Successor = null; subScopesCounter4.Successor = null; reevaluateElitesBranch.FalseBranch = null; reevaluateElitesBranch.Successor = null; scopeCleaner.Successor = scopeRestorer; mergingReducer.Successor = intCounter3; intCounter3.Successor = subScopesCounter3; subScopesCounter3.Successor = calculator2; calculator2.Successor = comparator2; comparator2.Successor = conditionalBranch3; conditionalBranch3.FalseBranch = analyzer2; conditionalBranch3.TrueBranch = null; analyzer2.Successor = comparator3; comparator3.Successor = conditionalBranch4; conditionalBranch4.FalseBranch = comparator4; conditionalBranch4.TrueBranch = null; conditionalBranch4.Successor = null; comparator4.Successor = conditionalBranch5; conditionalBranch5.FalseBranch = assigner3; conditionalBranch5.TrueBranch = null; conditionalBranch5.Successor = null; assigner3.Successor = assigner4; assigner4.Successor = assigner5; assigner5.Successor = selector; #endregion }
public static SignatureBuilder InitialsFor(Placeholder roleId) { return(new SignatureBuilder(roleId).WithStyle(SignatureStyle.INITIALS)); }
public ParticleSwarmOptimization() : base() { Parameters.Add(new ValueParameter <IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0))); Parameters.Add(new ValueParameter <BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true))); Parameters.Add(new ValueParameter <IntValue>("SwarmSize", "Size of the particle swarm.", new IntValue(40))); Parameters.Add(new ValueParameter <IntValue>("MaxIterations", "Maximal number of iterations.", new IntValue(1000))); Parameters.Add(new ValueParameter <MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer())); Parameters.Add(new ValueParameter <DoubleValue>("Inertia", "Inertia weight on a particle's movement (omega).", new DoubleValue(0.721))); Parameters.Add(new ValueParameter <DoubleValue>("PersonalBestAttraction", "Weight for particle's pull towards its personal best soution (phi_p).", new DoubleValue(1.193))); Parameters.Add(new ValueParameter <DoubleValue>("NeighborBestAttraction", "Weight for pull towards the neighborhood best solution or global best solution in case of a totally connected topology (phi_g).", new DoubleValue(1.193))); Parameters.Add(new ConstrainedValueParameter <IParticleCreator>("ParticleCreator", "Operator that creates a new particle.")); Parameters.Add(new ConstrainedValueParameter <IParticleUpdater>("ParticleUpdater", "Operator that updates a particle.")); Parameters.Add(new OptionalConstrainedValueParameter <ITopologyInitializer>("TopologyInitializer", "Creates neighborhood description vectors.")); Parameters.Add(new OptionalConstrainedValueParameter <ITopologyUpdater>("TopologyUpdater", "Updates the neighborhood description vectors.")); Parameters.Add(new OptionalConstrainedValueParameter <IDiscreteDoubleValueModifier>("InertiaUpdater", "Updates the omega parameter.")); Parameters.Add(new ConstrainedValueParameter <ISwarmUpdater>("SwarmUpdater", "Encoding-specific parameter which is provided by the problem. May provide additional encoding-specific parameters, such as velocity bounds for real valued problems")); RandomCreator randomCreator = new RandomCreator(); VariableCreator variableCreator = new VariableCreator(); Assigner currentInertiaAssigner = new Assigner(); solutionsCreator = new SolutionsCreator(); SubScopesCounter subScopesCounter = new SubScopesCounter(); Placeholder topologyInitializerPlaceholder = new Placeholder(); mainLoop = new ParticleSwarmOptimizationMainLoop(); OperatorGraph.InitialOperator = randomCreator; randomCreator.SetSeedRandomlyParameter.Value = null; randomCreator.SeedParameter.Value = null; randomCreator.Successor = variableCreator; variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0))); variableCreator.Successor = currentInertiaAssigner; currentInertiaAssigner.Name = "CurrentInertia := Inertia"; currentInertiaAssigner.LeftSideParameter.ActualName = "CurrentInertia"; currentInertiaAssigner.RightSideParameter.ActualName = "Inertia"; currentInertiaAssigner.Successor = solutionsCreator; solutionsCreator.NumberOfSolutionsParameter.ActualName = "SwarmSize"; ParameterizeSolutionsCreator(); solutionsCreator.Successor = subScopesCounter; subScopesCounter.Name = "Initialize EvaluatedSolutions"; subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions"; subScopesCounter.Successor = topologyInitializerPlaceholder; topologyInitializerPlaceholder.Name = "(TopologyInitializer)"; topologyInitializerPlaceholder.OperatorParameter.ActualName = "TopologyInitializer"; topologyInitializerPlaceholder.Successor = mainLoop; mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name; mainLoop.InertiaParameter.ActualName = "CurrentInertia"; mainLoop.MaxIterationsParameter.ActualName = MaxIterationsParameter.Name; mainLoop.NeighborBestAttractionParameter.ActualName = NeighborBestAttractionParameter.Name; mainLoop.InertiaUpdaterParameter.ActualName = InertiaUpdaterParameter.Name; mainLoop.ParticleUpdaterParameter.ActualName = ParticleUpdaterParameter.Name; mainLoop.PersonalBestAttractionParameter.ActualName = PersonalBestAttractionParameter.Name; mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName; mainLoop.SwarmSizeParameter.ActualName = SwarmSizeParameter.Name; mainLoop.TopologyUpdaterParameter.ActualName = TopologyUpdaterParameter.Name; mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName; mainLoop.ResultsParameter.ActualName = "Results"; InitializeAnalyzers(); InitializeParticleCreator(); InitializeSwarmUpdater(); ParameterizeSolutionsCreator(); UpdateAnalyzers(); UpdateInertiaUpdater(); InitInertiaUpdater(); UpdateTopologyInitializer(); Initialize(); ParameterizeMainLoop(); }
private void Initialize() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction.")); Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions.")); Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.")); Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions.")); Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization.")); Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of evaluated solutions.")); Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation.")); Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)")); Parameters.Add(new LookupParameter <DoubleValue>("ComparisonFactor", "The comparison factor is used to determine whether the offspring should be compared to the better parent, the worse parent or a quality value linearly interpolated between them. It is in the range [0;1].")); Parameters.Add(new LookupParameter <DoubleValue>("CurrentSuccessRatio", "The current success ratio.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.")); Parameters.Add(new LookupParameter <DoubleValue>("SelectionPressure", "The actual selection pressure.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.")); Parameters.Add(new ValueLookupParameter <BoolValue>("OffspringSelectionBeforeMutation", "True if the offspring selection step should be applied before mutation, false if it should be applied after mutation.")); Parameters.Add(new ValueLookupParameter <BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded.")); #endregion #region Create operators Placeholder selector = new Placeholder(); SubScopesProcessor subScopesProcessor1 = new SubScopesProcessor(); ChildrenCreator childrenCreator = new ChildrenCreator(); ConditionalBranch osBeforeMutationBranch = new ConditionalBranch(); UniformSubScopesProcessor uniformSubScopesProcessor1 = new UniformSubScopesProcessor(); Placeholder crossover1 = new Placeholder(); UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor(); Placeholder evaluator1 = new Placeholder(); SubScopesCounter subScopesCounter1 = new SubScopesCounter(); WeightedParentsQualityComparator qualityComparer1 = new WeightedParentsQualityComparator(); SubScopesRemover subScopesRemover1 = new SubScopesRemover(); UniformSubScopesProcessor uniformSubScopesProcessor3 = new UniformSubScopesProcessor(); StochasticBranch mutationBranch1 = new StochasticBranch(); Placeholder mutator1 = new Placeholder(); VariableCreator variableCreator1 = new VariableCreator(); VariableCreator variableCreator2 = new VariableCreator(); ConditionalSelector conditionalSelector = new ConditionalSelector(); SubScopesProcessor subScopesProcessor2 = new SubScopesProcessor(); UniformSubScopesProcessor uniformSubScopesProcessor4 = new UniformSubScopesProcessor(); Placeholder evaluator2 = new Placeholder(); SubScopesCounter subScopesCounter2 = new SubScopesCounter(); MergingReducer mergingReducer1 = new MergingReducer(); UniformSubScopesProcessor uniformSubScopesProcessor5 = new UniformSubScopesProcessor(); Placeholder crossover2 = new Placeholder(); StochasticBranch mutationBranch2 = new StochasticBranch(); Placeholder mutator2 = new Placeholder(); UniformSubScopesProcessor uniformSubScopesProcessor6 = new UniformSubScopesProcessor(); Placeholder evaluator3 = new Placeholder(); SubScopesCounter subScopesCounter3 = new SubScopesCounter(); WeightedParentsQualityComparator qualityComparer2 = new WeightedParentsQualityComparator(); SubScopesRemover subScopesRemover2 = new SubScopesRemover(); OffspringSelector offspringSelector = new OffspringSelector(); SubScopesProcessor subScopesProcessor3 = new SubScopesProcessor(); BestSelector bestSelector = new BestSelector(); WorstSelector worstSelector = new WorstSelector(); RightReducer rightReducer = new RightReducer(); LeftReducer leftReducer = new LeftReducer(); MergingReducer mergingReducer2 = new MergingReducer(); ConditionalBranch reevaluateElitesBranch = new ConditionalBranch(); UniformSubScopesProcessor uniformSubScopesProcessor7 = new UniformSubScopesProcessor(); Placeholder evaluator4 = new Placeholder(); SubScopesCounter subScopesCounter4 = new SubScopesCounter(); selector.Name = "Selector (placeholder)"; selector.OperatorParameter.ActualName = SelectorParameter.Name; childrenCreator.ParentsPerChild = new IntValue(2); osBeforeMutationBranch.Name = "Apply OS before mutation?"; osBeforeMutationBranch.ConditionParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name; crossover1.Name = "Crossover (placeholder)"; crossover1.OperatorParameter.ActualName = CrossoverParameter.Name; uniformSubScopesProcessor2.Parallel.Value = true; evaluator1.Name = "Evaluator (placeholder)"; evaluator1.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter1.Name = "Increment EvaluatedSolutions"; subScopesCounter1.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; qualityComparer1.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name; qualityComparer1.LeftSideParameter.ActualName = QualityParameter.Name; qualityComparer1.MaximizationParameter.ActualName = MaximizationParameter.Name; qualityComparer1.RightSideParameter.ActualName = QualityParameter.Name; qualityComparer1.ResultParameter.ActualName = "SuccessfulOffspring"; subScopesRemover1.RemoveAllSubScopes = true; mutationBranch1.ProbabilityParameter.ActualName = MutationProbabilityParameter.Name; mutationBranch1.RandomParameter.ActualName = RandomParameter.Name; mutator1.Name = "Mutator (placeholder)"; mutator1.OperatorParameter.ActualName = MutatorParameter.Name; variableCreator1.Name = "MutatedOffspring = true"; variableCreator1.CollectedValues.Add(new ValueParameter <BoolValue>("MutatedOffspring", null, new BoolValue(true), false)); variableCreator2.Name = "MutatedOffspring = false"; variableCreator2.CollectedValues.Add(new ValueParameter <BoolValue>("MutatedOffspring", null, new BoolValue(false), false)); conditionalSelector.ConditionParameter.ActualName = "MutatedOffspring"; conditionalSelector.ConditionParameter.Depth = 1; conditionalSelector.CopySelected.Value = false; uniformSubScopesProcessor4.Parallel.Value = true; evaluator2.Name = "Evaluator (placeholder)"; evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter2.Name = "Increment EvaluatedSolutions"; subScopesCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; crossover2.Name = "Crossover (placeholder)"; crossover2.OperatorParameter.ActualName = CrossoverParameter.Name; mutationBranch2.ProbabilityParameter.ActualName = MutationProbabilityParameter.Name; mutationBranch2.RandomParameter.ActualName = RandomParameter.Name; mutator2.Name = "Mutator (placeholder)"; mutator2.OperatorParameter.ActualName = MutatorParameter.Name; uniformSubScopesProcessor6.Parallel.Value = true; evaluator3.Name = "Evaluator (placeholder)"; evaluator3.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter3.Name = "Increment EvaluatedSolutions"; subScopesCounter3.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; qualityComparer2.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name; qualityComparer2.LeftSideParameter.ActualName = QualityParameter.Name; qualityComparer2.MaximizationParameter.ActualName = MaximizationParameter.Name; qualityComparer2.RightSideParameter.ActualName = QualityParameter.Name; qualityComparer2.ResultParameter.ActualName = "SuccessfulOffspring"; subScopesRemover2.RemoveAllSubScopes = true; offspringSelector.CurrentSuccessRatioParameter.ActualName = CurrentSuccessRatioParameter.Name; offspringSelector.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name; offspringSelector.SelectionPressureParameter.ActualName = SelectionPressureParameter.Name; offspringSelector.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name; offspringSelector.OffspringPopulationParameter.ActualName = "OffspringPopulation"; offspringSelector.OffspringPopulationWinnersParameter.ActualName = "OffspringPopulationWinners"; offspringSelector.SuccessfulOffspringParameter.ActualName = "SuccessfulOffspring"; offspringSelector.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name; bestSelector.CopySelected = new BoolValue(false); bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; bestSelector.NumberOfSelectedSubScopesParameter.ActualName = ElitesParameter.Name; bestSelector.QualityParameter.ActualName = QualityParameter.Name; worstSelector.CopySelected = new BoolValue(false); worstSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; worstSelector.NumberOfSelectedSubScopesParameter.ActualName = ElitesParameter.Name; worstSelector.QualityParameter.ActualName = QualityParameter.Name; reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites"; reevaluateElitesBranch.Name = "Reevaluate elites ?"; uniformSubScopesProcessor7.Parallel.Value = true; evaluator4.Name = "Evaluator (placeholder)"; evaluator4.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter4.Name = "Increment EvaluatedSolutions"; subScopesCounter4.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name; #endregion #region Create operator graph OperatorGraph.InitialOperator = selector; selector.Successor = subScopesProcessor1; subScopesProcessor1.Operators.Add(new EmptyOperator()); subScopesProcessor1.Operators.Add(childrenCreator); subScopesProcessor1.Successor = offspringSelector; childrenCreator.Successor = osBeforeMutationBranch; osBeforeMutationBranch.TrueBranch = uniformSubScopesProcessor1; osBeforeMutationBranch.FalseBranch = uniformSubScopesProcessor5; osBeforeMutationBranch.Successor = null; uniformSubScopesProcessor1.Operator = crossover1; uniformSubScopesProcessor1.Successor = uniformSubScopesProcessor2; crossover1.Successor = null; uniformSubScopesProcessor2.Operator = evaluator1; uniformSubScopesProcessor2.Successor = subScopesCounter1; evaluator1.Successor = qualityComparer1; qualityComparer1.Successor = subScopesRemover1; subScopesRemover1.Successor = null; subScopesCounter1.Successor = uniformSubScopesProcessor3; uniformSubScopesProcessor3.Operator = mutationBranch1; uniformSubScopesProcessor3.Successor = conditionalSelector; mutationBranch1.FirstBranch = mutator1; mutationBranch1.SecondBranch = variableCreator2; mutationBranch1.Successor = null; mutator1.Successor = variableCreator1; variableCreator1.Successor = null; variableCreator2.Successor = null; conditionalSelector.Successor = subScopesProcessor2; subScopesProcessor2.Operators.Add(new EmptyOperator()); subScopesProcessor2.Operators.Add(uniformSubScopesProcessor4); subScopesProcessor2.Successor = mergingReducer1; uniformSubScopesProcessor4.Operator = evaluator2; uniformSubScopesProcessor4.Successor = subScopesCounter2; evaluator2.Successor = null; subScopesCounter2.Successor = null; mergingReducer1.Successor = null; uniformSubScopesProcessor5.Operator = crossover2; uniformSubScopesProcessor5.Successor = uniformSubScopesProcessor6; crossover2.Successor = mutationBranch2; mutationBranch2.FirstBranch = mutator2; mutationBranch2.SecondBranch = null; mutationBranch2.Successor = null; mutator2.Successor = null; uniformSubScopesProcessor6.Operator = evaluator3; uniformSubScopesProcessor6.Successor = subScopesCounter3; evaluator3.Successor = qualityComparer2; qualityComparer2.Successor = subScopesRemover2; subScopesRemover2.Successor = null; subScopesCounter3.Successor = null; offspringSelector.OffspringCreator = selector; offspringSelector.Successor = subScopesProcessor3; subScopesProcessor3.Operators.Add(bestSelector); subScopesProcessor3.Operators.Add(worstSelector); subScopesProcessor3.Successor = mergingReducer2; bestSelector.Successor = rightReducer; rightReducer.Successor = reevaluateElitesBranch; reevaluateElitesBranch.TrueBranch = uniformSubScopesProcessor7; uniformSubScopesProcessor7.Operator = evaluator4; uniformSubScopesProcessor7.Successor = subScopesCounter4; subScopesCounter4.Successor = null; reevaluateElitesBranch.FalseBranch = null; reevaluateElitesBranch.Successor = null; worstSelector.Successor = leftReducer; leftReducer.Successor = null; mergingReducer2.Successor = null; #endregion }
public void TestCalc2(bool useArray) { if(useArray) LispPrinter.PrintVectorsAsLists = true;//required to compare the result IVectorFactory factory = useArray ? (IVectorFactory)new ArrayVectorFactory() : (IVectorFactory)new BNodeVectorFactory(); /* E ← T ((‘+’ / ‘-’) T)* T ← F (('*' / '/') F)* F ← N / '(' E ')' N ← [0-9]+ */ Rule eDigit = new LiteralAnyCharOf("0123456789"); Placeholder eNumber = new Placeholder(); eNumber.Expression = new FirstOf(new CollapseToString(new Sequence(eDigit, eNumber)), new CallbackHandler(eDigit, Convert.ToString)); Placeholder eAdditive = new Placeholder(); Placeholder eMultiplicative = new Placeholder(); Rule eSingular = new FirstOf(eNumber, new ExtractOne(1, new Sequence(new Literal('('), eAdditive, new Literal(')')))); // var BinaryInfixToPrefix = new Function(delegate(object v) { IVector a = (IVector)v; IVector tail = (IVector)a[1]; object x = a[0]; while (tail != factory.Empty) { x = factory.Create(tail[0], x, tail[1]); tail = (IVector)tail[2]; } return x; }); Placeholder eAdditiveSuffix = new Placeholder(); eAdditiveSuffix.Expression = new FirstOf( new Sequence(new LiteralAnyCharOf("+-"), eMultiplicative, eAdditiveSuffix), new EmptyRule(factory.Empty)); eAdditive.Expression = new CallbackHandler(new Sequence(eMultiplicative, eAdditiveSuffix), BinaryInfixToPrefix); Placeholder eMultiplicativeSuffix = new Placeholder(); eMultiplicativeSuffix.Expression = new FirstOf( new Sequence(new LiteralAnyCharOf("*/"), eSingular, eMultiplicativeSuffix), new EmptyRule(factory.Empty)); eMultiplicative.Expression = new CallbackHandler(new Sequence(eSingular, eMultiplicativeSuffix), BinaryInfixToPrefix); Rule expr = eAdditive; { var parser = new Parser(expr, TextCursor.Create("12+3*45+6+789*(6+2)*9+0"), factory); Result r = parser.Run(); string expected = "(+ (+ (+ (+ 12 (* 3 45)) 6) (* (* 789 (+ 6 2)) 9)) 0)"; Assert.IsNotNull(r); Assert.IsFalse(r.Cursor.CanPop()); Assert.AreEqual(expected, Convert.ToString(r.Value).Replace("\"", "").Replace("'", "")); object num = new CalculatorVisitor().Process(r.Value); Assert.AreEqual(Convert.ToDouble(12 + 3 * 45 + 6 + 789 * (6 + 2) * 9 + 0), num); } { var parser = new Parser(expr, TextCursor.Create("12+3*4a5+6+7*(6+2)*9+0"), factory); Result r = parser.Run(); //Assert.IsNull(r); Assert.IsTrue(r.Cursor.CanPop()); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(6, parser.FailCursor.Position); } { var parser = new Parser(expr, TextCursor.Create("12+3*45+(6+7*(6+2)*9+0"), factory); Result r = parser.Run(); //Assert.IsNull(r); Assert.IsTrue(r.Cursor.CanPop()); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(22, parser.FailCursor.Position); } { var parser = new Parser(expr, TextCursor.Create("(12+3*45+(6+7*(6+2)*9+0)"), factory); Result r = parser.Run(); Assert.IsNull(r); //Assert.AreNotEqual(TextCursor.EOI, r.Cursor.Peek()); if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debug.WriteLine(parser.GetError()); } Assert.AreEqual(24, parser.FailCursor.Position); } }
public RandomSearchAlgorithm() : base() { #region Add parameters Parameters.Add(new FixedValueParameter <IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0))); Parameters.Add(new FixedValueParameter <BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true))); Parameters.Add(new FixedValueParameter <MultiAnalyzer>("Analyzer", "The operator used to analyze the solutions each iteration.", new MultiAnalyzer())); Parameters.Add(new FixedValueParameter <IntValue>("MaximumEvaluatedSolutions", "The number of random solutions the algorithm should evaluate.", new IntValue(1000))); Parameters.Add(new FixedValueParameter <IntValue>("BatchSize", "The number of random solutions that are evaluated (in parallel) per iteration.", new IntValue(100))); Parameters.Add(new FixedValueParameter <IntValue>("MaximumIterations", "The number of iterations that the algorithm will run.", new IntValue(10)) { Hidden = true }); Parameters.Add(new FixedValueParameter <MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator()) { Hidden = true }); #endregion #region Create operators var randomCreator = new RandomCreator(); var variableCreator = new VariableCreator() { Name = "Initialize Variables" }; var resultsCollector = new ResultsCollector(); var solutionCreator = new SolutionsCreator() { Name = "Create Solutions" }; var analyzerPlaceholder = new Placeholder() { Name = "Analyzer (Placeholder)" }; var evaluationsCounter = new IntCounter() { Name = "Increment EvaluatedSolutions" }; var subScopesRemover = new SubScopesRemover(); var iterationsCounter = new IntCounter() { Name = "Increment Iterations" }; var terminationOperator = new TerminationOperator(); #endregion #region Create and parameterize operator graph OperatorGraph.InitialOperator = randomCreator; randomCreator.SeedParameter.Value = null; randomCreator.SeedParameter.ActualName = SeedParameter.Name; randomCreator.SetSeedRandomlyParameter.Value = null; randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name; randomCreator.Successor = variableCreator; variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("EvaluatedSolutions", new IntValue(0))); variableCreator.Successor = resultsCollector; resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Iterations", "The current iteration number.")); resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The current number of evaluated solutions.")); resultsCollector.Successor = solutionCreator; solutionCreator.NumberOfSolutionsParameter.ActualName = BatchSizeParameter.Name; solutionCreator.ParallelParameter.Value.Value = true; solutionCreator.Successor = evaluationsCounter; evaluationsCounter.ValueParameter.ActualName = "EvaluatedSolutions"; evaluationsCounter.Increment = null; evaluationsCounter.IncrementParameter.ActualName = BatchSizeParameter.Name; evaluationsCounter.Successor = analyzerPlaceholder; analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name; analyzerPlaceholder.Successor = subScopesRemover; subScopesRemover.RemoveAllSubScopes = true; subScopesRemover.Successor = iterationsCounter; iterationsCounter.ValueParameter.ActualName = "Iterations"; iterationsCounter.Increment = new IntValue(1); iterationsCounter.Successor = terminationOperator; terminationOperator.TerminatorParameter.ActualName = TerminatorParameter.Name; terminationOperator.ContinueBranch = solutionCreator; #endregion #region Create analyzers singleObjectiveQualityAnalyzer = new BestAverageWorstQualityAnalyzer(); #endregion #region Create terminators evaluationsTerminator = new ComparisonTerminator <IntValue>("EvaluatedSolutions", ComparisonType.Less, MaximumEvaluatedSolutionsParameter) { Name = "Evaluated solutions." }; qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" }; executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5))); #endregion #region Parameterize UpdateAnalyzers(); ParameterizeAnalyzers(); UpdateTerminators(); #endregion Initialize(); }
public Format ParseFormat(string format) { var result = new Format(format); var current = result; Placeholder currentPlaceholder = null; // Store parsing errors until the end: var parsingErrors = new ParsingErrors(result); int nestedDepth = 0; int lastI = 0; int operatorIndex = 0; int selectorIndex = 0; for (int i = 0, length = format.Length; i < length; i++) { var c = format[i]; if (currentPlaceholder == null) { if (c == '{') { // Finish the last text item: if (i != lastI) { current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); } lastI = i + 1; // See if this brace should be escaped: if (!this.AlternativeEscaping) { var nextI = lastI; if (nextI < length && format[nextI] == '{') { i++; continue; } } // New placeholder: nestedDepth++; currentPlaceholder = new Placeholder(current, i, nestedDepth); current.Items.Add(currentPlaceholder); current.HasNested = true; operatorIndex = i + 1; selectorIndex = 0; } else if (c == '}') { // Finish the last text item: if (i != lastI) { current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); } lastI = i + 1; // See if this brace should be escaped: if (!this.AlternativeEscaping) { var nextI = lastI; if (nextI < length && format[nextI] == '}') { i++; continue; } } // Make sure that this is a nested placeholder before we un-nest it: if (current.parent == null) { parsingErrors.AddIssue(current, "Format string has too many closing braces", i, i + 1); continue; } // End of the placeholder's Format: nestedDepth--; current.endIndex = i; current.parent.endIndex = i + 1; current = current.parent.parent; } else if (this.AlternativeEscaping && c == this.AlternativeEscapeChar) { // See if the next char is a brace that should be escaped: var nextI = i + 1; if (nextI < length && (format[nextI] == '{' || format[nextI] == '}')) { // Finish the last text item: if (i != lastI) { current.Items.Add(new LiteralText(current, lastI) { endIndex = i }); } lastI = i + 1; i++; continue; } } } else { // Placeholder is NOT null, so that means we're parsing the selectors: if (Operators.IndexOf(c) != -1) { // Add the selector: if (i != lastI) { currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); selectorIndex++; operatorIndex = i; } lastI = i + 1; } else if (c == ':') { // Add the selector: if (i != lastI) { currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); } else if (operatorIndex != i) { // There are trailing operators. For now, this is an error. parsingErrors.AddIssue(current, "There are trailing operators in the selector", operatorIndex, i); //var issue = "There are trailing operators in the selector"; //ParserError(format, operatorIndex, issue, result); } lastI = i + 1; // Start the format: currentPlaceholder.Format = new Format(currentPlaceholder, i + 1); current = currentPlaceholder.Format; currentPlaceholder = null; } else if (c == '}') { // Add the selector: if (i != lastI) { currentPlaceholder.Selectors.Add(new Selector(format, lastI, i, operatorIndex, selectorIndex)); } else if (operatorIndex != i) { // There are trailing operators. For now, this is an error. parsingErrors.AddIssue(current, "There are trailing operators in the selector", operatorIndex, i); //ParserError(format, operatorIndex, "There are trailing operators in the selector", result); } lastI = i + 1; // End the placeholder with no format: nestedDepth--; currentPlaceholder.endIndex = i + 1; current = currentPlaceholder.parent; currentPlaceholder = null; } else { // Let's make sure the selector characters are valid: // Make sure it's alphanumeric: if (('0' <= c && c <= '9') || (AlphanumericSelectors && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z')) || (AllowedSelectorChars.IndexOf(c) != -1)) { } else { // Invalid character in the selector. parsingErrors.AddIssue(current, "Invalid character in the selector", i, i + 1); //ParserError(format, i, "Invalid character in the selector", result); } } } } // finish the last text item: if (lastI != format.Length) { current.Items.Add(new LiteralText(current, lastI) { endIndex = format.Length }); } // Check that the format is finished: if (current.parent != null || currentPlaceholder != null) { //ParserError(format, format.Length, "Format string is missing a closing brace", result); parsingErrors.AddIssue(current, "Format string is missing a closing brace", format.Length, format.Length); current.endIndex = format.Length; while (current.parent != null) { current = current.parent.parent; current.endIndex = format.Length; } } // Check if there were any parsing errors: if (parsingErrors.HasIssues && ErrorAction == ErrorAction.ThrowError) { throw parsingErrors; } return(result); }
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions) { string contextName = name; string userName = null; bool explicitCreds = false; if (credentials != null && credentials.UserName != null) { if (credentials.Domain != null) { userName = credentials.Domain + "\\" + credentials.UserName; } else { userName = credentials.UserName; } explicitCreds = true; } else { userName = Utils.GetNT4UserName(); } GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}", name, userName, explicitCreds.ToString(), contextOptions.ToString()); if (!_isSAM) { // Determine the domain DNS name // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY int flags = unchecked ((int)(0x40000000 | 0x00000010 | 0x00000100)); UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags); contextName = info.DomainName; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName); ManualResetEvent contextReadyEvent = null; while (true) { Hashtable credTable = null; PrincipalContext ctx = null; // Wait for the PrincipalContext to be ready if (contextReadyEvent != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting"); contextReadyEvent.WaitOne(); } contextReadyEvent = null; lock (_tableLock) { CredHolder credHolder = (CredHolder)_table[contextName]; if (credHolder != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName); credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); Debug.Assert(credTable != null); object o = credTable[userName]; if (o is Placeholder) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder"); // A PrincipalContext is currently being constructed by another thread. // Wait for it. contextReadyEvent = ((Placeholder)o).contextReadyEvent; continue; } WeakReference refToContext = o as WeakReference; if (refToContext != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null"); ctx = (PrincipalContext)refToContext.Target; // null if GC'ed // If the PrincipalContext hasn't been GCed or disposed, use it. // Otherwise, we'll need to create a new one if (ctx != null && ctx.Disposed == false) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext"); return(ctx); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing"); credTable.Remove(userName); } } } // Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable // are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext. if (credHolder == null) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString()); // No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place // to store the PrincipalContext we'll be creating. credHolder = new CredHolder(); _table[contextName] = credHolder; credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); } // Put a placeholder on the contextName/userName slot, so that other threads that come along after // we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us credTable[userName] = new Placeholder(); } // Now we just need to create a PrincipalContext for the contextName and credentials GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString()); ctx = new PrincipalContext( (_isSAM ? ContextType.Machine : ContextType.Domain), contextName, null, contextOptions, credentials?.UserName, credentials?.Password ); lock (_tableLock) { Placeholder placeHolder = (Placeholder)credTable[userName]; // Replace the placeholder with the newly-created PrincipalContext credTable[userName] = new WeakReference(ctx); // Signal waiting threads to continue. We do this after inserting the PrincipalContext // into the table, so that the PrincipalContext is ready as soon as the other threads wake up. // (Actually, the order probably doesn't matter, since even if we did it in the // opposite order and the other thread woke up before we inserted the PrincipalContext, it would // just block as soon as it tries to acquire the tableLock that we're currently holding.) bool f = placeHolder.contextReadyEvent.Set(); Debug.Assert(f); } return(ctx); } }
public virtual IDictionary <string, object> ToJson() { var options = new Dictionary <string, object>(Events); if (Filter.HasValue()) { options["filter"] = SanitizeSelector(Filter); } if (Disabled.HasValue()) { options["disabled"] = SanitizeSelector(Disabled); } if (Handler.HasValue()) { options["handler"] = SanitizeSelector(Handler); } if (ContainerSelector.HasValue()) { options["container"] = SanitizeSelector(ContainerSelector); } if (ConnectWith.HasValue()) { options["connectWith"] = SanitizeSelector(ConnectWith); } if (HoldToDrag) { options["holdToDrag"] = true; } if (Axis != SortableAxis.None) { options["axis"] = Enum.GetName(typeof(SortableAxis), Axis).ToLowerInvariant(); } if (Cursor.HasValue()) { options["cursor"] = SanitizeSelector(Cursor); } if (CursorOffset.Left != int.MinValue || CursorOffset.Top != int.MinValue) { var topLeft = new Dictionary <string, int>(); if (CursorOffset.Top != int.MinValue) { topLeft.Add("top", CursorOffset.Top); } if (CursorOffset.Left != int.MinValue) { topLeft.Add("left", CursorOffset.Left); } options.Add("cursorOffset", topLeft); } if (HintHandler.HasValue()) { options["hint"] = HintHandler; } else if (Hint.HasValue()) { options["hint"] = Hint; } if (PlaceholderHandler.HasValue()) { options["placeholder"] = PlaceholderHandler; } else if (Placeholder.HasValue()) { options["placeholder"] = Placeholder; } return(options); }
public IslandGeneticAlgorithmMainLoop() : base() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far.")); Parameters.Add(new ValueLookupParameter <IntValue>("NumberOfIslands", "The number of islands.")); Parameters.Add(new ValueLookupParameter <IntValue>("MigrationInterval", "The number of generations that should pass between migration phases.")); Parameters.Add(new ValueLookupParameter <PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands.")); Parameters.Add(new ValueLookupParameter <IOperator>("Migrator", "The migration strategy.")); Parameters.Add(new ValueLookupParameter <IOperator>("EmigrantsSelector", "Selects the individuals that will be migrated.")); Parameters.Add(new ValueLookupParameter <IOperator>("ImmigrationReplacer", "Replaces some of the original population with the immigrants.")); Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population of solutions.")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations that the algorithm should process.")); Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction.")); Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions.")); Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.")); Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions.")); Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions.")); Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation.")); Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)")); Parameters.Add(new ValueLookupParameter <ResultCollection>("Results", "The results collection to store the results.")); Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to the analyze the islands.")); Parameters.Add(new ValueLookupParameter <IOperator>("IslandAnalyzer", "The operator used to analyze each island.")); Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times a solution has been evaluated.")); Parameters.Add(new LookupParameter <IntValue>("IslandGenerations", "The number of generations calculated on one island.")); Parameters.Add(new LookupParameter <IntValue>("IslandEvaluatedSolutions", "The number of times a solution has been evaluated on one island.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Migrate", "Migrate the island?")); #endregion #region Create operators VariableCreator variableCreator = new VariableCreator(); UniformSubScopesProcessor uniformSubScopesProcessor0 = new UniformSubScopesProcessor(); VariableCreator islandVariableCreator = new VariableCreator(); Placeholder islandAnalyzer1 = new Placeholder(); LocalRandomCreator localRandomCreator = new LocalRandomCreator(); Placeholder analyzer1 = new Placeholder(); ResultsCollector resultsCollector1 = new ResultsCollector(); UniformSubScopesProcessor uniformSubScopesProcessor1 = new UniformSubScopesProcessor(); Assigner generationsAssigner = new Assigner(); Assigner evaluatedSolutionsAssigner = new Assigner(); Placeholder selector = new Placeholder(); SubScopesProcessor subScopesProcessor1 = new SubScopesProcessor(); ChildrenCreator childrenCreator = new ChildrenCreator(); UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor(); Placeholder crossover = new Placeholder(); StochasticBranch stochasticBranch = new StochasticBranch(); Placeholder mutator = new Placeholder(); SubScopesRemover subScopesRemover = new SubScopesRemover(); UniformSubScopesProcessor uniformSubScopesProcessor3 = new UniformSubScopesProcessor(); Placeholder evaluator = new Placeholder(); SubScopesCounter subScopesCounter = new SubScopesCounter(); SubScopesProcessor subScopesProcessor2 = new SubScopesProcessor(); BestSelector bestSelector = new BestSelector(); RightReducer rightReducer = new RightReducer(); MergingReducer mergingReducer = new MergingReducer(); IntCounter islandGenerationsCounter = new IntCounter(); Comparator checkIslandGenerationsReachedMaximum = new Comparator(); ConditionalBranch checkContinueEvolution = new ConditionalBranch(); DataReducer generationsReducer = new DataReducer(); DataReducer evaluatedSolutionsReducer = new DataReducer(); Placeholder islandAnalyzer2 = new Placeholder(); UniformSubScopesProcessor uniformSubScopesProcessor5 = new UniformSubScopesProcessor(); Placeholder emigrantsSelector = new Placeholder(); IntCounter migrationsCounter = new IntCounter(); Placeholder migrator = new Placeholder(); UniformSubScopesProcessor uniformSubScopesProcessor6 = new UniformSubScopesProcessor(); Placeholder immigrationReplacer = new Placeholder(); Comparator generationsComparator = new Comparator(); Placeholder analyzer2 = new Placeholder(); ConditionalBranch generationsTerminationCondition = new ConditionalBranch(); ConditionalBranch reevaluateElitesBranch = new ConditionalBranch(); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Migrations", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("GenerationsSinceLastMigration", new IntValue(0))); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class IslandGeneticAlgorithm expects this to be called Generations islandVariableCreator.CollectedValues.Add(new ValueParameter <ResultCollection>("Results", new ResultCollection())); islandVariableCreator.CollectedValues.Add(new ValueParameter <IntValue>("IslandGenerations", new IntValue(0))); islandVariableCreator.CollectedValues.Add(new ValueParameter <IntValue>("IslandEvaluatedSolutions", new IntValue(0))); islandAnalyzer1.Name = "Island Analyzer (placeholder)"; islandAnalyzer1.OperatorParameter.ActualName = IslandAnalyzerParameter.Name; analyzer1.Name = "Analyzer (placeholder)"; analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name; resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Migrations")); resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations")); resultsCollector1.CollectedValues.Add(new ScopeTreeLookupParameter <ResultCollection>("IslandResults", "Result set for each island", "Results")); resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name; uniformSubScopesProcessor1.Parallel.Value = true; generationsAssigner.Name = "Initialize Island Generations"; generationsAssigner.LeftSideParameter.ActualName = IslandGenerations.Name; generationsAssigner.RightSideParameter.Value = new IntValue(0); evaluatedSolutionsAssigner.Name = "Initialize Island evaluated solutions"; evaluatedSolutionsAssigner.LeftSideParameter.ActualName = IslandEvaluatedSolutions.Name; evaluatedSolutionsAssigner.RightSideParameter.Value = new IntValue(0); selector.Name = "Selector (placeholder)"; selector.OperatorParameter.ActualName = SelectorParameter.Name; childrenCreator.ParentsPerChild = new IntValue(2); crossover.Name = "Crossover (placeholder)"; crossover.OperatorParameter.ActualName = CrossoverParameter.Name; stochasticBranch.ProbabilityParameter.ActualName = MutationProbabilityParameter.Name; //set it to the random number generator of the island stochasticBranch.RandomParameter.ActualName = "LocalRandom"; mutator.Name = "Mutator (placeholder)"; mutator.OperatorParameter.ActualName = MutatorParameter.Name; subScopesRemover.RemoveAllSubScopes = true; evaluator.Name = "Evaluator (placeholder)"; evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name; subScopesCounter.Name = "Increment EvaluatedSolutions"; subScopesCounter.ValueParameter.ActualName = IslandEvaluatedSolutions.Name; bestSelector.CopySelected = new BoolValue(false); bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; bestSelector.NumberOfSelectedSubScopesParameter.ActualName = ElitesParameter.Name; bestSelector.QualityParameter.ActualName = QualityParameter.Name; islandGenerationsCounter.Name = "Increment island generatrions"; islandGenerationsCounter.ValueParameter.ActualName = IslandGenerations.Name; islandGenerationsCounter.Increment = new IntValue(1); checkIslandGenerationsReachedMaximum.LeftSideParameter.ActualName = IslandGenerations.Name; checkIslandGenerationsReachedMaximum.RightSideParameter.ActualName = MigrationIntervalParameter.Name; checkIslandGenerationsReachedMaximum.Comparison = new Comparison(ComparisonType.GreaterOrEqual); checkIslandGenerationsReachedMaximum.ResultParameter.ActualName = Migrate.Name; checkContinueEvolution.Name = "Migrate?"; checkContinueEvolution.ConditionParameter.ActualName = Migrate.Name; checkContinueEvolution.FalseBranch = selector; islandAnalyzer2.Name = "Island Analyzer (placeholder)"; islandAnalyzer2.OperatorParameter.ActualName = IslandAnalyzerParameter.Name; generationsReducer.Name = "Increment Generations"; generationsReducer.ParameterToReduce.ActualName = islandGenerationsCounter.ValueParameter.ActualName; generationsReducer.TargetParameter.ActualName = "Generations"; generationsReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Min); generationsReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Sum); evaluatedSolutionsReducer.Name = "Increment Evaluated Solutions"; evaluatedSolutionsReducer.ParameterToReduce.ActualName = IslandEvaluatedSolutions.Name; evaluatedSolutionsReducer.TargetParameter.ActualName = EvaluatedSolutionsParameter.Name; evaluatedSolutionsReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Sum); evaluatedSolutionsReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Sum); emigrantsSelector.Name = "Emigrants Selector (placeholder)"; emigrantsSelector.OperatorParameter.ActualName = EmigrantsSelectorParameter.Name; migrationsCounter.Name = "Increment number of Migrations"; migrationsCounter.ValueParameter.ActualName = "Migrations"; migrationsCounter.Increment = new IntValue(1); migrator.Name = "Migrator (placeholder)"; migrator.OperatorParameter.ActualName = MigratorParameter.Name; immigrationReplacer.Name = "Immigration Replacer (placeholder)"; immigrationReplacer.OperatorParameter.ActualName = ImmigrationReplacerParameter.Name; generationsComparator.Name = "Generations >= MaximumGenerations ?"; generationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual); generationsComparator.LeftSideParameter.ActualName = "Generations"; generationsComparator.ResultParameter.ActualName = "TerminateGenerations"; generationsComparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name; analyzer2.Name = "Analyzer (placeholder)"; analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name; generationsTerminationCondition.Name = "Terminate?"; generationsTerminationCondition.ConditionParameter.ActualName = "TerminateGenerations"; reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites"; reevaluateElitesBranch.Name = "Reevaluate elites ?"; #endregion #region Create operator graph OperatorGraph.InitialOperator = variableCreator; variableCreator.Successor = uniformSubScopesProcessor0; uniformSubScopesProcessor0.Operator = islandVariableCreator; uniformSubScopesProcessor0.Successor = analyzer1; islandVariableCreator.Successor = islandAnalyzer1; // BackwardsCompatibility3.3 //the local randoms are created by the island GA itself and are only here to ensure same algorithm results #region Backwards compatible code, remove local random creator with 3.4 and rewire the operator graph islandAnalyzer1.Successor = localRandomCreator; localRandomCreator.Successor = null; #endregion analyzer1.Successor = resultsCollector1; resultsCollector1.Successor = uniformSubScopesProcessor1; uniformSubScopesProcessor1.Operator = generationsAssigner; uniformSubScopesProcessor1.Successor = generationsReducer; generationsReducer.Successor = evaluatedSolutionsReducer; evaluatedSolutionsReducer.Successor = migrationsCounter; migrationsCounter.Successor = uniformSubScopesProcessor5; generationsAssigner.Successor = evaluatedSolutionsAssigner; evaluatedSolutionsAssigner.Successor = selector; selector.Successor = subScopesProcessor1; subScopesProcessor1.Operators.Add(new EmptyOperator()); subScopesProcessor1.Operators.Add(childrenCreator); subScopesProcessor1.Successor = subScopesProcessor2; childrenCreator.Successor = uniformSubScopesProcessor2; uniformSubScopesProcessor2.Operator = crossover; uniformSubScopesProcessor2.Successor = uniformSubScopesProcessor3; crossover.Successor = stochasticBranch; stochasticBranch.FirstBranch = mutator; stochasticBranch.SecondBranch = null; stochasticBranch.Successor = subScopesRemover; mutator.Successor = null; subScopesRemover.Successor = null; uniformSubScopesProcessor3.Operator = evaluator; uniformSubScopesProcessor3.Successor = subScopesCounter; evaluator.Successor = null; subScopesCounter.Successor = null; subScopesProcessor2.Operators.Add(bestSelector); subScopesProcessor2.Operators.Add(new EmptyOperator()); subScopesProcessor2.Successor = mergingReducer; mergingReducer.Successor = islandAnalyzer2; bestSelector.Successor = rightReducer; rightReducer.Successor = reevaluateElitesBranch; reevaluateElitesBranch.TrueBranch = uniformSubScopesProcessor3; reevaluateElitesBranch.FalseBranch = null; reevaluateElitesBranch.Successor = null; islandAnalyzer2.Successor = islandGenerationsCounter; islandGenerationsCounter.Successor = checkIslandGenerationsReachedMaximum; checkIslandGenerationsReachedMaximum.Successor = checkContinueEvolution; uniformSubScopesProcessor5.Operator = emigrantsSelector; emigrantsSelector.Successor = null; uniformSubScopesProcessor5.Successor = migrator; migrator.Successor = uniformSubScopesProcessor6; uniformSubScopesProcessor6.Operator = immigrationReplacer; uniformSubScopesProcessor6.Successor = generationsComparator; generationsComparator.Successor = analyzer2; analyzer2.Successor = generationsTerminationCondition; generationsTerminationCondition.TrueBranch = null; generationsTerminationCondition.FalseBranch = uniformSubScopesProcessor1; generationsTerminationCondition.Successor = null; #endregion }
/** * Create a <code>TextBox</code> object that represents the slide's title. * * @return <code>TextBox</code> object that represents the slide's title. */ public TextBox AddTitle() { Placeholder pl = new Placeholder(); pl.SetShapeType(ShapeTypes.Rectangle); pl.GetTextRun().SetRunType(TextHeaderAtom.TITLE_TYPE); pl.SetText("Click to edit title"); pl.SetAnchor(new java.awt.Rectangle(54, 48, 612, 90)); AddShape(pl); return pl; }
private void Initialize() { #region Create parameters Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator.")); Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.")); Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution.")); Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far.")); Parameters.Add(new LookupParameter <DoubleValue>("MoveQuality", "The value which represents the quality of a move.")); Parameters.Add(new LookupParameter <BoolValue>("MoveTabu", "The value that indicates if a move is tabu or not.")); Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of generations which should be processed.")); Parameters.Add(new ValueLookupParameter <IntValue>("TabuTenure", "The length of the tabu list, and also means the number of iterations a move is kept tabu")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveGenerator", "The operator that generates the moves.")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveMaker", "The operator that performs a move and updates the quality.")); Parameters.Add(new ValueLookupParameter <IOperator>("MoveEvaluator", "The operator that evaluates a move.")); Parameters.Add(new ValueLookupParameter <IOperator>("TabuChecker", "The operator that checks whether a move is tabu.")); Parameters.Add(new ValueLookupParameter <IOperator>("TabuMaker", "The operator that declares a move tabu.")); Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze the solution and moves.")); Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored.")); Parameters.Add(new LookupParameter <IntValue>("EvaluatedMoves", "The number of evaluated moves.")); #endregion #region Create operators VariableCreator variableCreator = new VariableCreator(); SubScopesProcessor subScopesProcessor0 = new SubScopesProcessor(); Assigner bestQualityInitializer = new Assigner(); Placeholder analyzer1 = new Placeholder(); ResultsCollector resultsCollector1 = new ResultsCollector(); SubScopesProcessor solutionProcessor = new SubScopesProcessor(); Placeholder moveGenerator = new Placeholder(); UniformSubScopesProcessor moveEvaluationProcessor = new UniformSubScopesProcessor(); Placeholder moveEvaluator = new Placeholder(); Placeholder tabuChecker = new Placeholder(); SubScopesCounter subScopesCounter = new SubScopesCounter(); SubScopesSorter moveQualitySorter = new SubScopesSorter(); TabuSelector tabuSelector = new TabuSelector(); ConditionalBranch emptyNeighborhoodBranch1 = new ConditionalBranch(); SubScopesProcessor moveMakingProcessor = new SubScopesProcessor(); UniformSubScopesProcessor selectedMoveMakingProcesor = new UniformSubScopesProcessor(); Placeholder tabuMaker = new Placeholder(); Placeholder moveMaker = new Placeholder(); MergingReducer mergingReducer = new MergingReducer(); Placeholder analyzer2 = new Placeholder(); SubScopesRemover subScopesRemover = new SubScopesRemover(); ConditionalBranch emptyNeighborhoodBranch2 = new ConditionalBranch(); BestQualityMemorizer bestQualityUpdater = new BestQualityMemorizer(); IntCounter iterationsCounter = new IntCounter(); Comparator iterationsComparator = new Comparator(); ConditionalBranch iterationsTermination = new ConditionalBranch(); variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0))); // Class TabuSearch expects this to be called Iterations variableCreator.CollectedValues.Add(new ValueParameter <BoolValue>("EmptyNeighborhood", new BoolValue(false))); variableCreator.CollectedValues.Add(new ValueParameter <ItemList <IItem> >("TabuList", new ItemList <IItem>())); variableCreator.CollectedValues.Add(new ValueParameter <VariableCollection>("Memories", new VariableCollection())); variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("BestQuality", new DoubleValue(0))); bestQualityInitializer.Name = "Initialize BestQuality"; bestQualityInitializer.LeftSideParameter.ActualName = "BestQuality"; bestQualityInitializer.RightSideParameter.ActualName = QualityParameter.Name; analyzer1.Name = "Analyzer (placeholder)"; analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name; resultsCollector1.CopyValue = new BoolValue(false); resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Iterations")); resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Best Quality", null, "BestQuality")); resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name; moveGenerator.Name = "MoveGenerator (placeholder)"; moveGenerator.OperatorParameter.ActualName = MoveGeneratorParameter.Name; moveEvaluationProcessor.Parallel = new BoolValue(true); moveEvaluator.Name = "MoveEvaluator (placeholder)"; moveEvaluator.OperatorParameter.ActualName = MoveEvaluatorParameter.Name; tabuChecker.Name = "TabuChecker (placeholder)"; tabuChecker.OperatorParameter.ActualName = TabuCheckerParameter.Name; subScopesCounter.Name = "Increment EvaluatedMoves"; subScopesCounter.ValueParameter.ActualName = EvaluatedMovesParameter.Name; moveQualitySorter.DescendingParameter.ActualName = MaximizationParameter.Name; moveQualitySorter.ValueParameter.ActualName = MoveQualityParameter.Name; tabuSelector.AspirationParameter.Value = new BoolValue(true); tabuSelector.BestQualityParameter.ActualName = "BestQuality"; tabuSelector.CopySelected = new BoolValue(false); tabuSelector.EmptyNeighborhoodParameter.ActualName = "EmptyNeighborhood"; tabuSelector.MaximizationParameter.ActualName = MaximizationParameter.Name; tabuSelector.MoveQualityParameter.ActualName = MoveQualityParameter.Name; tabuSelector.MoveTabuParameter.ActualName = MoveTabuParameter.Name; moveMakingProcessor.Name = "MoveMaking processor (UniformSubScopesProcessor)"; emptyNeighborhoodBranch1.Name = "Neighborhood empty?"; emptyNeighborhoodBranch1.ConditionParameter.ActualName = "EmptyNeighborhood"; tabuMaker.Name = "TabuMaker (placeholder)"; tabuMaker.OperatorParameter.ActualName = TabuMakerParameter.Name; moveMaker.Name = "MoveMaker (placeholder)"; moveMaker.OperatorParameter.ActualName = MoveMakerParameter.Name; analyzer2.Name = "Analyzer (placeholder)"; analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name; subScopesRemover.RemoveAllSubScopes = true; bestQualityUpdater.Name = "Update BestQuality"; bestQualityUpdater.MaximizationParameter.ActualName = MaximizationParameter.Name; bestQualityUpdater.QualityParameter.ActualName = QualityParameter.Name; bestQualityUpdater.BestQualityParameter.ActualName = "BestQuality"; iterationsCounter.Name = "Iterations Counter"; iterationsCounter.Increment = new IntValue(1); iterationsCounter.ValueParameter.ActualName = "Iterations"; iterationsComparator.Name = "Iterations >= MaximumIterations"; iterationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual); iterationsComparator.LeftSideParameter.ActualName = "Iterations"; iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name; iterationsComparator.ResultParameter.ActualName = "Terminate"; emptyNeighborhoodBranch2.Name = "Neighborhood empty?"; emptyNeighborhoodBranch2.ConditionParameter.ActualName = "EmptyNeighborhood"; iterationsTermination.Name = "Iterations Termination Condition"; iterationsTermination.ConditionParameter.ActualName = "Terminate"; #endregion #region Create operator graph OperatorGraph.InitialOperator = variableCreator; variableCreator.Successor = subScopesProcessor0; subScopesProcessor0.Operators.Add(bestQualityInitializer); subScopesProcessor0.Successor = resultsCollector1; bestQualityInitializer.Successor = analyzer1; analyzer1.Successor = null; resultsCollector1.Successor = solutionProcessor; solutionProcessor.Operators.Add(moveGenerator); solutionProcessor.Successor = iterationsCounter; moveGenerator.Successor = moveEvaluationProcessor; moveEvaluationProcessor.Operator = moveEvaluator; moveEvaluationProcessor.Successor = subScopesCounter; moveEvaluator.Successor = tabuChecker; tabuChecker.Successor = null; subScopesCounter.Successor = moveQualitySorter; moveQualitySorter.Successor = tabuSelector; tabuSelector.Successor = emptyNeighborhoodBranch1; emptyNeighborhoodBranch1.FalseBranch = moveMakingProcessor; emptyNeighborhoodBranch1.TrueBranch = null; emptyNeighborhoodBranch1.Successor = subScopesRemover; moveMakingProcessor.Operators.Add(new EmptyOperator()); moveMakingProcessor.Operators.Add(selectedMoveMakingProcesor); moveMakingProcessor.Successor = mergingReducer; selectedMoveMakingProcesor.Operator = tabuMaker; selectedMoveMakingProcesor.Successor = null; tabuMaker.Successor = moveMaker; moveMaker.Successor = null; mergingReducer.Successor = analyzer2; analyzer2.Successor = null; subScopesRemover.Successor = null; iterationsCounter.Successor = iterationsComparator; iterationsComparator.Successor = emptyNeighborhoodBranch2; emptyNeighborhoodBranch2.TrueBranch = null; emptyNeighborhoodBranch2.FalseBranch = iterationsTermination; emptyNeighborhoodBranch2.Successor = null; iterationsTermination.TrueBranch = null; iterationsTermination.FalseBranch = solutionProcessor; #endregion }
public void Initialize(string gameId, bool testMode, bool enablePerPlacementLoad) { if (m_StartedInitialization) { return; } m_StartedInitialization = true; m_LoadEnabled = enablePerPlacementLoad; m_GameId = gameId; if (m_Platform.DebugMode) { Debug.Log("UnityAdsEditor: Initialize(" + gameId + ", " + testMode + ", " + enablePerPlacementLoad + ");"); } #if ASSET_STORE Debug.LogWarning("Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3"); #endif var placeHolderGameObject = new GameObject("UnityAdsEditorPlaceHolderObject") { hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector }; GameObject.DontDestroyOnLoad(placeHolderGameObject); m_Placeholder = placeHolderGameObject.AddComponent <Placeholder>(); m_Placeholder.OnFinish += (sender, e) => { m_Platform.UnityAdsDidFinish(e.placementId, e.showResult); if (!m_LoadEnabled) { m_Platform.UnityLifecycleManager.Post(() => { var placementIds = new List <string>(m_PlacementMap.Keys); foreach (var placementId in placementIds) { foreach (var listener in GetClonedHashSet(m_Platform.Listeners)) { listener?.OnUnityAdsReady(placementId); } } }); } }; var configurationUrl = string.Join("/", new string[] { k_BaseUrl, gameId, string.Join("&", new string[] { "configuration?platform=editor", "unityVersion=" + Uri.EscapeDataString(Application.unityVersion), "sdkVersionName=" + Uri.EscapeDataString(m_Platform.Version) }) }); var request = WebRequest.Create(configurationUrl); request.BeginGetResponse(result => { try { var response = request.EndGetResponse(result); var reader = new StreamReader(response.GetResponseStream() ?? throw new Exception("Null response stream fetching configuration")); var responseBody = reader.ReadToEnd(); try { m_Configuration = new Configuration(responseBody); if (!m_Configuration.enabled) { Debug.LogWarning("gameId " + gameId + " is not enabled"); } m_Initialized = true; foreach (var placement in m_Configuration.placements) { if (m_LoadEnabled) { m_PlacementMap.Add(placement.Key, false); foreach (var queuedPlacementId in m_QueuedLoads) { Load(queuedPlacementId); } } else { m_PlacementMap.Add(placement.Key, true); m_Platform.UnityAdsReady(placement.Key); } } } catch (Exception exception) { Debug.LogError("Failed to parse configuration for gameId: " + gameId); Debug.Log(responseBody); Debug.LogError(exception.Message); m_Platform.UnityAdsDidError("Failed to parse configuration for gameId: " + gameId); } reader.Close(); response.Close(); } catch (Exception exception) { Debug.LogError("Invalid configuration request for gameId: " + gameId); Debug.LogError(exception.Message); m_Platform.UnityAdsDidError("Failed to parse configuration for gameId: " + gameId); } }, new object()); }
private void Activate(RealmTime time, Item item, Position target) { MP -= item.MpCost; foreach (var eff in item.ActivateEffects) { switch (eff.Effect) { case ActivateEffects.BulletNova: { var prjDesc = item.Projectiles[0]; //Assume only one var batch = new Packet[21]; var s = Random.CurrentSeed; Random.CurrentSeed = (uint)(s * time.tickTimes); for (var i = 0; i < 20; i++) { var proj = CreateProjectile(prjDesc, item.ObjectType, (int)statsMgr.GetAttackDamage(prjDesc.MinDamage, prjDesc.MaxDamage), time.tickTimes, target, (float)(i * (Math.PI * 2) / 20)); Owner.EnterWorld(proj); fames.Shoot(proj); batch[i] = new ShootPacket { BulletId = proj.ProjectileId, OwnerId = Id, ContainerType = item.ObjectType, Position = target, Angle = proj.Angle, Damage = (short)proj.Damage }; } Random.CurrentSeed = s; batch[20] = new ShowEffectPacket { EffectType = EffectType.Trail, PosA = target, TargetId = Id, Color = new ARGB(0xFFFF00AA) }; Owner.BroadcastPackets(batch, null); } break; case ActivateEffects.Shoot: { ActivateShoot(time, item, target); } break; case ActivateEffects.StatBoostSelf: { var idx = -1; switch ((StatsType)eff.Stats) { case StatsType.MaximumHP: idx = 0; break; case StatsType.MaximumMP: idx = 1; break; case StatsType.Attack: idx = 2; break; case StatsType.Defense: idx = 3; break; case StatsType.Speed: idx = 4; break; case StatsType.Vitality: idx = 5; break; case StatsType.Wisdom: idx = 6; break; case StatsType.Dexterity: idx = 7; break; } var pkts = new List<Packet>(); ActivateBoostStat(this, idx, pkts); var OGstat = oldstat; var s = eff.Amount; Boost[idx] += s; UpdateCount++; Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { Boost[idx] = OGstat; UpdateCount++; })); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Potion, TargetId = Id, Color = new ARGB(0xffffffff) }, null); } break; case ActivateEffects.StatBoostAura: { var idx = -1; switch ((StatsType)eff.Stats) { case StatsType.MaximumHP: idx = 0; break; case StatsType.MaximumMP: idx = 1; break; case StatsType.Attack: idx = 2; break; case StatsType.Defense: idx = 3; break; case StatsType.Speed: idx = 4; break; case StatsType.Vitality: idx = 5; break; case StatsType.Wisdom: idx = 6; break; case StatsType.Dexterity: idx = 7; break; } var s = eff.Amount; BehaviorBase.AOE(Owner, this, eff.Range, true, player => { (player as Player).Boost[idx] += s; player.UpdateCount++; Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { (player as Player).Boost[idx] -= s; player.UpdateCount++; })); }); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range } }, null); } break; case ActivateEffects.ConditionEffectSelf: { ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = eff.DurationMS }); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = 1 } }, null); } break; case ActivateEffects.Tag: { //Add Tag to DB using (Database db = new Database()) { var db1 = db.CreateQuery(); db1.CommandText = "SELECT tags FROM accounts WHERE id=@id;"; db1.Parameters.AddWithValue("@id", psr.Account.AccountId); db1.ExecuteScalar(); db1.Parameters.AddWithValue("@tags", item.ObjectId); db1.CommandText = "UPDATE accounts SET tags=@tags"; db1.ExecuteNonQuery(); UpdateCount++; } } break; case ActivateEffects.ConditionEffectAura: { BehaviorBase.AOE(Owner, this, eff.Range, true, player => { player.ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = eff.DurationMS }); }); var color = 0xffffffff; if (eff.ConditionEffect.Value == ConditionEffectIndex.Damaging) color = 0xffff0000; Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(color), PosA = new Position { X = eff.Range } }, null); } break; case ActivateEffects.Heal: { var pkts = new List<Packet>(); ActivateHealHp(this, eff.Amount, pkts); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.HealNova: { var pkts = new List<Packet>(); BehaviorBase.AOE(Owner, this, eff.Range, true, player => { ActivateHealHp(player as Player, eff.Amount, pkts); }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range } }); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Magic: { var pkts = new List<Packet>(); ActivateHealMp(this, eff.Amount, pkts); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.MagicNova: { var pkts = new List<Packet>(); BehaviorBase.AOE(Owner, this, eff.Range, true, player => { ActivateHealMp(player as Player, eff.Amount, pkts); }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range } }); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Teleport: { Move(target.X, target.Y); UpdateCount++; Owner.BroadcastPackets(new Packet[] { new GotoPacket { ObjectId = Id, Position = new Position { X = X, Y = Y } }, new ShowEffectPacket { EffectType = EffectType.Teleport, TargetId = Id, PosA = new Position { X = X, Y = Y }, Color = new ARGB(0xFFFFFFFF) } }, null); } break; case ActivateEffects.VampireBlast: { var pkts = new List<Packet>(); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Trail, TargetId = Id, PosA = target, Color = new ARGB(0xFFFF0000) }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Diffuse, Color = new ARGB(0xFFFF0000), TargetId = Id, PosA = target, PosB = new Position { X = target.X + eff.Radius, Y = target.Y } }); var totalDmg = 0; var enemies = new List<Enemy>(); BehaviorBase.AOE(Owner, target, eff.Radius, false, enemy => { enemies.Add(enemy as Enemy); totalDmg += (enemy as Enemy).Damage(this, time, eff.TotalDamage, false); }); var players = new List<Player>(); BehaviorBase.AOE(Owner, this, eff.Radius, true, player => { players.Add(player as Player); ActivateHealHp(player as Player, totalDmg, pkts); }); var rand = new Random(); for (var i = 0; i < 5; i++) { var a = enemies[rand.Next(0, enemies.Count)]; var b = players[rand.Next(0, players.Count)]; pkts.Add(new ShowEffectPacket { EffectType = EffectType.Flow, TargetId = b.Id, PosA = new Position { X = a.X, Y = a.Y }, Color = new ARGB(0xffffffff) }); } if (enemies.Count > 0) { var a = enemies[rand.Next(0, enemies.Count)]; var b = players[rand.Next(0, players.Count)]; pkts.Add(new ShowEffectPacket { EffectType = EffectType.Flow, TargetId = b.Id, PosA = new Position { X = a.X, Y = a.Y }, Color = new ARGB(0Xffffffff) }); } Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Trap: { var effColor = new ARGB(0xff9000ff); if (eff.Color != null) effColor = new ARGB((uint)eff.Color); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Throw, Color = effColor, TargetId = Id, PosA = target }, null); Owner.Timers.Add(new WorldTimer(1500, (world, t) => { var trap = new Trap( this, eff.Radius, eff.TotalDamage, eff.ConditionEffect ?? ConditionEffectIndex.Slowed, eff.EffectDuration); trap.Move(target.X, target.Y); world.EnterWorld(trap); })); } break; case ActivateEffects.StasisBlast: { var pkts = new List<Packet>(); var effColor = new ARGB(0xffffffff); if (eff.Color != null) effColor = new ARGB((uint)eff.Color); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Concentrate, TargetId = Id, PosA = target, PosB = new Position { X = target.X + 3, Y = target.Y }, Color = effColor }); BehaviorBase.AOE(Owner, target, 3, false, enemy => { if (enemy.HasConditionEffect(ConditionEffects.StasisImmune)) { pkts.Add(new NotificationPacket { ObjectId = enemy.Id, Color = new ARGB(0xff00ff00), Text = "Immune" }); } else if (enemy.isPet) { } else if (!enemy.HasConditionEffect(ConditionEffects.Stasis)) { enemy.ApplyConditionEffect( new ConditionEffect { Effect = ConditionEffectIndex.Stasis, DurationMS = eff.DurationMS }, new ConditionEffect { Effect = ConditionEffectIndex.Confused, DurationMS = eff.DurationMS } ); Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { enemy.ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.StasisImmune, DurationMS = 3000 } ); } )); pkts.Add(new NotificationPacket { ObjectId = enemy.Id, Color = new ARGB(0xffff0000), Text = "Stasis" }); } }); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Decoy: { var decoy = new Decoy(this, eff.DurationMS, statsMgr.GetSpeed()); decoy.Move(X, Y); Owner.EnterWorld(decoy); } break; case ActivateEffects.MultiDecoy: { for (var i = 0; i < eff.Amount; i++) { var decoy = Decoy.DecoyRandom(this, eff.DurationMS, statsMgr.GetSpeed()); decoy.Move(X, Y); Owner.EnterWorld(decoy); } } break; case ActivateEffects.Lightning: { Enemy start = null; var angle = Math.Atan2(target.Y - Y, target.X - X); var diff = Math.PI / 3; BehaviorBase.AOE(Owner, target, 6, false, enemy => { if (!(enemy is Enemy)) return; var x = Math.Atan2(enemy.Y - Y, enemy.X - X); if (Math.Abs(angle - x) < diff) { start = enemy as Enemy; diff = Math.Abs(angle - x); } }); if (start == null) break; var current = start; var targets = new Enemy[eff.MaxTargets]; for (var i = 0; i < targets.Length; i++) { targets[i] = current; float dist = 8; var next = BehaviorBase.GetNearestEntity(current, ref dist, false, enemy => enemy is Enemy && Array.IndexOf(targets, enemy) == -1 && BehaviorBase.Dist(this, enemy) <= 6) as Enemy; if (next == null) break; current = next; } var pkts = new List<Packet>(); for (var i = 0; i < targets.Length; i++) { if (targets[i] == null) break; var prev = i == 0 ? (Entity)this : targets[i - 1]; targets[i].Damage(this, time, eff.TotalDamage, false); if (eff.ConditionEffect != null) targets[i].ApplyConditionEffect(new ConditionEffect { Effect = eff.ConditionEffect.Value, DurationMS = (int)(eff.EffectDuration * 1000) }); var shotColor = new ARGB(0xffff0088); if (eff.Color != null) shotColor = new ARGB((uint)eff.Color); pkts.Add(new ShowEffectPacket { EffectType = EffectType.Lightning, TargetId = prev.Id, Color = shotColor, PosA = new Position { X = targets[i].X, Y = targets[i].Y }, PosB = new Position { X = 350 } }); } Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.PoisonGrenade: { try { Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Throw, Color = new ARGB(0xffddff00), TargetId = Id, PosA = target }, null); var x = new Placeholder(1500); x.Move(target.X, target.Y); Owner.EnterWorld(x); Owner.Timers.Add(new WorldTimer(1500, (world, t) => { try { Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, Color = new ARGB(0xffddff00), TargetId = x.Id, PosA = new Position { X = eff.Radius } }, null); } catch { Console.ForegroundColor = ConsoleColor.DarkRed; Console.Out.WriteLine("Crash halted - Nobody likes death..."); Console.ForegroundColor = ConsoleColor.White; } var enemies = new List<Enemy>(); BehaviorBase.AOE(world, target, eff.Radius, false, enemy => PoisonEnemy(enemy as Enemy, eff)); })); } catch { Console.ForegroundColor = ConsoleColor.DarkBlue; Console.Out.WriteLine("Crash halted - Poison grenade??"); Console.ForegroundColor = ConsoleColor.White; } } break; case ActivateEffects.RemoveNegativeConditions: { BehaviorBase.AOE(Owner, this, eff.Range, true, player => { ApplyConditionEffect(NegativeEffs); }); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = eff.Range } }, null); } break; case ActivateEffects.RemoveNegativeConditionsSelf: { ApplyConditionEffect(NegativeEffs); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xffffffff), PosA = new Position { X = 1 } }, null); } break; case ActivateEffects.IncrementStat: { var idx = -1; switch ((StatsType)eff.Stats) { case StatsType.MaximumHP: idx = 0; break; case StatsType.MaximumMP: idx = 1; break; case StatsType.Attack: idx = 2; break; case StatsType.Defense: idx = 3; break; case StatsType.Speed: idx = 4; break; case StatsType.Vitality: idx = 5; break; case StatsType.Wisdom: idx = 6; break; case StatsType.Dexterity: idx = 7; break; } Stats[idx] += eff.Amount; var limit = int.Parse( XmlDatas.TypeToElement[ObjectType].Element(StatsManager.StatsIndexToName(idx)) .Attribute("max") .Value); if (Stats[idx] > limit) Stats[idx] = limit; UpdateCount++; } break; case ActivateEffects.Create: //this is a portal { short objType; if (!XmlDatas.IdToType.TryGetValue(eff.Id, out objType) || !XmlDatas.PortalDescs.ContainsKey(objType)) break; // object not found, ignore var entity = Resolve(objType); var w = RealmManager.GetWorld(Owner.Id); //can't use Owner here, as it goes out of scope var TimeoutTime = XmlDatas.PortalDescs[objType].TimeoutTime; var DungName = XmlDatas.PortalDescs[objType].DungeonName; ARGB c; c.A = 0; c.B = 91; c.R = 233; c.G = 176; if (eff.Id == "Wine Cellar Portal") //wine cellar incantation { var opened = false; foreach (var i in w.StaticObjects) { if (i.Value.ObjectType == 0x0721) //locked wine cellar portal { opened = true; entity.Move(i.Value.X, i.Value.Y); w.EnterWorld(entity); w.LeaveWorld(i.Value); UpdateCount++; } } if (opened) { psr.SendPacket(new NotificationPacket { Color = c, Text = DungName + " opened by " + psr.Account.Name, ObjectId = psr.Player.Id }); w.BroadcastPacket(new TextPacket { BubbleTime = 0, Stars = -1, Name = "", Text = DungName + " opened by " + psr.Account.Name }, null); w.Timers.Add(new WorldTimer(TimeoutTime * 1000, (world, t) => //default portal close time * 1000 { try { w.LeaveWorld(entity); } catch //couldn't remove portal, Owner became null. Should be fixed with RealmManager implementation { Console.WriteLine(@"Couldn't despawn portal."); } })); } } else { entity.Move(X, Y); w.EnterWorld(entity); psr.SendPacket(new NotificationPacket { Color = c, Text = DungName + " opened by " + psr.Account.Name, ObjectId = psr.Player.Id }); w.BroadcastPacket(new TextPacket { BubbleTime = 0, Stars = -1, Name = "", Text = DungName + " opened by " + psr.Account.Name }, null); w.Timers.Add(new WorldTimer(TimeoutTime * 1000, (world, t) => //default portal close time * 1000 { try { w.LeaveWorld(entity); } catch //couldn't remove portal, Owner became null. Should be fixed with RealmManager implementation { Console.WriteLine(@"Couldn't despawn portal."); } })); } } break; case ActivateEffects.Dye: { if (item.Texture1 != 0) { Texture1 = item.Texture1; } if (item.Texture2 != 0) { Texture2 = item.Texture2; } SaveToCharacter(); } break; case ActivateEffects.PartyAOE: { var randomnumber = Random.Next(1, 5); ConditionEffectIndex partyeffect = 0; var color = 0xffffffff; if (randomnumber == 1) { partyeffect = ConditionEffectIndex.Damaging; color = 0xffff0000; } if (randomnumber == 2) { color = 0xff00ff00; partyeffect = ConditionEffectIndex.Speedy; } if (randomnumber == 3) { color = 0xffffd800; partyeffect = ConditionEffectIndex.Berserk; } if (randomnumber == 4) { color = 0xff00ffff; partyeffect = ConditionEffectIndex.Healing; } BehaviorBase.AOE(Owner, this, eff.Range, true, player => { player.ApplyConditionEffect(new ConditionEffect { Effect = partyeffect, DurationMS = eff.DurationMS }); }); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(color), PosA = new Position { X = eff.Range } }, null); } break; case ActivateEffects.ShurikenAbility: { var w = RealmManager.GetWorld(Owner.Id); ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.Speedy, DurationMS = eff.DurationMS }); var pt = eff.ObjectId; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var substitute = Resolve(obj); substitute.PlayerOwner = this; substitute.isPet = true; w.EnterWorld(substitute); substitute.Move(X, Y); targetlink = target; } break; case ActivateEffects.TomeDamage: { var pkts = new List<Packet>(); BehaviorBase.AOE(Owner, this, eff.Range, false, enemy => { (enemy as Enemy).Damage(this, time, (int)statsMgr.GetAttackDamage(eff.TotalDamage, eff.TotalDamage), false, new ConditionEffect[0]); }); pkts.Add(new ShowEffectPacket { EffectType = EffectType.AreaBlast, TargetId = Id, Color = new ARGB(0xFF00FF00), PosA = new Position { X = eff.Range } }); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.Mushroom: { var w = RealmManager.GetWorld(Owner.Id); Size = eff.Amount; UpdateCount++; w.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { try { Size = 100; UpdateCount++; } catch { } })); } break; case ActivateEffects.PearlAbility: { var w = RealmManager.GetWorld(Owner.Id); var pt = eff.ObjectId; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var substitute = Resolve(obj); substitute.PlayerOwner = this; substitute.isPet = true; w.EnterWorld(substitute); substitute.Move(X, Y); targetlink = target; var pkts = new List<Packet>(); ActivateHealHp(this, eff.Amount, pkts); Owner.BroadcastPackets(pkts, null); } break; case ActivateEffects.PermaPet: { psr.Character.Pet = XmlDatas.IdToType[eff.ObjectId]; GivePet(XmlDatas.IdToType[eff.ObjectId]); UpdateCount++; } break; case ActivateEffects.MiniPot: { Client.Player.Stats[1] = 1; Client.Player.Stats[0] = 1; Client.Player.Stats[6] = 1; Client.Player.Stats[7] = 1; Client.Player.Stats[2] = 1; Client.Player.Stats[3] = 1; Client.Player.Stats[5] = 1; Client.Player.Stats[4] = 1; } break; case ActivateEffects.Backpack: { var bps = 1; foreach (var i in psr.Character.Backpacks) { if (bps < i.Key) bps = i.Key; } psr.Character.Backpacks.Add(bps + 1, new short[] { -1, -1, -1, -1, -1, -1, -1, -1 }); new Database().SaveBackpacks(psr.Character, psr.Account); SendInfo("Added backpack #" + (bps + 1)); } break; case ActivateEffects.Drake: { var w = RealmManager.GetWorld(Owner.Id); var pt = eff.ObjectId; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var drake = Resolve(obj); drake.PlayerOwner = this; w.EnterWorld(drake); drake.Move(X, Y); Owner.BroadcastPacket(new ShowEffectPacket { TargetId = Id, Color = new ARGB(0x9195A9), EffectType = EffectType.AreaBlast, PosA = new Position { X = 1 } }, null); Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { w.LeaveWorld(drake); })); } break; case ActivateEffects.BuildTower: { var w = RealmManager.GetWorld(Owner.Id); var pt = eff.ObjectId; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var tower = Resolve(obj); tower.PlayerOwner = this; tower.isPet = true; w.EnterWorld(tower); tower.Move(X, Y); Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { w.LeaveWorld(tower); })); } break; case ActivateEffects.MonsterToss: { var w = RealmManager.GetWorld(Owner.Id); var pt = eff.ObjectId; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var monster = Resolve(obj); Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Throw, Color = new ARGB(0x000000), TargetId = Id, PosA = target }, null); Owner.Timers.Add(new WorldTimer(1500, (world, t) => { w.EnterWorld(monster); monster.Move(target.X, target.Y); })); } break; case ActivateEffects.Halo: { var halo = new Halo(this, eff.Range, eff.Amount, eff.DurationMS); halo.Move(X, Y); Owner.EnterWorld(halo); } break; case ActivateEffects.Fame: { CurrentFame = psr.Account.Stats.Fame = new Database().UpdateFame(psr.Account, eff.Amount); } break; case ActivateEffects.SamuraiAbility: { var ydist = target.Y - Y; var xdist = target.X - X; var xwalkable = target.X + xdist / 2; var ywalkable = target.Y + ydist / 2; var tile = Owner.Map[(int)xwalkable, (int)ywalkable]; ObjectDesc desc; if (XmlDatas.TileDescs[tile.TileId].NoWalk) return; if (XmlDatas.ObjectDescs.TryGetValue(tile.ObjType, out desc)) { if (!desc.Static) return; } Owner.BroadcastPacket(new ShowEffectPacket { EffectType = EffectType.Diffuse, Color = new ARGB(0xFFFF0000), TargetId = Id, PosA = target, PosB = new Position { X = target.X + eff.Radius, Y = target.Y } }, null); BehaviorBase.AOE(Owner, target, eff.Radius, false, enemy => { (enemy as Enemy).Damage(this, time, eff.TotalDamage, false, new ConditionEffect { Effect = ConditionEffectIndex.Bleeding, DurationMS = eff.DurationMS }); }); Move(target.X + xdist / 2, target.Y + ydist / 2); UpdateCount++; Owner.BroadcastPackets(new Packet[] { new GotoPacket { ObjectId = Id, Position = new Position { X = X, Y = Y } }, new ShowEffectPacket { EffectType = EffectType.Teleport, TargetId = Id, PosA = new Position { X = X, Y = Y }, Color = new ARGB(0xFFFFFFFF) } }, null); ApplyConditionEffect(new ConditionEffect { Effect = ConditionEffectIndex.Paralyzed, DurationMS = eff.DurationMS2 }); } break; case ActivateEffects.Summon: { var w = RealmManager.GetWorld(Owner.Id); var pt = eff.ObjectId + " Summon"; short obj; XmlDatas.IdToType.TryGetValue(pt, out obj); var summon = Resolve(obj); summon.PlayerOwner = this; summon.isPet = true; w.EnterWorld(summon); summon.Move(X, Y); Owner.Timers.Add(new WorldTimer(eff.DurationMS, (world, t) => { w.LeaveWorld(summon); })); } break; } } UpdateCount++; }
public void testIsKeyword() { object pair = new Placeholder(); Assert.IsTrue(pair is Placeholder); }