Example #1
0
        /// <summary>
        /// Translates Dafny program to Boogie program
        /// </summary>
        /// <returns>Exit value</returns>
        public static void Translate(Dafny.Program dafnyProgram, string uniqueIdPrefix, out Bpl.Program boogieProgram) {

            Translator translator = new Translator(dafnyProgram.reporter);
            translator.InsertChecksums = true;
            translator.UniqueIdPrefix = uniqueIdPrefix;
            boogieProgram = translator.Translate(dafnyProgram);
        }
Example #2
0
 public PropertyGenerator(GeneratorData data, Translator translator, Documentation documentation)
 {
     this.data = data;
     this.translator = translator;
     this.documentation = documentation;
     this.PropertyMethods = new List<IntPtr>();
 }
 public static TranslationVote FindVote(Translation translation, Translator translator)
 {
     return Global.CurrentSession.QueryOver<TranslationVote>()
         .Where(x => x.Translation == translation)
         .And(x => x.Translator == translator)
         .SingleOrDefault();
 }
Example #4
0
        public void EnsureExceptionThrownnForInvalidCountry()
        {
            // Arrange
            var translator = new Translator();

            // Act and Assert
            Assert.Throws<TrosiTranslationException>(() => translator.Translate("Translate", "UK", "US"));
        }
Example #5
0
 public override CType ToCType(Translator translator)
 {
     CTree tree = CreateCType();
     foreach (Member member in _members)
     {
         tree.Add(member.ToCType(translator), member.Name, member.TopOffset);
     }
     return tree;
 }
        public static void UpdateRank(Translator translator)
        {
            var votes = Global.CurrentSession.QueryOver<TranslationVote>()
                .Where(x => x.Translator == translator)
                .RowCount();

            translator.Rank = votes;

            Global.CurrentSession.Update(translator);
        }
        public void ShouldSuccessfullyTranslate()
        {
            var sut = new Translator();

            var skater = new SkaterModel { Id = 1, Name = "Luan Oliveira", Brand = "Flip", Stance = "Goofy" };

            var actual = sut.Translate(skater);

            Assert.NotNull(actual);
        }
Example #8
0
        public void FixtureSetup()
        {
            this.kernel = new StandardKernel(new TestModule());

            var wizard = MockRepository.GenerateStub<IWizard>();
            this.kernel.Rebind<IWizard>().ToConstant(wizard);

            this.translator = this.kernel.Get<Translator>();
            this.translator.Kernel = this.kernel;
        }
Example #9
0
 public Translator GetTranslator(IPrincipal user)
 {
     var translator = Translators.FirstOrDefault(t => t.EMail == user.Identity.Name);
     if (translator == null)
     {
         translator = new Translator {EMail = user.Identity.Name};
         Translators.Add(translator);
         SaveChanges();
     }
     return translator;
 }
Example #10
0
        public void EnsureCorrectTranslation(string inputText, string expectedResult, string from, string to)
        {
            // Arrange
            var translator = new Translator();

            // Act
            var result = translator.Translate(inputText, from, to);

            // Assert
            Assert.That(result, Is.EqualTo(expectedResult));
        }
        public void Translation_Should_Log_Message()
        {
            var log = MockRepository.GenerateMock<ILog>();
             var client = MockRepository.GenerateStub<ITranslationClient>();

             var translator = new Translator(log, client);

             translator.EnglishToFrench("Hello");

             log.AssertWasCalled(me => me.Debug("Translating"));
        }
        public void Translation_Should_Log_Message()
        {
            var log = new Mock<ILog>();
             var client = new Mock<ITranslationClient>();

             var translator = new Translator(log.Object, client.Object);

             translator.EnglishToFrench("Hello");

             log.Verify(me => me.Debug("Translating"));
        }
        public void Translation_Should_Log_Message()
        {
            var log = Substitute.For<ILog>();
             var client = Substitute.For<ITranslationClient>();

             var translator = new Translator(log, client);

             translator.EnglishToFrench("Hello");

             log.Received().Debug("Translating");
        }
        public void When_Translating_Message_Should_Be_Passed_To_Log()
        {
            var log = new FakeLog();
             var client = new FakeClient();

             var translator = new Translator(log, client);

             translator.EnglishToFrench("Hello");

             Assert.IsTrue(log.LastCallWasDebug);
             Assert.That("Translating", Is.EqualTo(log.LastMessage));
        }
        protected void Translate_OnClick(object sender, EventArgs e)
        {
            String[] input = InputText.Text.Trim().Split(' ');

            String statistics = String.Empty;

            Translator translator = new Translator(Server.MapPath("~/resources/E2KDictionary.xml"),_inputLanguage, _outputLanguage);
            translator.UnknownText = "unknown ";
            OutputText.Text = translator.Translate(input, out statistics);

            Statistics.Text = statistics;
        }
Example #16
0
 public static bool Verify(Program dafnyProgram, ResolverTagger resolver, string uniqueIdPrefix, string requestId, ErrorReporterDelegate er, Program unresolvedProgram)
 {
   var translator = new Translator(dafnyProgram.reporter, er)
   {
     InsertChecksums = true,
     UniqueIdPrefix = uniqueIdPrefix
   };
   var boogieProgram = translator.Translate(dafnyProgram, unresolvedProgram);
   resolver.ReInitializeVerificationErrors(requestId, boogieProgram.Implementations);
   var outcome = BoogiePipeline(boogieProgram, 1 < CommandLineOptions.Clo.VerifySnapshots ? uniqueIdPrefix : null, requestId, er);
   return outcome == PipelineOutcome.Done || outcome == PipelineOutcome.VerificationCompleted;
 }
Example #17
0
        public void EnsureMultipleCallsFromSameObjectComplete()
        {
            // Arrange
            var translator = new Translator();

            // Act
            var firstResult = translator.Translate("Translate", "en", "de");
            var secondResult = translator.Translate("Translate", "en", "it");

            // Assert
            Assert.That(firstResult, Is.EqualTo("Übersetzen"));
            Assert.That(secondResult, Is.EqualTo("Traduci"));
        }
        private void Init()
        {
            var resPath = Path.Combine(AssemblyDirectory, "resources");

            var files = Directory.GetFiles(resPath, "*.po", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                var translator = new Translator();
                translator.RegisterTranslation(file);

                translators.Add(Path.GetFileNameWithoutExtension(file), translator);
            }
        }
        public static Translation FindByKeyForTranslator(int id, string language, Translator translator)
        {
            var crit = DetachedCriteria.For<Language>()
                .Add(Restrictions.Eq("IsoCode", language))
                .SetProjection(Projections.Id());

            return Global.CurrentSession.CreateCriteria<Translation>()
                .Add(Subqueries.PropertyEq("Language", crit))
                .Add(Restrictions.Eq("Translator", translator))
                .CreateAlias("Key", "k")
                .Add(Restrictions.Eq("k.Id", id))
                .UniqueResult<Translation>();
        }
        public void When_Translating_Original_Should_Be_Passed_To_Client_And_Return_Result()
        {
            var log = new FakeLog();
             var client = new FakeClient();

             var translator = new Translator(log, client);

             var original = "Hello";
             var expected = "Bonjour";
             client.Setup(original, expected);

             Assert.That(expected, Is.EqualTo(translator.EnglishToFrench(original)));
        }
