public void ResultsInCorrectCountsWithPredicate() { // Given Engine engine = new Engine(); engine.CleanOutputPathOnExecute = false; CountModule a = new CountModule("A") { AdditionalOutputs = 1 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new Branch(b).Where((x, y) => x.Content == "1"), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(1, b.InputCount); Assert.AreEqual(2, c.InputCount); Assert.AreEqual(2, a.OutputCount); Assert.AreEqual(3, b.OutputCount); Assert.AreEqual(8, c.OutputCount); }
public void SitemapGeneratedWithSitemapItem(string hostname, string formatterString, string expected) { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); if (!string.IsNullOrWhiteSpace(hostname)) engine.Metadata[Keys.Hostname] = hostname; Pipeline contentPipeline = new Pipeline("Content", engine, null); var doc = new Document(engine, contentPipeline).Clone("Test", new[] { new KeyValuePair<string, object>(Keys.RelativeFilePath, "sub/testfile.html") }); IDocument[] inputs = { doc }; IExecutionContext context = new ExecutionContext(engine, contentPipeline); Core.Modules.Metadata.Meta m = new Core.Modules.Metadata.Meta(Keys.SitemapItem, (d, c) => new SitemapItem(d[Keys.RelativeFilePath].ToString())); var outputs = m.Execute(inputs, context); Func<string, string> formatter = null; if (!string.IsNullOrWhiteSpace(formatterString)) formatter = f => string.Format(formatterString, f); // When Sitemap sitemap = new Sitemap(formatter); List<IDocument> results = sitemap.Execute(outputs.ToList(), context).ToList(); foreach (IDocument document in inputs.Concat(outputs.ToList())) { ((IDisposable)document).Dispose(); } // Then Assert.AreEqual(1, results.Count); Assert.That(results[0].Content, Does.Contain($"<loc>{expected}</loc>")); }
private object CallFunction(object child, string function, object[] args, Engine engine) { engine.SetContext(null); if (Script != null) engine.ExecuteScript(Script, CodeTree); Functions.Execute(engine); return engine.CallFunction(function, args); }
public BgColorChangeMaterial(Engine engine, Material baseMaterial) : base(engine, baseMaterial) { Navin = BgColorChangeParameter.None; foreach (var param in baseMaterial.TextureParameters) { var tex = baseMaterial.TexturesFiles[param.TextureIndex]; BgColorChangeParameter currentParam; if (!CharacterParameterMap.TryGetValue(param.ParameterId, out currentParam)) { System.Diagnostics.Trace.WriteLine(string.Format("Unknown character parameter {0:X8} for texture '{1}' in material '{2}'.", param.ParameterId, tex.Path, baseMaterial.File.Path)); continue; } Navin |= currentParam; switch (currentParam) { case BgColorChangeParameter.ColorMap0: ColorMap0 = Engine.TextureFactory.GetResource(tex); break; case BgColorChangeParameter.SpecularMap0: SpecularMap0 = Engine.TextureFactory.GetResource(tex); break; case BgColorChangeParameter.NormalMap0: NormalMap0 = Engine.TextureFactory.GetResource(tex); break; } } CurrentTechniqueName = "BgColorChange"; // TechniqueNames[Navin]; }
public void Transform(Engine engine, Package package) { TemplatingLogger log = TemplatingLogger.GetLogger(GetType()); RepositoryLocalObject context; if (package.GetByName(Package.PageName) != null) { context = (RepositoryLocalObject)engine.GetObject(package.GetByName(Package.PageName)); log.Debug("Setting context to page with ID " + context.Id); } else { log.Info("This template building block should only run on a page. Exiting."); return; } if (!(context is Page)) return; Page page = (Page)context; package.PushItem(SiteEditPageContext, package.CreateStringItem(ContentType.Text, page.OwningRepository.Id)); package.PushItem(SiteEditPublishContext, package.CreateStringItem(ContentType.Text, page.ContextRepository.Id)); if (page.ComponentPresentations.Count <= 0) return; Component component = page.ComponentPresentations[0].Component; package.PushItem(SiteEditComponentContext, package.CreateStringItem(ContentType.Text, component.OwningRepository.Id)); }
private static void Main() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; var e = new Engine(); e.Run(); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (Engine game = new Engine()) { game.Run(); } }
public void OrderByOrdersInDescendingOrder() { // Given List<string> content = new List<string>(); Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 4 }; CountModule count2 = new CountModule("A") { AdditionalOutputs = 2 }; Concat concat = new Concat(count2); OrderBy orderBy = new OrderBy((d, c) => d.Get<int>("A")).Descending(); Execute gatherData = new Execute((d, c) => { content.Add(d.Content); return null; }); engine.Pipelines.Add(count, concat, orderBy, gatherData); // When engine.Execute(); // Then Assert.AreEqual(8, content.Count); CollectionAssert.AreEqual(new[] { "5", "4", "3", "3", "2", "2", "1", "1" }, content); }
public void OrderByOrdersThenByInAscendingOrder() { // Given List<string> content = new List<string>(); Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 4 }; CountModule count2 = new CountModule("B") { AdditionalOutputs = 1 }; OrderBy orderBy = new OrderBy((d, c) => d.Get<int>("A")) .ThenBy((d, c) => d.Get<int>("B")); Execute gatherData = new Execute((d, c) => { content.Add(d.Content); return null; }); engine.Pipelines.Add(count, count2, orderBy, gatherData); // When engine.Execute(); // Then Assert.AreEqual(10, content.Count); // (4+1) * (21+1) CollectionAssert.AreEqual(new[] { "11", "12", "23", "24", "35", "36", "47", "48", "59", "510" }, content); }
protected override object OnGet(Engine engine) { var type = engine.GetType(TypeName); if (TypeArguments == null || TypeArguments.Count == 0) return type; var typeArgs = TypeArguments.Select(arg => arg.Get(engine)).Cast<Type>().ToArray(); return type.MakeGenericType(typeArgs); }
public TileData(Engine engine) { _instance = this; IConfigurationService configurationService = engine.Services.GetService<IConfigurationService>(); string ultimaOnlineDirectory = configurationService.GetValue<string>(ConfigSections.UltimaOnline, ConfigKeys.UltimaOnlineDirectory); string filePath = Path.Combine(ultimaOnlineDirectory, "tiledata.mul"); if (filePath != null) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader bin = new BinaryReader(fs); m_LandData = new LandData[0x4000]; for (int i = 0; i < 0x4000; ++i) { if ((i & 0x1F) == 0) { bin.ReadInt32(); // header } TileFlag flags = (TileFlag)bin.ReadInt32(); bin.ReadInt16(); // skip 2 bytes -- textureID m_LandData[i] = new LandData(ReadNameString(bin), flags); } m_ItemData = new ItemData[0x4000]; m_HeightTable = new int[0x4000]; for (int i = 0; i < 0x4000; ++i) { if ((i & 0x1F) == 0) bin.ReadInt32(); // header TileFlag flags = (TileFlag)bin.ReadInt32(); int weight = bin.ReadByte(); int quality = bin.ReadByte(); bin.ReadInt16(); bin.ReadByte(); int quantity = bin.ReadByte(); int anim = bin.ReadInt16(); bin.ReadInt16(); bin.ReadByte(); int value = bin.ReadByte(); int height = bin.ReadByte(); m_ItemData[i] = new ItemData(ReadNameString(bin), flags, weight, quality, quantity, value, height, anim); m_HeightTable[i] = height; } } } else { throw new FileNotFoundException(); } }
public void IfResultsInCorrectCounts() { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule a = new CountModule("A") { AdditionalOutputs = 2 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new If((x, y) => x.Content == "1", b), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(1, b.InputCount); Assert.AreEqual(5, c.InputCount); Assert.AreEqual(3, a.OutputCount); Assert.AreEqual(3, b.OutputCount); Assert.AreEqual(20, c.OutputCount); }
public EngineTests() { _engine = new Engine() .SetValue("log", new Action<object>(Console.WriteLine)) .SetValue("assert", new Action<bool>(Assert.True)) ; }
public void Transform(Engine engine, Package package) { TemplatingLogger log = TemplatingLogger.GetLogger(GetType()); if (package.GetByName(Package.PageName) == null) { log.Info("Do not use this template building block in Component Templates"); return; } Page page = (Page)engine.GetObject(package.GetByName(Package.PageName)); string output; if (page.Title.ToLower().Contains("index")) output = StripNumbersFromTitle(page.OrganizationalItem.Title); else { output = GetLinkToSgIndexPage((StructureGroup)page.OrganizationalItem, engine.GetSession()) + Separator + StripNumbersFromTitle(page.Title); } foreach (OrganizationalItem parent in page.OrganizationalItem.GetAncestors()) { output = GetLinkToSgIndexPage((StructureGroup)parent, engine.GetSession()) + Separator + output; } package.PushItem("breadcrumb", package.CreateStringItem(ContentType.Html, output)); }
public ClrAccessDescriptor(Engine engine, Func<JsValue, JsValue> get, Action<JsValue, JsValue> set) : base( get: new GetterFunctionInstance(engine, get), set: set == null ? Native.Undefined.Instance : new SetterFunctionInstance(engine, set) ) { }
/// <summary> /// Crea un objeto tipo GameObject. /// </summary> /// <param name="effect">Effecto usado para dibujar.</param> /// <param name="engine">Clase principal del juego.</param> /// <param name="position">Posición del objeto.</param> /// <param name="size">Tamaño del objeto.</param> public GameObject(Engine engine, Vector3 position, float size) : base(engine) { this.size = size; color = Color.LightGray; this.position = position; }
/// <summary> /// Constructor de la clase GameObject. /// </summary> /// <param name="effect">Effecto usado para dibujar.</param> /// <param name="engine">Clase principal del juego.</param> /// <param name="size">Tamaño del objeto.</param> /// <param name="position">Posicion x, y, z dada como Vector3.</param> /// <param name="color">Color del objeto.</param> public GameObject(Engine engine, Vector3 position, Color color, float size) : base(engine) { this.size = size; this.color = color; this.position = position; }
protected override void OnExecute(Engine engine) { var type = engine.GetType(TypeProperty, TypePath, TypeCodeTree); var value = engine.Get(ValueProperty, Path, CodeTree, type); bool foundMatch = false; bool executedStatement = false; foreach (var statement in Body) { if (statement is Case) { // Fell through to a new case group. if (executedStatement) return; var caseStatement = statement as Case; if (!foundMatch) { var testValue = caseStatement.Get(engine); if (engine.ShouldInterrupt) return; foundMatch = (bool)engine.Operator(Op.Equals, value, testValue); } } else { // Found a match if (foundMatch) { statement.Execute(engine); executedStatement = true; if (engine.ShouldInterrupt) return; } } } if (!executedStatement) Default.Execute(engine); }
internal override object Read(Engine engine, IntPtr objectAddress) { var fieldAddress = objectAddress + this.Offset; if (this.Size != 4) { throw new InvalidOperationException(); } if (this.ArrayCount != 1) { if (fieldAddress == IntPtr.Zero) { throw new InvalidOperationException(); } var items = new int[this.ArrayCount]; for (int i = 0; i < this.ArrayCount; i++) { items[i] = engine.Runtime.ReadValueS32(fieldAddress); fieldAddress += this.Size; } return items; } if (this.ArrayCount == 0) { throw new InvalidOperationException(); } return engine.Runtime.ReadValueS32(fieldAddress); }
public override void Draw(Texture2D ImageToProcess,RenderHelper rHelper, GameTime gt, Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatingBuffer) { rHelper.PushRenderTarget(renderTarget1); Saturate.Parameters["current"].SetValue(ImageToProcess); Saturate.Parameters["halfPixel"].SetValue(GraphicInfo.HalfPixel); if(useFloatingBuffer) rHelper.RenderFullScreenQuadVertexPixel(Saturate,SamplerState.PointClamp); else rHelper.RenderFullScreenQuadVertexPixel(Saturate, SamplerState.LinearClamp); Texture2D t = rHelper.PopRenderTargetAsSingleRenderTarget2D(); rHelper.PushRenderTarget(renderTarget0); gaussian.Draw(t, rHelper, gt, GraphicInfo, world,useFloatingBuffer); Texture2D x = rHelper.PopRenderTargetAsSingleRenderTarget2D(); rHelper.Clear(Color.Black); Combine.Parameters["halfPixel"].SetValue(GraphicInfo.HalfPixel); Combine.Parameters["base"].SetValue(ImageToProcess); Combine.Parameters["last"].SetValue(x); if (useFloatingBuffer) rHelper.RenderFullScreenQuadVertexPixel(Combine , SamplerState.PointClamp); else rHelper.RenderFullScreenQuadVertexPixel(Combine, GraphicInfo.SamplerState); }
public IncludeExcludeEngineFactory(IPlainEngine plainEngine, Engine.Minify.IMinifyEngine minifyEngine, Http.IHttp http, Configuration.JsMinifierConfiguration configuration) { _plainEngine = plainEngine; _minifyEngine = minifyEngine; _http = http; _configuration = configuration; }
public void PaginateSetsDocumentsInMetadata() { // Given List<IList<string>> content = new List<IList<string>>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; Paginate paginate = new Paginate(3, count); Execute gatherData = new Execute((d, c) => { content.Add(d.Get<IList<IDocument>>(Keys.PageDocuments).Select(x => x.Content).ToList()); return null; }); engine.Pipelines.Add(paginate, gatherData); // When engine.Execute(); // Then Assert.AreEqual(3, content.Count); CollectionAssert.AreEqual(new[] { "1", "2", "3" }, content[0]); CollectionAssert.AreEqual(new[] { "4", "5", "6" }, content[1]); CollectionAssert.AreEqual(new[] { "7", "8" }, content[2]); }
public RollingCircleEnemy(Engine engine, Vector2 position) : base(engine, position) { animation = new Animation(engine, @"Characters\FlickeringCircle", 64, 64, 1, 2, 2, 15, Global.Animations.Repeat); animation.Play(); enemyPhysicsComponent = new EnemyPhysicsComponent(Engine, position, Global.Shapes.Circle); enemyPhysicsComponent.MainFixture.Body.LinearDamping = 2.0f; enemyPhysicsComponent.MainFixture.CollisionFilter.CollisionCategories = (Category)Global.CollisionCategories.Enemy; enemyPhysicsComponent.MainFixture.OnCollision += EnemyOnCollision; deathAnimation = new Animation(engine, @"Miscellaneous\Explosion", 512, 512, 3, 4, 9, 20, Global.Animations.PlayOnce); deathAnimation.Scale = 0.3f; deathAnimation.DrawOrder = int.MaxValue - 1; enemySound = Engine.Audio.GetCue("EnterTheVoid"); light = new Light(engine); light.Color = Color.White; light.Fov = MathHelper.TwoPi; light.Position = position; light.Range = 100; engine.AddComponent(this); }
public void 助詞によって引数の順番を切り替える() { // 副作用を有り。 var engine = new Engine(); string[] codes = { "「A」が「B」を「C」にテストする。" , "「A」が「C」に「B」をテストする。" , "「B」を「A」が「C」にテストする。" , "「B」を「C」に「A」がテストする。" , "「C」に「A」が「B」をテストする。" , "「C」に「B」を「A」がテストする。"}; engine.Global.SetVariable("テスト", new SuffixFunc<Func<object, object, object, object>>( (a, b, c) => ((string)a == "A" && (string)b == "B" && (string)c == "C"), "が", "を", "に")); foreach (var code in codes) { Assert.IsTrue((bool)engine.Execute(code, Statics.TestName)); } var defun = "以下の定義でAがBをCにテストする。" + " [A,B,C]を文字列連結する。" + "以上。"; engine.Execute(defun, Statics.TestName); foreach (var code in codes) { Assert.AreEqual("ABC", (string)engine.Execute(code, Statics.TestName)); } }
public void Transform(Engine engine, Package package) { if (package.GetByName(Package.PageName) == null) return; Page page = (Page)engine.GetObject(package.GetByName(Package.PageName)); bool hasHeader = false; bool hasFooter = false; foreach (CP cp in page.ComponentPresentations) { if (cp.ComponentTemplate.Title.ToLower().Contains("header")) hasHeader = true; if (cp.ComponentTemplate.Title.ToLower().Contains("footer")) hasFooter = true; } if (!hasHeader) { ComponentTemplate headerCt = (ComponentTemplate)engine.GetObject(page.ContextRepository.RootFolder.WebDavUrl + HeaderComponentTemplateUrl); Component header = (Component)engine.GetObject(page.ContextRepository.RootFolder.WebDavUrl + HeaderComponentUrl); package.PushItem("headerCP", package.CreateStringItem(ContentType.Html, string.Format("<tcdl:ComponentPresentation type=\"Dynamic\" componentURI=\"{0}\" templateURI=\"{1}\" />", header.Id, headerCt.Id))); } if (!hasFooter) { ComponentTemplate footerCt = (ComponentTemplate)engine.GetObject(page.ContextRepository.RootFolder.WebDavUrl + FooterComponentTemplateUrl); Component footer = (Component)engine.GetObject(page.ContextRepository.RootFolder.WebDavUrl + FooterComponentUrl); package.PushItem("footerCP", package.CreateStringItem(ContentType.Html, string.Format("<tcdl:ComponentPresentation type=\"Dynamic\" componentURI=\"{0}\" templateURI=\"{1}\" />", footer.Id, footerCt.Id))); } }
public static Dynamic.Page BuildPage(TCM.Page tcmPage, Engine engine, BuildManager manager, int linkLevels, bool resolveWidthAndHeight) { Dynamic.Page p = new Dynamic.Page(); p.Title = tcmPage.Title; p.Id = tcmPage.Id.ToString(); p.Filename = tcmPage.FileName; p.PageTemplate = manager.BuildPageTemplate(tcmPage.PageTemplate); p.Schema = manager.BuildSchema(tcmPage.MetadataSchema); p.Metadata = new Dynamic.SerializableDictionary<string, Dynamic.Field>(); if (linkLevels > 0) { try { if (tcmPage.Metadata != null) { var tcmMetadataFields = new Tridion.ContentManager.ContentManagement.Fields.ItemFields(tcmPage.Metadata, tcmPage.MetadataSchema); p.Metadata = manager.BuildFields(tcmMetadataFields, linkLevels, resolveWidthAndHeight); } } catch (ItemDoesNotExistException) { // fail silently if there is no metadata schema } } p.ComponentPresentations = new List<Dynamic.ComponentPresentation>(); foreach (TCM.ComponentPresentation cp in tcmPage.ComponentPresentations) { Dynamic.ComponentPresentation dynCp = manager.BuildComponentPresentation(cp, engine, linkLevels - 1, resolveWidthAndHeight); p.ComponentPresentations.Add(dynCp); } p.StructureGroup = manager.BuildOrganizationalItem((TCM.StructureGroup)tcmPage.OrganizationalItem); p.Publication = manager.BuildPublication(tcmPage.ContextRepository); p.Categories = manager.BuildCategories(tcmPage); return p; }
public Camera3D(Engine engine) : base(engine) { ResetCamera(); Engine.AddComponent(this); }
public void PaginateSetsCorrectMetadata() { // Given List<int> currentPage = new List<int>(); List<int> totalPages = new List<int>(); List<bool> hasNextPage = new List<bool>(); List<bool> hasPreviousPage = new List<bool>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; Paginate paginate = new Paginate(3, count); Execute gatherData = new Execute((d, c) => { currentPage.Add(d.Get<int>(Keys.CurrentPage)); totalPages.Add(d.Get<int>(Keys.TotalPages)); hasNextPage.Add(d.Get<bool>(Keys.HasNextPage)); hasPreviousPage.Add(d.Get<bool>(Keys.HasPreviousPage)); return null; }); engine.Pipelines.Add(paginate, gatherData); // When engine.Execute(); // Then CollectionAssert.AreEqual(new[] { 1, 2, 3 }, currentPage); CollectionAssert.AreEqual(new[] { 3, 3, 3 }, totalPages); CollectionAssert.AreEqual(new[] { true, true, false }, hasNextPage); CollectionAssert.AreEqual(new[] { false, true, true }, hasPreviousPage); }
public override void Update(Engine.GameTime gameTime) { if(AnimationSetRenderComponent.IsFinished()) { AnimationSetRenderComponent.SetAnimation("Flying"); } }
private Menu menu; // Reference to menu form #endregion Fields #region Constructors // Constructor public Gameplay(Engine initEngine, Menu initMenu, byte initCurrentState = (byte)state.Menu) { currentState = initCurrentState; // These are all inherited from Menu -- engine = initEngine; // 'Continue Game' has not been implemented yet, menu = initMenu; // so constructor will be with a fresh engine and InitializeComponent(); // PreDeal state. }
public override string GetWinner(Room room) { List <string> winners = new List <string>(); List <Player> players = room.GetAlivePlayers(); Player win_player = players[0]; if (players.Count == 1) { if (!win_player.General1Showed) { room.ShowGeneral(win_player, true, false, false); } if (!win_player.General2Showed) { room.ShowGeneral(win_player, false, false, false); } foreach (Player p in room.Players) { if (RoomLogic.IsFriendWith(room, win_player, p)) { winners.Add(p.Name); } } } else { bool has_diff_kingdoms = false; string left_kingdom = null; foreach (Player p in players) { left_kingdom = Engine.GetGeneral(p.ActualGeneral1, room.Setting.GameMode).Kingdom; foreach (Player p2 in players) { if (p == p2) { continue; } if (p.HasShownOneGeneral() && p2.HasShownOneGeneral() && !RoomLogic.IsFriendWith(room, p, p2)) { has_diff_kingdoms = true; break; // if both shown but not friend, hehe. } if ((p.HasShownOneGeneral() && !p2.HasShownOneGeneral() && !RoomLogic.WillBeFriendWith(room, p2, p)) || (!p.HasShownOneGeneral() && p2.HasShownOneGeneral() && !RoomLogic.WillBeFriendWith(room, p, p2))) { has_diff_kingdoms = true; break; // if either shown but not friend, hehe. } if (!p.HasShownOneGeneral() && !p2.HasShownOneGeneral()) { if (Engine.GetGeneral(p.ActualGeneral1, room.Setting.GameMode).Kingdom != Engine.GetGeneral(p2.ActualGeneral1, room.Setting.GameMode).Kingdom) { has_diff_kingdoms = true; break; // if neither shown and not friend, hehe. } } } if (has_diff_kingdoms) { break; } } bool all_live_shown = true; if (!has_diff_kingdoms) { //check all shown before judging careerist, cos same skills could change kindom such as dragonphoenix foreach (Player p in players) { if (!p.HasShownOneGeneral()) { all_live_shown = false; } } } if (!has_diff_kingdoms && !all_live_shown) { // judge careerist List <string> lords = new List <string>(); int all = 0; foreach (Player p in room.Players) { if (p.HasShownOneGeneral()) { if (p.Kingdom == left_kingdom && p.Role != "careerist") { all++; } } else if (Engine.GetGeneral(p.ActualGeneral1, room.Setting.GameMode).Kingdom == left_kingdom) { all++; } } foreach (Player p in room.Players) { if (Engine.GetGeneral(p.ActualGeneral1, room.Setting.GameMode).IsLord()) { if (p.Alive && p.General1Showed) //the lord has shown { lords.Add(Engine.GetGeneral(p.ActualGeneral1, room.Setting.GameMode).Kingdom); } else if (!p.Alive && p.Kingdom == left_kingdom) //the lord is dead, all careerist { return(null); } else if (p.Alive && !p.HasShownOneGeneral() && all > room.Players.Count / 2) //the lord not yet shown { return(null); } } } if (lords.Count == 0 && all > room.Players.Count / 2) //careerist exists { has_diff_kingdoms = true; } } if (has_diff_kingdoms) { return(null); //if has enemy, hehe } // if run here, all are friend. foreach (Player p in players) { if (!p.General1Showed) { room.ShowGeneral(p, true, false, false); // dont trigger event } if (!p.General2Showed) { room.ShowGeneral(p, false, false, false); } } foreach (Player p in room.Players) { if (RoomLogic.IsFriendWith(room, win_player, p)) { winners.Add(p.Name); } } } return(string.Join("+", winners)); }
public static void OpenGuildGump() { Engine.SendPacketToServer(new GuildButtonRequest()); }
public ReturnError DownloadMP3(List <string> links, string destPath) { _songCount = links.Count; if (_songCount == 0) { throw new Exception("No links available."); } if (!Directory.Exists(destPath)) { throw new DirectoryNotFoundException("Destination path does not exist."); } YouTube youtube = YouTube.Default; convertedSong = 0; ReturnError results = new ReturnError(); results.errorNumber = 0; results.errorLinks = new List <string>(); foreach (string link in links) { if (link.Contains("&list=")) { downloadPlaylist(link, destPath, "", 0); } else { try { YouTubeVideo audio = youtube.GetAllVideos(link) .Where(e => e.AudioFormat == AudioFormat.Aac && e.AdaptiveKind == AdaptiveKind.Audio) .ToList() .FirstOrDefault(); string filename = Path.ChangeExtension( Path.Combine(destPath, Path.GetFileNameWithoutExtension(audio.FullName)), "mp3"); filename = filename.Replace(" - YouTube", ""); MediaFile inputFile = new MediaFile { Filename = audio.GetUri() }; MediaFile outputFile = new MediaFile { Filename = filename }; getThumbnail(link); using (Engine engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); engine.ConvertProgressEvent += engine_ConvertProgressEvent; } } catch (NullReferenceException e) { results.errorNumber++; results.errorLinks.Add(link); } } } return(results); }
public static void SetAbility(string ability, string onOff = "toggle") { AbilitiesManager manager = AbilitiesManager.GetInstance(); if (ability.ToLower().Equals("stun")) { Engine.SendPacketToServer(new StunRequest()); return; } if (ability.ToLower().Equals("disarm")) { Engine.SendPacketToServer(new DisarmRequest()); return; } bool primary; switch (ability.ToLower()) { case "primary": primary = true; break; default: primary = false; break; } string onOffNormalized = onOff.Trim().ToLower(); if (onOffNormalized != "toggle") { switch (onOffNormalized) { case "on": { if (primary && manager.IsPrimaryEnabled || !primary && manager.IsSecondaryEnabled) { if (!MacroManager.QuietMode) { UOC.SystemMessage(Strings.Ability_already_set___, (int)UOC.SystemMessageHues.Green); } return; } break; } case "off": { if (primary && !manager.IsPrimaryEnabled || !primary && !manager.IsSecondaryEnabled) { if (!MacroManager.QuietMode) { UOC.SystemMessage(Strings.Ability_not_set___, (int)UOC.SystemMessageHues.Green); } return; } break; } } } if (onOffNormalized == "off" || onOffNormalized == "toggle" && (manager.IsPrimaryEnabled || manager.IsSecondaryEnabled)) { UOC.ClearWeaponAbility(); } else { UOC.SystemMessage(string.Format(Strings.Setting_ability___0_____, ability), (int)UOC.SystemMessageHues.Green); manager.SetAbility(primary ? AbilityType.Primary : AbilityType.Secondary); } }
public void Execute(string input) { var engine = new Engine(input); engine.Reader(); }
public override void Initialize(TargetableObject targetableObject) { _engine = targetableObject.GetComponent <Engine>(); _initialSpeed = _engine.currentSpeed; }
public static void Main(string[] args) { Engine engine = new Engine(); engine.Run(); }
public override void Assign(Room room) { AssignGeneralsForPlayers(room, out Dictionary <Player, List <string> > options); List <Client> receivers = new List <Client>(); foreach (Player player in options.Keys) { player.SetTag("generals", JsonUntity.Object2Json(options[player])); List <string> args = new List <string> { player.Name, string.Empty, JsonUntity.Object2Json(options[player]), false.ToString(), true.ToString(), false.ToString() }; Client client = room.GetClient(player); if (client != null && !receivers.Contains(client)) { client.CommandArgs = args; receivers.Add(client); } } List <Player> players = room.Players; Countdown countdown = new Countdown { Max = room.Setting.GetCommandTimeout(CommandType.S_COMMAND_CHOOSE_GENERAL, ProcessInstanceType.S_CLIENT_INSTANCE), Type = Countdown.CountdownType.S_COUNTDOWN_USE_SPECIFIED }; room.NotifyMoveFocus(players, countdown); room.DoBroadcastRequest(receivers, CommandType.S_COMMAND_CHOOSE_GENERAL); room.DoBroadcastNotify(CommandType.S_COMMAND_UNKNOWN, new List <string> { false.ToString() }); foreach (Player player in options.Keys) { player.RemoveTag("generals"); if (!string.IsNullOrEmpty(player.General1)) { continue; } bool success = true; Client client = room.GetClient(player); List <string> reply = client?.ClientReply; if (client == null || !room.GetClient(player).IsClientResponseReady || reply == null || reply.Count == 0 || string.IsNullOrEmpty(reply[0])) { success = false; } else { string generalName = reply[0]; string[] generals = generalName.Split('+'); if (generals.Length != 2 || (!options[player].Contains(Engine.GetMainGeneral(generals[0])) && room.GetClient(player).UserRight < 3) || (!options[player].Contains(Engine.GetMainGeneral(generals[1])) && room.GetClient(player).UserRight < 3) || !SetPlayerGeneral(room, player, generals[0], true) || !SetPlayerGeneral(room, player, generals[1], false)) { success = false; } } if (!success) { List <string> default_generals = GeneralSelctor.GeInstance().SelectGenerals(room, options[player]); SetPlayerGeneral(room, player, default_generals[0], true); SetPlayerGeneral(room, player, default_generals[1], false); } } foreach (Player player in players) { List <string> names = new List <string>(); if (!string.IsNullOrEmpty(player.General1)) { string name = player.General1; player.Kingdom = Engine.GetGeneral(player.General1, room.Setting.GameMode).Kingdom; string role = Engine.GetMappedRole(player.Kingdom); if (string.IsNullOrEmpty(role)) { role = Engine.GetGeneral(player.General1, room.Setting.GameMode).Kingdom; } names.Add(name); player.Role = role; player.General1 = "anjiang"; foreach (Client p in room.Clients) { if (p != room.GetClient(player)) { room.NotifyProperty(p, player, "Kingdom", "god"); } } room.BroadcastProperty(player, "General1"); room.NotifyProperty(room.GetClient(player), player, "ActualGeneral1"); room.NotifyProperty(room.GetClient(player), player, "Kingdom"); } if (!string.IsNullOrEmpty(player.General2)) { string name = player.General2; names.Add(name); player.General2 = "anjiang"; room.BroadcastProperty(player, "General2"); room.NotifyProperty(room.GetClient(player), player, "ActualGeneral2"); } room.SetTag(player.Name, names); room.HandleUsedGeneral(names[0]); room.HandleUsedGeneral(names[1]); // setup AI //AI* ai = cloneAI(player); //ais << ai; //player->setAI(ai); } //君主转换 if (room.Setting.LordConvert) { room.AskForLordConvert(); } foreach (Player player in players) { General general1 = Engine.GetGeneral(player.ActualGeneral1, room.Setting.GameMode); General general2 = Engine.GetGeneral(player.ActualGeneral2, room.Setting.GameMode); if (general1.CompanionWith(player.ActualGeneral2)) { player.AddMark("CompanionEffect"); } int max_hp = general1.GetMaxHpHead() + general2.GetMaxHpDeputy(); player.SetMark("HalfMaxHpLeft", max_hp % 2); player.MaxHp = max_hp / 2; player.Hp = player.MaxHp; room.BroadcastProperty(player, "MaxHp"); room.BroadcastProperty(player, "Hp"); } }
public void OnCancel(TargetCancelType type) { Engine.AddTextMessage("Reagent drop request canceled."); }
private Dictionary <string, double> CalculateDeputyValue(Room room, string first, List <string> _candidates) { List <string> candidates = _candidates; Dictionary <string, double> points = new Dictionary <string, double>(); foreach (string second in candidates) { if (this.points.ContainsKey(string.Format("{0}+{1}", first, second))) { points[string.Format("{0}+{1}", first, second)] = this.points[string.Format("{0}+{1}", first, second)]; continue; } if (first == second || Engine.GetGeneral(first, room.Setting.GameMode).Kingdom != Engine.GetGeneral(second, room.Setting.GameMode).Kingdom) { continue; } DataRow[] rows1 = pair_value.Select(string.Format("general1 = '{0}' and general2 = '{1}'", first, second)); if (rows1.Length > 0) { this.points[string.Format("{0}+{1}", first, second)] = int.Parse(rows1[0]["value1"].ToString()); points[string.Format("{0}+{1}", first, second)] = int.Parse(rows1[0]["value1"].ToString()); } else { General general1 = Engine.GetGeneral(first, room.Setting.GameMode); General general2 = Engine.GetGeneral(second, room.Setting.GameMode); double general2_value = Engine.GetGeneralValue(second, "Hegemony"); double v = Engine.GetGeneralValue(first, "Hegemony") + general2_value; int max_hp = general1.GetMaxHpHead() + general2.GetMaxHpDeputy(); if (max_hp % 2 > 0) { v -= 0.5; } if (max_hp >= 8) { v += 1; } if (room.Setting.LordConvert) { string lord = "lord_" + first; General lord_general = Engine.GetGeneral(lord, room.Setting.GameMode); if (lord_general != null) { v += 5; } } if (general1.CompanionWith(second)) { v += 3; } if (general1.IsFemale()) { if ("wu" == general1.Kingdom && !general1.HasSkill("jieying", "Hegemony", true)) { v -= 1; } else if (general1.Kingdom != "qun") { v += 0.5; } } else if ("qun" == general1.Kingdom) { v += 0.5; } if (general1.HasSkill("baoling", "Hegemony", true) && general2_value > 6) { v -= 5; } if (max_hp < 8) { List <string> need_high_max_hp_skills = new List <string> { "zhiheng", "zaiqi", "yinghun", "kurou" }; foreach (string skill in need_high_max_hp_skills) { if (Engine.GetGeneralSkills(first, "Hegemony", true).Contains(skill) || Engine.GetGeneralSkills(second, "Hegemony", false).Contains(skill)) { v -= 5; } } } this.points.Add(string.Format("{0}+{1}", first, second), v); points.Add(string.Format("{0}+{1}", first, second), v); } } return(points); }
public void Run() { Engine.Run(); }
public static void Main() { var engine = new Engine(); engine.StartUp(); }
public void RunTarget_WithErrors(Project project, string target) { Engine.BuildProject(project, new [] { target }, new Hashtable(), BuildSettings.None); Assert.IsTrue(Engine.Logger.ErrorEvents.Count > 0, "#RunTarget-HasExpectedErrors"); }
public void Run(int numberOfCycles) { Engine.Run(numberOfCycles); }
static void Main(string[] args) { var engine = new Engine(new ExtendedInteractionManager()); engine.Start(); }
/////////////////////////////////////////////////////////////////////////////////////////////// #region IExecuteArgument Members public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Argument value, ref Result error ) { ReturnCode code = ReturnCode.Ok; if (interpreter != null) { if (arguments != null) { try { string name = null; Variant operand1 = null; Variant operand2 = null; code = Value.GetOperandsFromArguments(interpreter, this, arguments, ValueFlags.AnyVariant, interpreter.CultureInfo, ref name, ref operand1, ref operand2, ref error); if (code == ReturnCode.Ok) { code = Value.FixupVariants( this, operand1, operand2, null, null, false, false, ref error); if (code == ReturnCode.Ok) { if (operand1.IsWideInteger()) { value = ((long)operand1.Value | (long)operand2.Value); } else if (operand1.IsInteger()) { value = ((int)operand1.Value | (int)operand2.Value); } else if (operand1.IsBoolean()) { value = ((bool)operand1.Value | (bool)operand2.Value); } else { error = String.Format( "unsupported operand type for operator {0}", FormatOps.OperatorName(name, this.Lexeme)); code = ReturnCode.Error; } } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); error = String.Format( "caught math exception: {0}", e); code = ReturnCode.Error; } } else { error = "invalid argument list"; code = ReturnCode.Error; } } else { error = "invalid interpreter"; code = ReturnCode.Error; } return(code); }
static void Main(string[] args) { IEngine engine = new Engine(new AppenderFactory(), new LayoutFactory(), new FileReader()); engine.Run(); }
public Car(string make, string model, int year, double fuelQuantity, double fuelConsumption, Engine engine, Tire[] tires) : this(make, model, year, fuelQuantity, fuelConsumption) { this.Engine = engine; this.Tires = tires; }
public static Dynamic.Page BuildPage(TCM.Page tcmPage, Engine engine, BuildManager manager) { return(BuildPage(tcmPage, engine, manager, 1, false, false)); }
private TestExecutionContext GetExecutionContext(Engine engine) => new TestExecutionContext { Namespaces = new TestNamespacesCollection(engine.Namespaces.ToArray()), FileSystem = GetFileSystem() };
/////////////////////////////////////////////////////////////////////// #region IExecute Members public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { if (interpreter == null) { result = "invalid interpreter"; return(ReturnCode.Error); } if (arguments == null) { result = "invalid argument list"; return(ReturnCode.Error); } if (arguments.Count < 2) { result = "wrong # args: should be \"hash option ?arg ...?\""; return(ReturnCode.Error); } ReturnCode code; string subCommand = arguments[1]; bool tried = false; code = ScriptOps.TryExecuteSubCommandFromEnsemble( interpreter, this, clientData, arguments, true, false, ref subCommand, ref tried, ref result); if ((code != ReturnCode.Ok) || tried) { return(code); } // // NOTE: These algorithms are known to be supported by the // framework. // // Normal: MD5, RIPEMD160, SHA, SHA1, SHA256, SHA384, SHA512 // // Keyed: MACTripleDES // // HMAC: HMACMD5, HMACRIPEMD160, HMACSHA1, HMACSHA256, // HMACSHA384, HMACSHA512 // switch (subCommand) { case "keyed": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) <= arguments.Count) && ((argumentIndex + 3) >= arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if ((argumentIndex + 3) == arguments.Count) { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 2], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { algorithm.Key = bytes; } } if (code == ReturnCode.Ok) { if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported keyed hash algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "list": { if ((arguments.Count == 2) || (arguments.Count == 3)) { string type = null; if (arguments.Count == 3) { type = arguments[2]; } switch (type) { case null: case "all": { StringList list = new StringList(); lock (syncRoot) { if (defaultAlgorithms != null) { list.AddRange(defaultAlgorithms); } } if (keyedHashAlgorithmNames != null) { foreach (string hashAlgorithmName in keyedHashAlgorithmNames) { list.Add(StringList.MakeList("keyed", hashAlgorithmName)); } } if (macHashAlgorithmNames != null) { foreach (string hashAlgorithmName in macHashAlgorithmNames) { list.Add(StringList.MakeList("mac", hashAlgorithmName)); } } if (normalHashAlgorithmNames != null) { foreach (string hashAlgorithmName in normalHashAlgorithmNames) { list.Add(StringList.MakeList("normal", hashAlgorithmName)); } } result = list; break; } case "default": { lock (syncRoot) { result = (defaultAlgorithms != null) ? new StringList(defaultAlgorithms) : null; } break; } case "keyed": { result = (keyedHashAlgorithmNames != null) ? new StringList(keyedHashAlgorithmNames) : null; break; } case "mac": { result = (macHashAlgorithmNames != null) ? new StringList(macHashAlgorithmNames) : null; break; } case "normal": { result = (normalHashAlgorithmNames != null) ? new StringList(normalHashAlgorithmNames) : null; break; } default: { result = "unknown algorithm list, must be: all, default, keyed, mac, or normal"; code = ReturnCode.Error; break; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?type?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "mac": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) <= arguments.Count) && ((argumentIndex + 3) >= arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (HMAC algorithm = HMAC.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if ((argumentIndex + 3) == arguments.Count) { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 2], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { algorithm.Key = bytes; } } if (code == ReturnCode.Ok) { if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported hmac algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "normal": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) == arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (HashAlgorithm algorithm = HashAlgorithm.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported hash algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string\"", this.Name, subCommand); code = ReturnCode.Error; } break; } default: { result = ScriptOps.BadSubCommand( interpreter, null, null, subCommand, this, null, null); code = ReturnCode.Error; break; } } return(code); }
public JintArrowFunctionExpression(Engine engine, IFunction function) : base(engine, ArrowParameterPlaceHolder.Empty) { _function = new JintFunctionDefinition(engine, function); }
// Use this for initialization void Start() { _engine = GetComponent<Engine>(); _steerWheel = GetComponent<SteerWheel>(); }
public MoveSystem(Engine engine, Size boardSize) : base(engine) { _boardSize = boardSize; }
private static void Main() { Engine engine = new Engine(); engine.Run(); }
public Dacia(Engine engine, string color, CarModelType model) : base(engine, color) { Model = model; }
static void Main(string[] args) { var optionsResult = Parser.Default.ParseArguments <ConsoleOptions>(args); optionsResult.WithNotParsed(errors => { var text = HelpText.AutoBuild(optionsResult); text.Copyright = " "; text.Heading = "Jackett v" + EnvironmentUtil.JackettVersion + " options:"; System.Console.WriteLine(text); Environment.ExitCode = 1; return; }); optionsResult.WithParsed(options => { try { var runtimeSettings = options.ToRunTimeSettings(); // Initialize autofac, logger, etc. We cannot use any calls to Engine before the container is set up. Engine.BuildContainer(runtimeSettings, new WebApi2Module()); if (runtimeSettings.LogRequests) { Engine.Logger.Info("Logging enabled."); } if (runtimeSettings.TracingEnabled) { Engine.Logger.Info("Tracing enabled."); } if (runtimeSettings.IgnoreSslErrors == true) { Engine.Logger.Info("Jackett will ignore SSL certificate errors."); } if (runtimeSettings.DoSSLFix == true) { Engine.Logger.Info("SSL ECC workaround enabled."); } else if (runtimeSettings.DoSSLFix == false) { Engine.Logger.Info("SSL ECC workaround has been disabled."); } // Choose Data Folder if (!string.IsNullOrWhiteSpace(runtimeSettings.CustomDataFolder)) { Engine.Logger.Info("Jackett Data will be stored in: " + runtimeSettings.CustomDataFolder); } if (!string.IsNullOrEmpty(runtimeSettings.ClientOverride)) { if (runtimeSettings.ClientOverride != "httpclient" && runtimeSettings.ClientOverride != "httpclient2" && runtimeSettings.ClientOverride != "httpclientnetcore") { Engine.Logger.Error($"Client override ({runtimeSettings.ClientOverride}) has been deprecated, please remove it from your start arguments"); Environment.Exit(1); } } // Use Proxy if (options.ProxyConnection != null) { Engine.Logger.Info("Proxy enabled. " + runtimeSettings.ProxyConnection); } /* ====== Actions ===== */ // Install service if (options.Install) { Engine.ServiceConfig.Install(); return; } // Uninstall service if (options.Uninstall) { Engine.Server.ReserveUrls(doInstall: false); Engine.ServiceConfig.Uninstall(); return; } // Reserve urls if (options.ReserveUrls) { Engine.Server.ReserveUrls(doInstall: true); return; } // Start Service if (options.StartService) { if (!Engine.ServiceConfig.ServiceRunning()) { Engine.ServiceConfig.Start(); } return; } // Stop Service if (options.StopService) { if (Engine.ServiceConfig.ServiceRunning()) { Engine.ServiceConfig.Stop(); } return; } // Migrate settings if (options.MigrateSettings) { Engine.ConfigService.PerformMigration(); return; } // Show Version if (options.ShowVersion) { System.Console.WriteLine("Jackett v" + EnvironmentUtil.JackettVersion); return; } /* ====== Overrides ===== */ // Override listen public if (options.ListenPublic || options.ListenPrivate) { if (Engine.ServerConfig.AllowExternal != options.ListenPublic) { Engine.Logger.Info("Overriding external access to " + options.ListenPublic); Engine.ServerConfig.AllowExternal = options.ListenPublic; if (System.Environment.OSVersion.Platform != PlatformID.Unix) { if (ServerUtil.IsUserAdministrator()) { Engine.Server.ReserveUrls(doInstall: true); } else { Engine.Logger.Error("Unable to switch to public listening without admin rights."); Engine.Exit(1); } } Engine.SaveServerConfig(); } } // Override port if (options.Port != 0) { if (Engine.ServerConfig.Port != options.Port) { Engine.Logger.Info("Overriding port to " + options.Port); Engine.ServerConfig.Port = options.Port; if (System.Environment.OSVersion.Platform != PlatformID.Unix) { if (ServerUtil.IsUserAdministrator()) { Engine.Server.ReserveUrls(doInstall: true); } else { Engine.Logger.Error("Unable to switch ports when not running as administrator"); Engine.Exit(1); } } Engine.SaveServerConfig(); } } Engine.Server.Initalize(); Engine.Server.Start(); Engine.RunTime.Spin(); Engine.Logger.Info("Server thread exit"); } catch (Exception e) { Engine.Logger.Error(e, "Top level exception"); } }); }
public NumberInstance(Engine engine) : base(engine) { }
private void fillTable() { cs.PrepareForUpdate(); Filters flt = new Filters(); flt[Filters.RAB_ID] = _rabFemale.ID.ToString(); flt[Filters.HETEROSIS] = chHetererosis.Checked ? "1" : "0"; flt[Filters.INBREEDING] = chInbreed.Checked ? "1" : "0"; flt[Filters.MALE_REST] = _opt_malewait.ToString(); flt[Filters.MAKE_CANDIDATE] = _opt_makeCand.ToString(); flt[Filters.SHOW_CANDIDATE] = chCandidates.Checked ? "1" : "0"; flt[Filters.SHOW_REST] = chRest.Checked ? "1" : "0"; //TODO здесь трахатели идеалогически неверно передаются через объекты Трахов FuckPartner[] fs = Engine.db().GetAllFuckers(flt); listView1.BeginUpdate(); foreach (FuckPartner fP in fs) { bool heter = (fP.BreedId != _rabFemale.BreedID); bool inbr = RabNetEngHelper.inbreeding(_rabFemale.Genoms, fP.OldGenoms); ListViewItem li = listView1.Items.Add(fP.FullName); li.UseItemStyleForSubItems = false; if (fP.LastFuck != DateTime.MinValue && DateTime.Now < fP.LastFuck.Date.AddDays(_opt_malewait)) { li.SubItems[IND_NAME].ForeColor = chRest.ForeColor; } li.Tag = fP; li.SubItems.Add("Мальчик"); if (fP.Status == 1 || (fP.Status == 0 && fP.Age >= _opt_makeCand)) { li.SubItems[IND_STATE].Text = "Кандидат"; li.SubItems[IND_STATE].ForeColor = chCandidates.ForeColor; } if (fP.Status == 2) { li.SubItems[IND_STATE].Text = "Производитель"; } li.SubItems.Add(_breeds[fP.BreedId]); li.SubItems.Add(fP.F***s.ToString()); li.SubItems.Add(fP.MutualChildren.ToString()); li.SubItems.Add(inbr ? "ДА" : "-"); int inbrLevel = 0; if (RabbitGen.DetectInbreeding(_rabFemale.RabGenoms, fP.RabGenoms, ref inbrLevel)) { li.SubItems.Add(inbrLevel.ToString() + " поколение"); } else { li.SubItems.Add("-"); } if (heter) { li.SubItems[IND_BREED].ForeColor = chHetererosis.ForeColor; } if (inbr) { li.SubItems[IND_INBR].ForeColor = chInbreed.ForeColor; } if (_rabMaleId == fP.Id) { li.Selected = true; li.EnsureVisible(); } } // если был передан партнер, но его нет в списке, то обнуляем его, т.к. он не был выбран if (listView1.SelectedItems.Count == 0) { _rabMaleId = 0; } else { listView1_SelectedIndexChanged(null, null); } listView1.EndUpdate(); cs.RestoreAfterUpdate(); }
public async Task <IHttpActionResult> SetConfig() { var originalPort = Engine.Server.Config.Port; var originalAllowExternal = Engine.Server.Config.AllowExternal; var jsonReply = new JObject(); try { var postData = await ReadPostDataJson(); int port = (int)postData["port"]; bool external = (bool)postData["external"]; string saveDir = (string)postData["blackholedir"]; bool updateDisabled = (bool)postData["updatedisabled"]; bool preRelease = (bool)postData["prerelease"]; bool logging = (bool)postData["logging"]; string basePathOverride = (string)postData["basepathoverride"]; Engine.Server.Config.UpdateDisabled = updateDisabled; Engine.Server.Config.UpdatePrerelease = preRelease; Engine.Server.Config.BasePathOverride = basePathOverride; Startup.BasePath = Engine.Server.BasePath(); Engine.Server.SaveConfig(); Engine.SetLogLevel(logging ? LogLevel.Debug : LogLevel.Info); Startup.TracingEnabled = logging; if (port != Engine.Server.Config.Port || external != Engine.Server.Config.AllowExternal) { if (ServerUtil.RestrictedPorts.Contains(port)) { jsonReply["result"] = "error"; jsonReply["error"] = "The port you have selected is restricted, try a different one."; return(Json(jsonReply)); } // Save port to the config so it can be picked up by the if needed when running as admin below. Engine.Server.Config.AllowExternal = external; Engine.Server.Config.Port = port; Engine.Server.SaveConfig(); // On Windows change the url reservations if (System.Environment.OSVersion.Platform != PlatformID.Unix) { if (!ServerUtil.IsUserAdministrator()) { try { processService.StartProcessAndLog(Application.ExecutablePath, "--ReserveUrls", true); } catch { Engine.Server.Config.Port = originalPort; Engine.Server.Config.AllowExternal = originalAllowExternal; Engine.Server.SaveConfig(); jsonReply["result"] = "error"; jsonReply["error"] = "Failed to acquire admin permissions to reserve the new port."; return(Json(jsonReply)); } } else { serverService.ReserveUrls(true); } } (new Thread(() => { Thread.Sleep(500); serverService.Stop(); Engine.BuildContainer(); Engine.Server.Initalize(); Engine.Server.Start(); })).Start(); } if (saveDir != Engine.Server.Config.BlackholeDir) { if (!string.IsNullOrEmpty(saveDir)) { if (!Directory.Exists(saveDir)) { throw new Exception("Blackhole directory does not exist"); } } Engine.Server.Config.BlackholeDir = saveDir; Engine.Server.SaveConfig(); } jsonReply["result"] = "success"; jsonReply["port"] = port; jsonReply["external"] = external; } catch (Exception ex) { logger.Error(ex, "Exception in set_port"); jsonReply["result"] = "error"; jsonReply["error"] = ex.Message; } return(Json(jsonReply)); }