Example #21
0
        public static void Interactive()
        {
            IN = Console.In;
            OUT = Console.Out;
            ERROR = Console.Error;

            try
            {
                var scope = new Scope();
                var compiler = new Translator();

                for (string line = Line(); line != null; line = Line())
                {
                    Tokenizer tokens = new Tokenizer(new ParseReader(new StringReader(line)));
                    try
                    {
                        Parser parser = new Parser(tokens);
                        try
                        {
                            StmtAST stmt = parser.Stmt();
                            if(parser.Tokens.PeekType() != new EoF())
                                ERROR.WriteLine("WARNING: Ignoring tokens: " + parser.Tokens.PeekToken().GetText());
                            
                            object value = stmt.Translate(compiler).Exec(scope);
                            if(value != null)
                                OUT.WriteLine(value.ToString());
                            
                            OUT.Flush();

                        }
                        catch(InternalStorkNetException e)
                        {
                            OUT.Write("INTERNAL ERROR: " + e.Message + "\n");
                            OUT.Write(e.StackTrace);
                        }
                        catch(StorkNetException e)
                        {
                            OUT.Write("ERROR: " + e.Message + "\n");
                        }
                    }
                    finally
                    {
                        tokens.Close();
                    }
                }
            }
            catch (Exception e)
            {
                OUT.WriteLine(e.StackTrace);
            }
        }
        public CommanderAnimation(Scene scene)
        {
            Scene = scene;

            Background = new Image("PixelBlanc")
            {
                Color = Color.White,
                Alpha = 0,
                Size = Preferences.BackBuffer,
                VisualPriority = VisualPriorities.Cutscenes.IntroCommanderBackground,
                Blend = BlendType.Add
            };

            Commander = new Text("Commander", @"Pixelite")
            {
                Color = Color.White,
                SizeX = 16,
                VisualPriority = VisualPriorities.Cutscenes.IntroCommanderText
            };

            SubTitle = new Translator(
                scene,
                new Vector3(0, 100, 0),
                "Alien", Colors.Default.NeutralDark,
                @"Pixelite", Colors.Default.AlienBright,
                "Todo: Subtitle here",
                5, true, 4000, 250, VisualPriorities.Cutscenes.IntroCommanderText, false);
            SubTitle.CenterText = true;

            TimeBeforeIn = IntroCutscene.Timing["CommanderIn"];

            PrepareLetters();

            //Scene.VisualEffects.Add(Background, Core.Visual.VisualEffects.FadeInFrom0(255, TimeBeforeIn, 2000));
            //Scene.VisualEffects.Add(Background, Core.Visual.VisualEffects.FadeOutTo0(255, TimeBeforeIn + 11000, 2000));

            foreach (var kvp in Letters)
            {
                kvp.Key.Alpha = 0;

                Scene.PhysicalEffects.Add(kvp.Key, Core.Physics.PhysicalEffects.Move(kvp.Value, TimeBeforeIn + 2000, 10000));
                Scene.VisualEffects.Add(kvp.Key, Core.Visual.VisualEffects.FadeInFrom0(255, TimeBeforeIn + Main.Random.Next(2000, 3000), 1500));
                Scene.VisualEffects.Add(kvp.Key, Core.Visual.VisualEffects.FadeOutTo0(255, TimeBeforeIn + 11000, 1000));
            }

            Scene.VisualEffects.Add(SubTitle, Core.Visual.VisualEffects.FadeInFrom0(255, TimeBeforeIn + 5000, 3000));
            Scene.VisualEffects.Add(SubTitle, Core.Visual.VisualEffects.FadeOutTo0(255, TimeBeforeIn + 11000, 1000));

            Elapsed = 0;
        }
        public void Translation_Should_Return_Result_From_Client()
        {
            var log = Substitute.For<ILog>();
             var client = Substitute.For<ITranslationClient>();

             var translator = new Translator(log, client);

             var original = "Hello";
             var expected = "Bonjour";

             client.EnglishToFrench(original).Returns(expected);

             Assert.That(expected, Is.EqualTo(translator.EnglishToFrench(original)));
        }
        public void Translation_Should_Return_Result_From_Client()
        {
            var log = new Mock<ILog>();
             var client = new Mock<ITranslationClient>();

             var translator = new Translator(log.Object, client.Object);

             var original = "Hello";
             var expected = "Bonjour";

             client.Setup(me => me.EnglishToFrench(original))
            .Returns(expected);

             Assert.That(expected, Is.EqualTo(translator.EnglishToFrench(original)));
        }
        private EffectsController<IVisual> EffectsController; // needed to be controller by this object because of the Tutorial system


        public LevelStartedAnnunciation(Simulator simulator, Level level)
        {
            Simulator = simulator;

            TranslatorMission = new Translator
            (Simulator.Scene, new Vector3(-600, -330, 0), "Alien", Colors.Default.AlienBright, @"Pixelite", Colors.Default.NeutralBright, level.Mission, 4, true, 4000, 250, Preferences.PrioriteGUIHistoire, false);

            EffectsController = new EffectsController<IVisual>();

            EffectsController.Add(TranslatorMission.ToTranslate, EphemereGames.Core.Visual.VisualEffects.FadeInFrom0(255, 1000, 500));
            EffectsController.Add(TranslatorMission.Translated, EphemereGames.Core.Visual.VisualEffects.FadeInFrom0(255, 1000, 500));

            EffectsController.Add(TranslatorMission.ToTranslate, EphemereGames.Core.Visual.VisualEffects.FadeOutTo0(255, 10000, 2000));
            EffectsController.Add(TranslatorMission.Translated, EphemereGames.Core.Visual.VisualEffects.FadeOutTo0(255, 10000, 2000));
        }
        public void Translation_Should_Return_Result_From_Client()
        {
            var log = MockRepository.GenerateStub<ILog>();
             var client = MockRepository.GenerateStub<ITranslationClient>();

             var translator = new Translator(log, client);

             var original = "Hello";
             var expected = "Bonjour";

             client.Stub(me => me.EnglishToFrench(original))
            .Return(expected);

             Assert.That(expected, Is.EqualTo(translator.EnglishToFrench(original)));
        }
Example #27
0
        public static void Main(string[] args)
        {
            string progressMapPath = Path.Combine(Environment.CurrentDirectory, @"source\progress map.vsdx");
            string inputOntologyPath = Path.Combine(Environment.CurrentDirectory, @"source\bpmn2_OWL.owl");
            string outputOntologyPath = Path.Combine(Environment.CurrentDirectory, @"source\bpmn2.owl");

            Translator translator = new Translator();

            translator.InputOntologyPath = inputOntologyPath;
            translator.ProgressMapPath = progressMapPath;
            translator.OutputOntologyPath = outputOntologyPath;

            translator.execute();

            Console.ReadLine();
        }
Example #28
0
    // Use this for initialization
    void Start()
    {
        main = this;
        _next = 0;

        //ball
        _ball = new List<GameObject>();

        //receiver
        _receiver = Instantiate(Resources.Load("Receiver")) as GameObject;
        _receiver.transform.parent = gameObject.transform;
        _receiver.transform.Translate(0f, 0f, 0f);

        //where balls will be destroyed (double receiver height)
        _end = 0 - _receiver.transform.localScale.y * 2;
    }
        public void TranslateColumnMap_returns_cached_result_for_streaming_queries()
        {
            var metadataWorkspaceMock = new Mock<MetadataWorkspace>();
            metadataWorkspaceMock.Setup(m => m.GetQueryCacheManager()).Returns(QueryCacheManager.Create());

            var collectionMap = BuildSimpleEntitySetColumnMap(metadataWorkspaceMock);

            var factory =
                new Translator().TranslateColumnMap<object>(
                    collectionMap, metadataWorkspaceMock.Object, new SpanIndex(), MergeOption.NoTracking, streaming: true, valueLayer: false);
            Assert.NotNull(factory);
            Assert.Null(factory.NullableColumns);
            Assert.Null(factory.ColumnTypes);
            Assert.Same(factory, 
                new Translator().TranslateColumnMap<object>(
                    collectionMap, metadataWorkspaceMock.Object, new SpanIndex(), MergeOption.NoTracking, streaming: true, valueLayer: false));
        }
Example #30
0
        static void Main(string[] args)
        {
            if (string.IsNullOrEmpty(args[0])) throw new Exception("No file name");

            string inputFile = args[0];
            string outputFile = GetOutputFilePath(inputFile);

            Parser p = new Parser(inputFile);
            Translator t = new Translator();
            SymbolTableBuilder b = new SymbolTableBuilder();

            List<ParsedCommand> parsedCommands = p.Parse();
            Dictionary<string, int> symbolTable = b.Build(parsedCommands);
            List<string> codedCommands = t.Translate(parsedCommands, symbolTable);

            File.WriteAllLines(outputFile, codedCommands.ToArray());
        }
        private void btnApplyLoan_Click(object sender, RoutedEventArgs e)
        {
            double amount = slAmount.Value;
            int    length = Convert.ToInt16(slLenght.Value) * 12;

            Loan loan = new Loan(GameObject.GetInstance().GameTime, amount, length, this.Airline.LoanRate);

            if (AirlineHelpers.CanApplyForLoan(GameObject.GetInstance().HumanAirline, loan))
            {
                this.Airline.addLoan(loan);

                AirlineHelpers.AddAirlineInvoice(this.Airline.Airline, GameObject.GetInstance().GameTime, Invoice.InvoiceType.Loans, loan.Amount);
            }
            else
            {
                WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2124"), Translator.GetInstance().GetString("MessageBox", "2124", "message"), WPFMessageBoxButtons.Ok);
            }
        }
Example #32
0
 private void FrmInstanceName_Load(object sender, EventArgs e)
 {
     Translator.TranslateForm(this, "Scada.Admin.App.Forms.FrmItemName");
     Modified = false;
 }
Example #33
0
 public Collector(Translator translator)
 {
     _translator = translator;
 }
Example #34
0
 private void ShowMaintenanceServerModal()
 {
     _modalManager.ShowWarningDialog(Translator.Get("CantConnectToMaintenanceServer"));
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["expid"] != "0")
        {
            List <CompanyProducts> CP  = CompanyProducts.GetProductsByCompanyID(Convert.ToInt32(Request.QueryString["expid"]));
            List <BIRegistration>  BIU = BIRegistration.GetAll();

            string[] arrProdInterest = new string[10];
            string   strTemp = "";
            int      i, j, k, l;
            int      counter        = 0;
            bool     check          = false;
            bool     newLine        = false;
            string[] arrPhraseWords = new string[2];


            if (CP.Count > 0)
            {
                VisitorsPlaceHolder.Text += "<center><b style='font-size: 16pt'><u>" + CP[0].CompanyName + "</u></b></center><br />";
                VisitorsPlaceHolder.Text += "<br />";

                for (i = 0; i < BIU.Count; i++)
                {
                    strTemp         = BIU[i].ProductInterest;
                    arrProdInterest = strTemp.Split(';');
                    for (l = 0; l < arrProdInterest.Length; l++)
                    {
                        if (arrProdInterest[l] != null)
                        {
                            counter++;
                        }
                    }

                    for (j = 0; j < counter; j++)
                    {
                        for (k = 0; k < CP.Count; k++)
                        {
                            if (arrProdInterest[j] == Convert.ToString(CP[k].ParentID))
                            {
                                if (check == false)
                                {
                                    VisitorsPlaceHolder.Text += "<strong><u>" + Translator.DirectTranslation(BIU[i].FirstName) + " " + Translator.DirectTranslation(BIU[i].LastName) + "</u></strong><br />";
                                    VisitorsPlaceHolder.Text += "Job Title " + Translator.DictionaryTranslation(BIU[i].JobTitle) + " Company " + Translator.DictionaryTranslation(BIU[i].Company) + "<br />";
                                    VisitorsPlaceHolder.Text += "Country " + Translator.DictionaryTranslation(BIU[i].Country) + " City " + Translator.DictionaryTranslation(BIU[i].City) + "<br />";
                                    VisitorsPlaceHolder.Text += "Email " + BIU[i].Email + " Web Site " + BIU[i].Website + "<br />";
                                    VisitorsPlaceHolder.Text += "Phone: " + BIU[i].Phone + " Fax: " + BIU[i].Fax + "<br /><br />";
                                    VisitorsPlaceHolder.Text += "<strong>Interested Products:</strong><br/>";
                                    check   = true;
                                    newLine = true;
                                }

                                strTemp                   = CP[k].ProductName;
                                arrPhraseWords            = strTemp.Split('(');
                                VisitorsPlaceHolder.Text += " * " + arrPhraseWords[0] + "<br />";
                            }
                        }
                    }
                    check   = false;
                    counter = 0;
                    if (newLine == true)
                    {
                        VisitorsPlaceHolder.Text += "<br />";
                        newLine = false;
                    }
                }
            }
            else
            {
                VisitorsPlaceHolder.Text += "<b>Equipment was not chosen for the company</b>";
            }
        }
        else
        {
            VisitorsPlaceHolder.Text += "<b>The company was not chosen</b>";
        }
    }
Example #36
0
 // internal for FormTranslate
 internal MessageBoxes()
 {
     Translator.Translate(this, AppSettings.CurrentTranslation);
 }
Example #37
0
 private void FrmDeviceCommand_Load(object sender, EventArgs e)
 {
     Translator.TranslateForm(this, "Scada.Server.Shell.Forms.FrmGenCommand");
     pnlCmdVal.Top = pnlCmdDevice.Top = pnlCmdData.Top;
     AdjustControls();
 }
Example #38
0
        public void TestReadNewProjectFormat()
        {
            var testProject = @"
            <Project Sdk=""Microsoft.NET.Sdk"">
              <PropertyGroup>
                <RootNamespace>TestProject</RootNamespace>
                <AssemblyName>TestProject</AssemblyName>
                <TargetFramework>net40</TargetFramework>

                <NoStdLib>true</NoStdLib>
                <DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
                <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
                <AdditionalExplicitAssemblyReferences />

              </PropertyGroup>

              <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">
                <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
              </PropertyGroup>

              <ItemGroup>
                <!-- This is just an example include that does not necessarily needs to exist at all. -->
                <!-- The test this file is subject to is not building an actual Bridge app, but just having Bridge.Translator load the project file. -->
                <Reference Include=""Bridge"">
                  <SpecificVersion>False</SpecificVersion>
                  <HintPath>$(SolutionDir)\Bridge\Bridge.dll</HintPath>
                </Reference>
              </ItemGroup>

              <ItemGroup>
                <Folder Include=""Properties\"" />
              </ItemGroup>

            </Project>";
            var tmpDir      = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tmpFile     = Path.Combine(tmpDir, "Test.csproj");

            try
            {
                Directory.CreateDirectory(tmpDir);
                File.WriteAllText(tmpFile, testProject);
                File.WriteAllText(Path.Combine(tmpDir, "test1.cs"), "using System;");
                File.WriteAllText(Path.Combine(tmpDir, "test2.cs"), "using System;");

                var translator = new Translator(tmpFile, null);
                translator.Log          = Substitute.For <ILogger>();
                translator.AssemblyInfo = new AssemblyInfo
                {
                    CombineLocales   = false,
                    CombineScripts   = true,
                    OutputFormatting = JavaScriptOutputType.Minified,
                    FileName         = "test.js"
                };
                translator.ProjectProperties = new ProjectProperties()
                {
                    Configuration = "Release",
                    Platform      = "AnyCPU",
                };

                translator.EnsureProjectProperties();

                Assert.AreEqual(OverflowMode.Checked, translator.OverflowMode);
                Assert.AreEqual("TestProject", translator.ProjectProperties.RootNamespace);
                Assert.AreEqual("TestProject", translator.ProjectProperties.AssemblyName);
                Assert.AreEqual(Path.Combine(tmpDir, "bin", "Release", "net40", "TestProject.dll"), translator.AssemblyLocation);

                var files = translator.SourceFiles.OrderBy(s => s).ToArray();
                Assert.AreEqual("test1.cs", files[0]);
                Assert.AreEqual("test2.cs", files[1]);

                var constants = translator.DefineConstants.OrderBy(c => c).ToArray();
                Assert.AreEqual("BRIDGE", constants.First(ct => ct == "BRIDGE"));
                Assert.AreEqual("NET40", constants.First(ct => ct == "NET40"));
                Assert.AreEqual("RELEASE", constants.First(ct => ct == "RELEASE"));
                Assert.AreEqual("TRACE", constants.First(ct => ct == "TRACE"));
            }
            finally
            {
                Directory.Delete(tmpDir, true);
            }
        }
Example #39
0
        public void TestReadOldProjectFormat()
        {
            var testProject = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <Project ToolsVersion=""12.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
              <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
              <PropertyGroup>
                <ProjectGuid>{16777B9C-A3B6-4E0B-B5A2-AA933A2F54D3}</ProjectGuid>
                <RootNamespace>TestProject</RootNamespace>
                <AssemblyName>TestProject</AssemblyName>
              </PropertyGroup>
              <PropertyGroup>
                <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>
                <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>
                <OutputType>Library</OutputType>
                <AppDesignerFolder>Properties</AppDesignerFolder>
                <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
                <FileAlignment>512</FileAlignment>
                <RestorePackages>true</RestorePackages>
                <NoStdLib>True</NoStdLib>
                <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
                <AdditionalExplicitAssemblyReferences />
                <WarningLevel>0</WarningLevel>
                <NoWarn>1591, 0219, 0414, 0618, 0626, 0649, 0693, 0824, 0660, 0661, 7035</NoWarn>
              </PropertyGroup>
              <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">
                <OutputPath>bin\Debug\</OutputPath>
              </PropertyGroup>
              <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">
                <OutputPath>bin\Release\</OutputPath>
              </PropertyGroup>
              <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">
                <DebugSymbols>true</DebugSymbols>
                <DebugType>full</DebugType>
                <Optimize>false</Optimize>
                <DefineConstants>DEBUG;TRACE</DefineConstants>
                <ErrorReport>prompt</ErrorReport>
                <CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
              </PropertyGroup>
              <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">
                <DebugType>pdbonly</DebugType>
                <Optimize>true</Optimize>
                <DefineConstants>TRACE</DefineConstants>
                <ErrorReport>prompt</ErrorReport>
                <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
              </PropertyGroup>
              <ItemGroup>
                <Compile Include=""Properties\AssemblyInfo.cs"" />
                <Compile Include=""Test.cs"" />
              </ItemGroup>
              <ItemGroup>
                <None Include=""Bridge\bridge.json"" />
              </ItemGroup>
              <ItemGroup>
                <Reference Include=""Bridge"">
                  <SpecificVersion>False</SpecificVersion>
                  <HintPath>..\..\..\..\Bridge\bin\$(Configuration)\Bridge.dll</HintPath>
                </Reference>
                <Reference Include=""Bridge.Html5"">
                  <SpecificVersion>False</SpecificVersion>
                  <HintPath>..\..\..\..\Html5\bin\$(Configuration)\Bridge.Html5.dll</HintPath>
                </Reference>
              </ItemGroup>
              <ItemGroup>
                <Folder Include=""Bridge\build\"" />
                <Folder Include=""Bridge\output\"" />
              </ItemGroup>
              <!-- Bridge Compiler -->
              <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
              <PropertyGroup Condition=""$(UseBridgeTask) != true"">
                <PostBuildEvent Condition=""$(OS) != Unix"">""$(ProjectDir)..\..\..\Builder\$(OutDir)bridge.exe"" -p ""$(ProjectPath)"" -b ""$(ProjectDir)$(OutDir)Bridge.dll"" -cfg ""$(Configuration)"" --platform ""$(Platform)""</PostBuildEvent>
                <PostBuildEvent Condition=""$(OS) == Unix"">mono ""$(ProjectDir)../../../Builder/$(OutDir)bridge.exe"" -p ""$(ProjectDir)/$(MSBuildProjectFile)"" -b ""$(ProjectDir)$(OutDir)Bridge.dll""  -cfg ""$(Configuration)"" --platform ""$(Platform)""</PostBuildEvent>
              </PropertyGroup>
              <UsingTask Condition=""$(UseBridgeTask) == true"" TaskName=""GenerateScript"" AssemblyFile=""$(ProjectDir)..\..\..\Build\$(OutDir)Bridge.Build.dll"" />
              <Target Condition=""$(UseBridgeTask) == true"" Name=""AfterBuild"">
                <Message Text=""Using Bridge Task"" Importance=""high"" />
                <GenerateScript DefineConstants=""$(DefineConstants)"" OutputPath=""$(OutputPath)"" Configuration=""$(Configuration)"" Assembly=""@(IntermediateAssembly)"" AssembliesPath=""$(OutputPath)"" ProjectPath=""$(MSBuildProjectFullPath)"" />
              </Target>
            </Project>";
            var tmpDir      = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tmpFile     = Path.Combine(tmpDir, "Test.csproj");

            try
            {
                Directory.CreateDirectory(tmpDir);
                File.WriteAllText(tmpFile, testProject);

                var translator = new Translator(tmpFile, null);
                translator.Log          = Substitute.For <ILogger>();
                translator.AssemblyInfo = new AssemblyInfo
                {
                    CombineLocales   = false,
                    CombineScripts   = true,
                    OutputFormatting = JavaScriptOutputType.Minified,
                    FileName         = "test.js"
                };
                translator.ProjectProperties = new ProjectProperties()
                {
                    Configuration = "Release",
                    Platform      = "AnyCPU",
                };

                translator.EnsureProjectProperties();

                Assert.AreEqual(OverflowMode.Checked, translator.OverflowMode);
                Assert.AreEqual("TestProject", translator.ProjectProperties.RootNamespace);
                Assert.AreEqual("TestProject", translator.ProjectProperties.AssemblyName);
                Assert.AreEqual(Path.Combine(tmpDir, "bin", "Release", "TestProject.dll"), translator.AssemblyLocation);

                var files = translator.SourceFiles.OrderBy(s => s).ToArray();
                Assert.AreEqual("Properties\\AssemblyInfo.cs", files[0]);
                Assert.AreEqual("Test.cs", files[1]);

                var constants = translator.DefineConstants.OrderBy(c => c).ToArray();
                Assert.AreEqual("BRIDGE", constants.First(ct => ct == "BRIDGE"));
                Assert.AreEqual("TRACE", constants.First(ct => ct == "TRACE"));
            }
            finally
            {
                Directory.Delete(tmpDir, true);
            }
        }
Example #40
0
        protected void fillPageLimits(Listing_Standard listing)
        {
            DoHeading(listing, "PSI.Settings.Sensitivity.Header");

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.LoadPresetButton")))
            {
                string[] presetList = { };
                String   path2      = GenFilePaths.CoreModsFolderPath + "/Pawn State Icons/Presets/Sensitivity/";
                if (Directory.Exists(path2))
                {
                    presetList = Directory.GetFiles(path2, "*.cfg");
                }

                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (string setname in presetList)
                {
                    options.Add(new FloatMenuOption(Path.GetFileNameWithoutExtension(setname), () =>
                    {
                        try
                        {
                            ModSettings settings                 = XmlLoader.ItemFromXmlFile <ModSettings>(setname, true);
                            PSI.settings.limit_bleedMult         = settings.limit_bleedMult;
                            PSI.settings.limit_diseaseLess       = settings.limit_diseaseLess;
                            PSI.settings.limit_EfficiencyLess    = settings.limit_EfficiencyLess;
                            PSI.settings.limit_FoodLess          = settings.limit_FoodLess;
                            PSI.settings.limit_MoodLess          = settings.limit_MoodLess;
                            PSI.settings.limit_RestLess          = settings.limit_RestLess;
                            PSI.settings.limit_apparelHealthLess = settings.limit_apparelHealthLess;
                            PSI.settings.limit_tempComfortOffset = settings.limit_tempComfortOffset;
                        }
                        catch (IOException) { Log.Error(Translator.Translate("PSI.Settings.LoadPreset.UnableToLoad") + setname); }
                    }));
                }
                Find.LayerStack.Add((Layer) new Layer_FloatMenu(options, false));
            }

            listing.DoGap();

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Bleeding") + Translator.Translate("PSI.Settings.Sensitivity.Bleeding." + Math.Round(PSI.settings.limit_bleedMult - 0.25)));
            PSI.settings.limit_bleedMult = listing.DoSlider(PSI.settings.limit_bleedMult, 0.5f, 5.0f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Injured") + ((int)(PSI.settings.limit_EfficiencyLess * 100)) + "%");
            PSI.settings.limit_EfficiencyLess = listing.DoSlider(PSI.settings.limit_EfficiencyLess, 0.01f, 0.99f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Food") + ((int)(PSI.settings.limit_FoodLess * 100)) + "%");
            PSI.settings.limit_FoodLess = listing.DoSlider(PSI.settings.limit_FoodLess, 0.01f, 0.99f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Mood") + ((int)(PSI.settings.limit_MoodLess * 100)) + "%");
            PSI.settings.limit_MoodLess = listing.DoSlider(PSI.settings.limit_MoodLess, 0.01f, 0.99f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Rest") + ((int)(PSI.settings.limit_RestLess * 100)) + "%");
            PSI.settings.limit_RestLess = listing.DoSlider(PSI.settings.limit_RestLess, 0.01f, 0.99f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.ApparelHealth") + ((int)(PSI.settings.limit_apparelHealthLess * 100)) + "%");
            PSI.settings.limit_apparelHealthLess = listing.DoSlider(PSI.settings.limit_apparelHealthLess, 0.01f, 0.99f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Sensitivity.Temperature") + ((int)(PSI.settings.limit_tempComfortOffset)) + "C");
            PSI.settings.limit_tempComfortOffset = listing.DoSlider(PSI.settings.limit_tempComfortOffset, -10f, 10f);

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.ReturnButton")))
            {
                page = "main";
            }
        }
Example #41
0
        protected void fillPageMain(Listing_Standard listing)
        {
            //listing.DoHeading("General settings");

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.IconSet") + PSI.settings.iconSet))
            {
                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (string setname in PSI.iconSets)
                {
                    options.Add(new FloatMenuOption(setname, () =>
                    {
                        PSI.settings.iconSet = setname;
                        PSI.materials        = new Materials(setname);
                        PSI.materials.reloadTextures(true);
                    }));
                }
                Find.LayerStack.Add((Layer) new Layer_FloatMenu(options, false));
            }

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.LoadPresetButton")))
            {
                string[] presetList = {};
                String   path2      = GenFilePaths.CoreModsFolderPath + "/Pawn State Icons/Presets/Complete/";
                if (Directory.Exists(path2))
                {
                    presetList = Directory.GetFiles(path2, "*.cfg");
                }

                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (string setname in presetList)
                {
                    options.Add(new FloatMenuOption(Path.GetFileNameWithoutExtension(setname), () =>
                    {
                        try
                        {
                            PSI.settings = XmlLoader.ItemFromXmlFile <ModSettings>(setname, true);
                            PSI.saveSettings();
                            PSI.reinit();
                        }
                        catch (IOException) { Log.Error(Translator.Translate("PSI.Settings.LoadPreset.UnableToLoad") + setname); }
                    }));
                }
                Find.LayerStack.Add((Layer) new Layer_FloatMenu(options, false));
            }

            listing.DoGap();
            DoHeading(listing, "PSI.Settings.Advanced");

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.VisibilityButton")))
            {
                page = "showhide";
            }
            if (listing.DoTextButton(Translator.Translate("PSI.Settings.ArrangementButton")))
            {
                page = "arrange";
            }
            if (listing.DoTextButton(Translator.Translate("PSI.Settings.SensitivityButton")))
            {
                page = "limits";
            }
        }
Example #42
0
 private void DoHeading(Listing_Standard listing, String translator_key, bool translate = true)
 {
     Text.Font = GameFont.Medium;
     listing.DoLabel(translate?Translator.Translate(translator_key):translator_key);
     Text.Font = GameFont.Small;
 }
Example #43
0
        protected void fillPageArrangement(Listing_Standard listing)
        {
            DoHeading(listing, "PSI.Settings.Arrangement.Header");

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.LoadPresetButton")))
            {
                string[] presetList = { };
                String   path2      = GenFilePaths.CoreModsFolderPath + "/Pawn State Icons/Presets/Position/";
                if (Directory.Exists(path2))
                {
                    presetList = Directory.GetFiles(path2, "*.cfg");
                }

                List <FloatMenuOption> options = new List <FloatMenuOption>();
                foreach (string setname in presetList)
                {
                    options.Add(new FloatMenuOption(Path.GetFileNameWithoutExtension(setname), () =>
                    {
                        try
                        {
                            ModSettings settings          = XmlLoader.ItemFromXmlFile <ModSettings>(setname, true);
                            PSI.settings.iconDistanceX    = settings.iconDistanceX;
                            PSI.settings.iconDistanceY    = settings.iconDistanceY;
                            PSI.settings.iconOffsetX      = settings.iconOffsetX;
                            PSI.settings.iconOffsetY      = settings.iconOffsetY;
                            PSI.settings.iconsHorizontal  = settings.iconsHorizontal;
                            PSI.settings.iconsScreenScale = settings.iconsScreenScale;
                            PSI.settings.iconsInColumn    = settings.iconsInColumn;
                            PSI.settings.iconSize         = settings.iconSize;
                        }
                        catch (IOException) { Log.Error(Translator.Translate("PSI.Settings.LoadPreset.UnableToLoad") + setname); }
                    }));
                }
                Find.LayerStack.Add((Layer) new Layer_FloatMenu(options, false));
            }

            int labelNum = (int)(PSI.settings.iconSize * 4.5f);

            if (labelNum > 8)
            {
                labelNum = 8;
            }
            else if (labelNum < 0)
            {
                labelNum = 0;
            }

            listing.DoLabel(Translator.Translate("PSI.Settings.Arrangement.IconSize") + Translator.Translate("PSI.Settings.SizeLabel." + labelNum));
            PSI.settings.iconSize = listing.DoSlider(PSI.settings.iconSize, 0.5f, 2.0f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Arrangement.IconPosition") + (int)(PSI.settings.iconDistanceX * 100) + " , " + (int)(PSI.settings.iconDistanceY * 100));
            PSI.settings.iconDistanceX = listing.DoSlider(PSI.settings.iconDistanceX, -2.0f, 2.0f);
            PSI.settings.iconDistanceY = listing.DoSlider(PSI.settings.iconDistanceY, -2.0f, 2.0f);

            listing.DoLabel(Translator.Translate("PSI.Settings.Arrangement.IconOffset") + (int)(PSI.settings.iconOffsetX * 100) + " , " + (int)(PSI.settings.iconOffsetY * 100));
            PSI.settings.iconOffsetX = listing.DoSlider(PSI.settings.iconOffsetX, -2.0f, 2.0f);
            PSI.settings.iconOffsetY = listing.DoSlider(PSI.settings.iconOffsetY, -2.0f, 2.0f);
            listing.DoLabelCheckbox(Translator.Translate("PSI.Settings.Arrangement.Horizontal"), ref PSI.settings.iconsHorizontal);
            listing.DoLabelCheckbox(Translator.Translate("PSI.Settings.Arrangement.ScreenScale"), ref PSI.settings.iconsScreenScale);

            listing.DoLabel(Translator.Translate("PSI.Settings.Arrangement.IconsPerColumn") + PSI.settings.iconsInColumn);
            PSI.settings.iconsInColumn = (int)listing.DoSlider(PSI.settings.iconsInColumn, 1.0f, 9.0f);

            if (listing.DoTextButton(Translator.Translate("PSI.Settings.ReturnButton")))
            {
                page = "main";
            }
        }
Example #44
0
        public void DisarmBomb()
        {
            RemoveAfterLeave = true;

            var letter = LetterMaker.MakeLetter(Translator.Translate("SuccessDisarming"), Translator.Translate("SuccessDisarmingDesc"), LetterDefOf.PositiveEvent);

            Find.LetterStack.ReceiveLetter(letter);
        }
Example #45
0
        protected override void CreateBody()
        {
            CreateBody(Translator.GetString("What is the main purpose of this workstation?"));

            List <PurposeBase> allPurposes = new List <PurposeBase> ();

            foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/Warehouse/Presentation/SetupAssistant/Purpose"))
            {
                object      instance = node.CreateInstance();
                PurposeBase purpose  = instance as PurposeBase;
                if (purpose != null)
                {
                    allPurposes.Add(purpose);
                }
            }
            allPurposes.Sort((p1, p2) => Math.Max(-1, Math.Min(1, p1.Ordinal - p2.Ordinal)));

            HBox hbo = new HBox();

            hbo.Show();
            vboBody.PackStart(hbo, true, true, 6);

            VBox vbo = new VBox();

            vbo.Show();
            hbo.PackStart(vbo, true, true, 4);

            algImage = new Alignment(.5f, .5f, 1f, 1f)
            {
                WidthRequest = 220
            };
            algImage.Show();
            hbo.PackStart(algImage, false, true, 4);

            RadioButton group     = null;
            bool        activeSet = false;

            foreach (PurposeBase purpose in allPurposes)
            {
                Widget rbtn = purpose.GetSelectionWidget(ref group);
                rbtn.Show();
                purpose.Toggled += rbtn_Toggled;

                vbo.PackStart(rbtn, false, true, 4);
                choices.Add(purpose);

                if (activeSet)
                {
                    continue;
                }

                activeSet      = true;
                purpose.Active = true;
                rbtn_Toggled(rbtn, EventArgs.Empty);
            }

            WrapLabel footer = new WrapLabel
            {
                Markup = string.Format(Translator.GetString(
                                           "The selection here will determine the content displayed when {1} is started. To change this later please go to:{0}{2}"),
                                       Environment.NewLine,
                                       DataHelper.ProductName,
                                       new PangoStyle
                {
                    Italic = true,
                    Bold   = true,
                    Text   = Translator.GetString("Other->Settings->Special->Startup->Startup page")
                })
            };

            footer.Show();
            vboBody.PackStart(footer, true, true, 4);
        }
Example #46
0
 public void Translate()
 {
     Translator.Translate(this, AppSettings.CurrentTranslation);
 }
 public string ParseCode(Translator translator, TreeReader reader)
 {
     return("public class TENGRI_" + ClassName + " {" + translator.Emulate(Body, true, false, ClassName) + "}");
 }
Example #48
0
        public LoginViewModel()
        {
            Os_Folder          = App.Os_Folder;
            Profile            = new FacebookProfile();
            criptografia       = new Criptografia();
            OnLoginCommand     = new Command(async() => await LoginAsync());
            OnShareDataCommand = new Command(async() => await ShareDataAsync());
            OnLoadDataCommand  = new Command(async() => await LoadData());
            OnLogoutCommand    = new Command(() =>
            {
                if (CrossFacebookClient.Current.IsLoggedIn)
                {
                    CrossFacebookClient.Current.Logout();
                    IsLoggedIn = false;
                }
            });



            // if exists, loads the email to the form
            if (Application.Current.Properties.ContainsKey(Constants.persistUser))
            {
                email = (string)Application.Current.Properties[Constants.persistUser];
            }
            if (Application.Current.Properties.ContainsKey(Constants.persistPass))
            {
                password = (string)Application.Current.Properties[Constants.persistPass];
            }
            SubmitCommand = new Command(OnSubmit);



            async void OnSubmit()
            {
                using (UserDialogs.Instance.Loading(Translator.getText("Loading"), null, null, true, MaskType.Black))
                {
                    var current = Connectivity.NetworkAccess;

                    if (current == NetworkAccess.Internet)
                    {
                        if (email != null && password != null)
                        {
                            // if empty show message
                            if (email.Length == 0 || password.Length == 0)
                            {
                                DisplayInvalidLoginPrompt();
                            }
                            else
                            {
                                Profile profile = new Profile();

                                await getLoginProcess(profile, email, password, Constants.RegAP);
                            }
                        }
                        else
                        {
                            DisplayInvalidLoginEmpty();
                        }
                    }
                    else
                    {
                        App.ToastMessage(Translator.getText("NoInternet"), Color.Black, "");
                    }
                }
            }

            async Task LoginAsync()
            {
                using (UserDialogs.Instance.Loading(Translator.getText("Loading"), null, null, true, MaskType.Black))
                {
                    FacebookResponse <bool> response = await CrossFacebookClient.Current.LoginAsync(permisions);

                    switch (response.Status)
                    {
                    case FacebookActionStatus.Completed:
                        IsLoggedIn = true;
                        OnLoadDataCommand.Execute(null);
                        break;

                    case FacebookActionStatus.Canceled:

                        break;

                    case FacebookActionStatus.Unauthorized:
                        await Application.Current.MainPage.DisplayAlert("Unauthorized", response.Message, "Ok");

                        break;

                    case FacebookActionStatus.Error:
                        await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Ok");

                        break;
                    }
                }
            }

            async Task ShareDataAsync()
            {
                FacebookShareLinkContent linkContent = new FacebookShareLinkContent("Awesome team of developers, making the world a better place one project or plugin at the time!",
                                                                                    new Uri("http://www.github.com/crossgeeks"));
                var ret = await CrossFacebookClient.Current.ShareAsync(linkContent);
            }

            async Task LoadData()
            {
                using (UserDialogs.Instance.Loading(Translator.getText("Loading"), null, null, true, MaskType.Black))
                {
                    var jsonData = await CrossFacebookClient.Current.RequestUserDataAsync
                                   (
                        new string[] { "id", "name", "email", "picture", "cover", "friends" }, new string[] { }
                                   );

                    var data = JObject.Parse(jsonData.Data);
                    Profile = new FacebookProfile()
                    {
                        FullName = data["name"].ToString(),
                        Picture  = new UriImageSource {
                            Uri = new Uri($"{data["picture"]["data"]["url"]}")
                        },
                        Email = data["email"].ToString()
                    };

                    Profile profile = new Profile()
                    {
                        FirstName = data["name"].ToString(),
                        Picture   = data["picture"]["data"]["url"].ToString(),
                        Email     = data["email"].ToString(),
                        Token     = Profile.Token
                    };


                    await getLoginProcess(profile, profile.Email, criptografia.encryptar(profile.Email, Constants.AppCode), Constants.RegFB);
                }
            }
        }
        public static Translator GetTranslator(string culture)
        {
            Translator t = new Translator(culture);

            return(t);// GlobalLanguageService.Instance.Translator[culture].ToObject<JObject>();
        }
Example #50
0
 // Token: 0x06000064 RID: 100 RVA: 0x00006618 File Offset: 0x00004818
 public override string CompInspectStringExtra()
 {
     if (CamoUtility.IsCamoActive(this.Pawn, out Apparel apparel))
     {
         if (apparel != null)
         {
             float  activeCamoEff = ThingCompUtility.TryGetComp <CompGearCamo>(apparel).Props.ActiveCamoEff;
             string text          = Translator.Translate("CompCamo.Active");
             if (ThingCompUtility.TryGetComp <CompGearCamo>(apparel).Props.StealthCamoChance > 0 && activeCamoEff > 0f)
             {
                 text = Translator.Translate("CompCamo.Stealth");
             }
             return(TranslatorFormattedStringExtensions.Translate("CompCamo.CamouflageDesc", text, GenText.ToStringPercent(activeCamoEff)));
         }
     }
     else if (CamoGearUtility.GetCurCamoEff(this.Pawn, out string a, out float num))
     {
         string text2 = Translator.Translate("CompCamo.Undefined");
         if (!(a == "Arctic"))
         {
             if (!(a == "Desert"))
             {
                 if (!(a == "Jungle"))
                 {
                     if (!(a == "Stone"))
                     {
                         if (!(a == "Urban"))
                         {
                             if (a == "Woodland")
                             {
                                 text2 = Translator.Translate("CompCamo.Woodland");
                             }
                         }
                         else
                         {
                             text2 = Translator.Translate("CompCamo.Urban");
                         }
                     }
                     else
                     {
                         text2 = Translator.Translate("CompCamo.Stone");
                     }
                 }
                 else
                 {
                     text2 = Translator.Translate("CompCamo.Jungle");
                 }
             }
             else
             {
                 text2 = Translator.Translate("CompCamo.Desert");
             }
         }
         else
         {
             text2 = Translator.Translate("CompCamo.Arctic");
         }
         return(TranslatorFormattedStringExtensions.Translate("CompCamo.CamouflageDesc", text2, GenText.ToStringPercent(num)));
     }
     return(null);
 }
        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            if ((this.Airliner.HasRoute && this.Airliner.Status == FleetAirliner.AirlinerStatus.Stopped) || !this.Airliner.HasRoute)
            {
                AirlinerFacilityItem item = (AirlinerFacilityItem)((Button)sender).Tag;

                AirlinerFacility facility = (AirlinerFacility)PopUpAirlinerFacility.ShowPopUp(item.AirlinerClass, item.Facility.Type);

                if (facility != null && item.AirlinerClass.getFacility(item.Facility.Type) != facility)
                {
                    if (facility.Type == AirlinerFacility.FacilityType.Seat)
                    {
                        item.AirlinerClass.SeatingCapacity = Convert.ToInt16(Convert.ToDouble(item.AirlinerClass.RegularSeatingCapacity) / facility.SeatUses);
                    }

                    item.AirlinerClass.setFacility(GameObject.GetInstance().HumanAirline, facility);

                    showFacilities();
                }
            }
            else
            {
                WPFMessageBox.Show(Translator.GetInstance().GetString("MessageBox", "2301"), Translator.GetInstance().GetString("MessageBox", "2301", "message"), WPFMessageBoxButtons.Ok);
            }
        }
        private void InitializeSecondGrid ()
        {
            if (secondGrid == null) {
                secondGrid = new ListView { Name = "secondGrid" };

                ScrolledWindow sWindow = new ScrolledWindow { HscrollbarPolicy = PolicyType.Automatic, VscrollbarPolicy = PolicyType.Automatic };
                sWindow.Add (secondGrid);

                algSecondGrid.Add (sWindow);
                sWindow.Show ();
                secondGrid.Show ();
            }

            ColumnController cc = new ColumnController ();

            CellText ct = new CellText ("ItemName");
            colSecondItem = new Column (Translator.GetString ("Item"), ct, 1);
            cc.Add (colSecondItem);

            CellTextQuantity ctq = new CellTextQuantity ("Quantity");
            colSecondQuantity = new Column (Translator.GetString ("Qtty"), ctq, 0.1) { MinWidth = 70 };
            cc.Add (colSecondQuantity);

            if (!BusinessDomain.LoggedUser.HideItemsPurchasePrice) {
                CellTextCurrency ctc = new CellTextCurrency ("PriceIn", PriceType.Purchase);
                colSecondPurchaseValue = new Column (Translator.GetString ("Purchase price"), ctc, 0.1) {MinWidth = 70};
                cc.Add (colSecondPurchaseValue);
            }

            if (BusinessDomain.AppConfiguration.AllowItemLotName) {
                ct = new CellText ("Lot");
                colSecondLot = new Column (Translator.GetString ("Lot"), ct, 0.1) { MinWidth = 70 };
                cc.Add (colSecondLot);
            }

            if (BusinessDomain.AppConfiguration.AllowItemSerialNumber) {
                ct = new CellText ("SerialNumber");
                colSecondSerialNo = new Column (Translator.GetString ("Serial number"), ct, 0.1) { MinWidth = 80 };
                cc.Add (colSecondSerialNo);
            }

            CellTextDate ctd;
            if (BusinessDomain.AppConfiguration.AllowItemExpirationDate) {
                ctd = new CellTextDate ("ExpirationDate");
                colSecondExpirationDate = new Column (Translator.GetString ("Expiration date"), ctd, 0.1) { MinWidth = 70 };
                cc.Add (colSecondExpirationDate);
            }

            if (BusinessDomain.AppConfiguration.AllowItemManufacturedDate) {
                ctd = new CellTextDate ("ProductionDate");
                colSecondProductionDate = new Column (Translator.GetString ("Production date"), ctd, 0.1) { MinWidth = 70 };
                cc.Add (colSecondProductionDate);
            }

            if (BusinessDomain.AppConfiguration.AllowItemLocation) {
                ct = new CellText ("LotLocation");
                colSecondLotLocation = new Column (Translator.GetString ("Lot location"), ct, 0.1) { MinWidth = 70 };
                cc.Add (colSecondLotLocation);
            }

            secondGrid.ColumnController = cc;
            secondGrid.AllowSelect = false;
            secondGrid.CellsFucusable = true;
            secondGrid.ManualFucusChange = true;
            secondGrid.RulesHint = true;
        }
 // Token: 0x06000055 RID: 85 RVA: 0x000033E0 File Offset: 0x000015E0
 public override string TransformLabel(string label)
 {
     return(base.TransformLabel(label) + " " + (this.operatingAtHighPower ? Translator.Translate("HeatedFloor_HighPower") : Translator.Translate("HeatedFloor_LowPower")));
 }
        private void ExecuteSearch()
        {
            _matchingItems.Clear();
            _displayItems.Clear();
            _listViewItems.Clear();
            lvResults.Items.Clear();

            if (_shouldCancelSearch.WaitOne(0))
            {
                return;
            }

            try
            {
                UseWaitCursor = true;

                pbProgress.Maximum = 1;
                pbProgress.Value   = 0;
                pbProgress.Visible = true;

                ssStatus.Text = Translator.Translate("TXT_INIT_SEARCH");
                Application.DoEvents();

                bool needFolderLookup =
                    (theTask.UseAttributes == true) && ((theTask.Attributes & FileAttributes.Directory) == FileAttributes.Directory);

                string actualSearchPattern = theTask.SearchPattern;
                if (theTask.SearchPattern == Translator.Translate("TXT_SEARCH_BOOKMARKS"))
                {
                    actualSearchPattern = "*.bmk";
                    needFolderLookup    = false;
                }
                else if (theTask.SearchPattern == Translator.Translate("TXT_SEARCH_MEDIAFILES"))
                {
                    needFolderLookup    = false;
                    actualSearchPattern = MediaRenderer.AllMediaTypesMultiFilter;
                }

                List <string> fsEntries = new List <string>();

                SearchOption searchOption = theTask.IsRecursive ?
                                            SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

                if (needFolderLookup)
                {
                    List <string> subdirs = PathUtils.EnumDirectoriesUsingMultiFilter(_shouldCancelSearch,
                                                                                      theTask.SearchPath, actualSearchPattern, searchOption);
                    if (subdirs != null)
                    {
                        fsEntries.AddRange(subdirs);
                    }
                }

                List <string> files = PathUtils.EnumFilesUsingMultiFilter(_shouldCancelSearch,
                                                                          theTask.SearchPath, actualSearchPattern, searchOption);
                if (files != null)
                {
                    fsEntries.AddRange(files);
                }

                pbProgress.Maximum = fsEntries.Count + 1;

                foreach (string fsi in fsEntries)
                {
                    if (_shouldCancelSearch.WaitOne(0))
                    {
                        return;
                    }

                    if (TestFolder(fsi) == false)
                    {
                        TestFile(fsi);
                    }

                    ssStatus.Text    = fsi;
                    pbProgress.Value = pbProgress.Value + 1;
                    Application.DoEvents();
                }

                _displayItems.Sort();

                foreach (string str in _displayItems)
                {
                    CreateListViewItem(str);
                }
            }
            catch (Exception ex)
            {
                ssStatus.Text = ex.Message;
            }
            finally
            {
                lvResults.Items.AddRange(_listViewItems.ToArray());

                if (lvResults.Items.Count > 0)
                {
                    ssStatus.Text = Translator.Translate("TXT_TOTAL_ITEMS_FOUND", lvResults.Items.Count);
                }
                else
                {
                    ssStatus.Text = Translator.Translate("TXT_NO_ITEMS_FOUND");
                }

                pbProgress.Visible = false;
                UseWaitCursor      = false;

                GC.Collect();
            }
        }
Example #55
0
 public CpuContext(MemoryManager memory)
 {
     _translator = new Translator(new JitMemoryAllocator(), memory);
 }
Example #56
0
 public void DoListShiftButton(Rect rect)
 {
     TooltipHandler.TipRegion(rect, this.ColonistOrAnimal ? Translator.Translate("LvTab_Colonist") : Translator.Translate("LvTab_Animal"));
     if (Widgets.ButtonText(rect, this.ColonistOrAnimal ? Translator.Translate("LvTab_Colonist") : Translator.Translate("LvTab_Animal")))
     {
         this.ColonistOrAnimal = !this.ColonistOrAnimal;
         Notify_ResolutionChanged();
     }
 }
 protected override void OnCreateHiddenButton(HiddenButtonWrapper buttonWrapper)
 {
     buttonWrapper.HiddenButton.PopupCaption = Translator.Translate(Define.DefaultCulture, "正在传阅...");
 }
Example #58
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
                {
                    Hash128 key = guestProgramList[programIndex];

                    Logger.Info?.Print(LogClass.Gpu, $"Compiling shader {key} ({programIndex + 1} / {guestProgramList.Length})");

                    byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                    bool   hasHostCache      = hostProgramBinary != null;

                    IProgram hostProgram = null;

                    // If the program sources aren't in the cache, compile from saved guest program.
                    byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                    if (guestProgram == null)
                    {
                        Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                        // Should not happen, but if someone messed with the cache it's better to catch it.
                        invalidEntries?.Add(key);

                        continue;
                    }

                    ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                    ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                    if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                    {
                        Debug.Assert(cachedShaderEntries.Length == 1);

                        GuestShaderCacheEntry entry = cachedShaderEntries[0];

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        ShaderProgram     program;
                        ShaderProgramInfo shaderProgramInfo;

                        // Reconstruct code holder.
                        if (isHostProgramValid)
                        {
                            program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                            shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
                        }
                        else
                        {
                            IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                            program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
                        }

                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (hostProgram == null)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            // Compile shader and create program as the shader program binary got invalidated.
                            shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
                            hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
                    }
                    else
                    {
                        Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                        ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                        List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                        TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformationFeedbackInformations(ref guestProgramReadOnlySpan, fileHeader);

                        TranslationFlags flags = DefaultFlags;

                        if (tfd != null)
                        {
                            flags = TranslationFlags.Feedback;
                        }

                        TranslationCounts counts = new TranslationCounts();

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        // Reconstruct code holder.
                        for (int i = 0; i < cachedShaderEntries.Length; i++)
                        {
                            GuestShaderCacheEntry entry = cachedShaderEntries[i];

                            if (entry == null)
                            {
                                continue;
                            }

                            ShaderProgram program;

                            if (entry.Header.SizeA != 0)
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext((ulong)entry.Header.Size, 0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                // NOTE: Vertex B comes first in the shader cache.
                                byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                            }
                            else
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                            }

                            shaderPrograms.Add(program);
                        }

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (!isHostProgramValid)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            List <IShader> hostShaders = new List <IShader>();

                            // Compile shaders and create program as the shader program binary got invalidated.
                            for (int stage = 0; stage < Constants.ShaderStages; stage++)
                            {
                                ShaderProgram program = shaders[stage]?.Program;

                                if (program == null)
                                {
                                    continue;
                                }

                                IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                                shaders[stage].HostShader = hostShader;

                                hostShaders.Add(hostShader);
                            }

                            hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                Logger.Info?.Print(LogClass.Gpu, "Shader cache loaded.");
            }
        }
        private void OnSettingsChanged(object sender, EventArgs e)
        {
            if (!enableEvents)
            {
                return;
            }

            try
            {
                enableEvents = false;

                if (sender == txtSearchPath)
                {
                    if (txtSearchPath.Text == Translator.Translate("TXT_BROWSE"))
                    {
                        return;
                    }
                    else
                    {
                        theTask.SearchPath = txtSearchPath.Text;

                        //cmbSearchPath.SelectedItem = null;
                        //cmbSearchPath.AddUniqueItem(theTask.SearchPath.ToLowerInvariant());
                        //cmbSearchPath.SelectedItem = theTask.SearchPath.ToLowerInvariant();
                    }
                }

                if (SearchBookmarksActive())
                {
                    chkOption1.Visible = true; chkOption2.Visible = true;
                    chkOption1.Text    = Translator.Translate("TXT_NON_ORPHAN_BOOKMARKS");
                    chkOption2.Text    = Translator.Translate("TXT_ORPHAN_BOOKMARKS");
                }
                else if (SearchMediaFilesActive())
                {
                    chkOption1.Visible = true; chkOption2.Visible = true;
                    chkOption1.Text    = Translator.Translate("TXT_MEDIA_WITH_BOOKMARKS");
                    chkOption2.Text    = Translator.Translate("TXT_MEDIA_WITHOUT_BOOKMARKS");
                }
                else
                {
                    chkOption1.Visible = false; chkOption2.Visible = false;
                }

                lbAttributes.Height  = (chkAttrSearch.Checked ? 73 : 0);
                lbAttributes.Visible = chkAttrSearch.Checked;
                lbAttributes.Enabled = chkAttrSearch.Checked;

                theTask.SearchPattern = cmbSearchPattern.Text;
                theTask.SearchText    = cmbSearchText.Text;
                theTask.SearchPath    = txtSearchPath.Text;

                theTask.IsCaseInsensitive = chkNoCase.Checked;
                theTask.IsRecursive       = chkRecursive.Checked;
                theTask.UseAttributes     = chkAttrSearch.Checked;

                theTask.SearchProperties = chkPropSearch.Checked;
            }
            finally
            {
                enableEvents = true;
            }
        }
Example #60
0
        internal static void MakeAndSaveTranslations(ConcurrentDictionary <ulong, TranslatedFunction> funcs, IMemoryManager memory, JumpTable jumpTable)
        {
            var profiledFuncsToTranslate = PtcProfiler.GetProfiledFuncsToTranslate(funcs);

            if (profiledFuncsToTranslate.Count == 0)
            {
                ResetMemoryStreamsIfNeeded();
                PtcJumpTable.ClearIfNeeded();

                GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;

                return;
            }

            _translateCount = 0;

            ThreadPool.QueueUserWorkItem(TranslationLogger, profiledFuncsToTranslate.Count);

            void TranslateFuncs()
            {
                while (profiledFuncsToTranslate.TryDequeue(out var item))
                {
                    ulong address = item.address;

                    Debug.Assert(PtcProfiler.IsAddressInStaticCodeRange(address));

                    TranslatedFunction func = Translator.Translate(memory, jumpTable, address, item.mode, item.highCq);

                    bool isAddressUnique = funcs.TryAdd(address, func);

                    Debug.Assert(isAddressUnique, $"The address 0x{address:X16} is not unique.");

                    if (func.HighCq)
                    {
                        jumpTable.RegisterFunction(address, func);
                    }

                    Interlocked.Increment(ref _translateCount);

                    if (State != PtcState.Enabled)
                    {
                        break;
                    }
                }

                Translator.DisposePools();
            }

            int maxDegreeOfParallelism = (Environment.ProcessorCount * 3) / 4;

            List <Thread> threads = new List <Thread>();

            for (int i = 0; i < maxDegreeOfParallelism; i++)
            {
                Thread thread = new Thread(TranslateFuncs);
                thread.IsBackground = true;

                threads.Add(thread);
            }

            threads.ForEach((thread) => thread.Start());
            threads.ForEach((thread) => thread.Join());

            threads.Clear();

            _loggerEvent.Set();

            PtcJumpTable.Initialize(jumpTable);

            PtcJumpTable.ReadJumpTable(jumpTable);
            PtcJumpTable.ReadDynamicTable(jumpTable);

            Thread preSaveThread = new Thread(PreSave);

            preSaveThread.IsBackground = true;
            preSaveThread.Start();
        }