Example #1
0
        static void Main(string[] args)
        {
            foreach( var inputFileName in Directory.EnumerateFiles(".", "*.in") )
            {
                var outputFileName = Path.ChangeExtension(inputFileName, ".out");

                Console.WriteLine("Solving {0}...", inputFileName);
                var inputFile = new InputFile(inputFileName);

                using( var outputFile = new OutputFile(outputFileName))
                {
                    foreach (var testCase in inputFile)
                    {
                        Console.WriteLine("TestCase: {0}", testCase);

                        var newSentence = string.Join(" ", testCase.Sentence.Split(' ').Reverse());

                        var testResult = new TestResult(newSentence);

                        Console.WriteLine("TestResult: {0}", testResult);

                        outputFile.Add(testResult);
                    }
                }
                Console.WriteLine("Solving {0}... done", inputFileName);
            }

            Console.WriteLine("-- PRESS ENTER TO CLOSE --");
            Console.ReadLine();
        }
Example #2
0
        static void Main(string[] args)
        {
            //Console.Write("Enter file path: ");
            //var path = Console.ReadLine();

            var inputPath = "c:/data.csv";
            var inputFile = new InputFile(inputPath);

            var outputPath = "C:\\Users\\Ryan\\Desktop\\output.csv";
            var calls = inputFile.GetFileCalls();
            var outputFile = new OutputFile(calls, outputPath);
            outputFile.WriteFile();
            Console.WriteLine("Saved file with {0} lines", calls.Count);

            Console.WriteLine("\nPress any key to quit...");
            Console.ReadLine();
        }
Example #3
0
        private void ProcessFile(string path, Stream stream)
        {
            var resource = new Resource();

            try
            {
                resource.Read(stream);

                string extension = Path.GetExtension(path);

                if (extension.EndsWith("_c", StringComparison.Ordinal))
                {
                    extension = extension.Substring(0, extension.Length - 2);
                }

                // Verify that extension matches resource type
                if (resource.ResourceType != ResourceType.Unknown)
                {
                    var type      = typeof(ResourceType).GetMember(resource.ResourceType.ToString()).First();
                    var attribute = "." + ((ExtensionAttribute)type.GetCustomAttributes(typeof(ExtensionAttribute), false).First()).Extension;

                    if (attribute != extension)
                    {
                        throw new Exception(string.Format("Mismatched resource type and file extension. ({0} != expected {1})", attribute, extension));
                    }
                }

                if (CollectStats)
                {
                    string id   = string.Format("{0}_{1}", resource.ResourceType, resource.Version);
                    string info = string.Empty;

                    switch (resource.ResourceType)
                    {
                    case ResourceType.Texture:
                        var texture = (Texture)resource.Blocks[BlockType.DATA];
                        info = texture.Format.ToString();
                        texture.GenerateBitmap();
                        break;

                    case ResourceType.Sound:
                        info = ((Sound)resource.Blocks[BlockType.DATA]).Type.ToString();
                        break;

                    case ResourceType.Particle:
                        var particle        = new ParticleSystem(resource);
                        var particleClasses =
                            particle.GetEmitters()
                            .Concat(particle.GetRenderers())
                            .Concat(particle.GetOperators())
                            .Concat(particle.GetInitializers())
                            .Select(r => r.GetProperty <string>("_class"));

                        foreach (var particleClass in particleClasses)
                        {
                            uniqueParticleClasses.TryGetValue(particleClass, out var currentCount);
                            uniqueParticleClasses[particleClass] = currentCount + 1;
                        }

                        break;
                    }

                    if (info != string.Empty)
                    {
                        id = string.Concat(id, "_", info);
                    }

                    lock (stats)
                    {
                        if (stats.ContainsKey(id))
                        {
                            if (stats[id].Count++ < 10)
                            {
                                stats[id].FilePaths.Add(path);
                            }
                        }
                        else
                        {
                            stats.Add(id, new ResourceStat(resource, info, path));
                        }
                    }

                    if (resource.EditInfo != null && resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies))
                    {
                        lock (uniqueSpecialDependancies)
                        {
                            foreach (var dep in ((ValveResourceFormat.Blocks.ResourceEditInfoStructs.SpecialDependencies)resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]).List)
                            {
                                uniqueSpecialDependancies[string.Format("{0} \"{1}\"", dep.CompilerIdentifier, dep.String)] = path;
                            }
                        }
                    }

                    foreach (var block in resource.Blocks)
                    {
                        block.Value.ToString();
                    }
                }

                if (OutputFile != null)
                {
                    byte[] data;

                    switch (resource.ResourceType)
                    {
                    case ResourceType.Panorama:
                        data = ((Panorama)resource.Blocks[BlockType.DATA]).Data;
                        break;

                    case ResourceType.Sound:
                        var sound = (Sound)resource.Blocks[BlockType.DATA];

                        switch (sound.Type)
                        {
                        case Sound.AudioFileType.MP3:
                            extension = "mp3";
                            break;

                        case Sound.AudioFileType.WAV:
                            extension = "wav";
                            break;
                        }

                        data = sound.GetSound();

                        break;

                    case ResourceType.Texture:
                        extension = "png";

                        var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap();
                        var image  = SKImage.FromBitmap(bitmap);

                        using (var ms = new MemoryStream())
                        {
                            using (var imageData = image.Encode(SKEncodedImageFormat.Png, 100))
                            {
                                imageData.SaveTo(ms);
                            }

                            data = ms.ToArray();
                        }

                        break;

                    case ResourceType.Particle:
                    case ResourceType.Mesh:
                        //Wrap it around a KV3File object to get the header.
                        data = Encoding.UTF8.GetBytes(((BinaryKV3)resource.Blocks[BlockType.DATA]).GetKV3File().ToString());
                        break;

                    //These all just use ToString() and WriteText() to do the job
                    case ResourceType.SoundEventScript:
                        data = Encoding.UTF8.GetBytes(resource.Blocks[BlockType.DATA].ToString());
                        break;

                    default:
                        Console.WriteLine("-- (I don't know how to dump this resource type)");
                        return;
                    }

                    var filePath = Path.ChangeExtension(path, extension);

                    if (RecursiveSearch)
                    {
                        // I bet this is prone to breaking, is there a better way?
                        filePath = filePath.Remove(0, InputFile.TrimEnd(Path.DirectorySeparatorChar).Length + 1);
                    }
                    else
                    {
                        filePath = Path.GetFileName(filePath);
                    }

                    DumpFile(filePath, data);
                }
            }
            catch (Exception e)
            {
                File.AppendAllText("exceptions.txt", string.Format("---------------\nFile: {0}\nException: {1}\n\n", path, e));

                lock (ConsoleWriterLock)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine(e);
                    Console.ResetColor();
                }
            }

            if (CollectStats)
            {
                return;
            }

            //Console.WriteLine("\tInput Path: \"{0}\"", args[fi]);
            //Console.WriteLine("\tResource Name: \"{0}\"", "???");
            //Console.WriteLine("\tID: {0:x16}", 0);

            lock (ConsoleWriterLock)
            {
                // Highlight resource type line if undetermined
                if (resource.ResourceType == ResourceType.Unknown)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                }

                Console.WriteLine("\tResource Type: {0} [Version {1}] [Header Version: {2}]", resource.ResourceType, resource.Version, resource.HeaderVersion);
                Console.ResetColor();
            }

            Console.WriteLine("\tFile Size: {0} bytes", resource.FileSize);
            Console.WriteLine(Environment.NewLine);

            if (resource.Blocks.ContainsKey(BlockType.RERL))
            {
                Console.WriteLine("--- Resource External Refs: ---");
                Console.WriteLine("\t{0,-16}  {1,-48}", "Id:", "Resource Name:");

                foreach (var res in resource.ExternalReferences.ResourceRefInfoList)
                {
                    Console.WriteLine("\t{0:X16}  {1,-48}", res.Id, res.Name);
                }
            }
            else
            {
                Console.WriteLine("--- (No External Resource References Found)");
            }

            Console.WriteLine(Environment.NewLine);

            if (false)
            {
                // TODO: Resource Deferred Refs:
            }
            else
            {
                Console.WriteLine("--- (No Deferred Resource References Found)");
            }

            Console.WriteLine(Environment.NewLine);

            Console.WriteLine("--- Resource Blocks: Count {0} ---", resource.Blocks.Count);

            foreach (var block in resource.Blocks)
            {
                Console.WriteLine("\t-- Block: {0,-4}  Size: {1,-6} bytes [Offset: {2,6}]", block.Key, block.Value.Size, block.Value.Offset);
            }

            if (PrintAllBlocks || !string.IsNullOrEmpty(BlockToPrint))
            {
                Console.WriteLine(Environment.NewLine);

                foreach (var block in resource.Blocks)
                {
                    if (!PrintAllBlocks && BlockToPrint != block.Key.ToString())
                    {
                        continue;
                    }

                    Console.WriteLine("--- Data for block \"{0}\" ---", block.Key);
                    Console.WriteLine(block.Value);
                }
            }
        }
Example #4
0
        // Daily Sales button creates daily sales report and stores in Text file.
        private void DailySalesReportButton_Click(object sender, EventArgs e)
        {
            //Local variable declaration.
            double TotalPriceValue = 0;
            string today           = GetDateTime.ToString("dd-MM-yy");

            int[,] SoldItemArray = new int[14, 5];
            //an object of straemreader is created.
            StreamReader InputFile;

            // code to Open the stockFile.
            InputFile = File.OpenText("StockFile.txt");
            //code which uses Loop to read from file and stores in array.
            for (int i = 0; i < 14; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    DefaultStock[i, j] = int.Parse(InputFile.ReadLine());
                }
            }
            InputFile.Close();
            //code to find out the daily sales of item and stored in SoldItem array.
            for (int i = 0; i < 14; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    SoldItemArray[i, j] = DefaultStock[i, j] - TempStockArray[i, j];
                }
            }

            // object of StreamWriter class is created to write to the file.
            StreamWriter OutputFile = File.CreateText(today + "DailyTranscationReport.txt");

            OutputFile.WriteLine("Beer Palace Sales Report -- Daily salses \nTime Stamp --- " + GetDateTime);
            OutputFile.Write("\t\t\t\t\t");
            for (int k = 0; k <= 4; k++)
            {
                if (k == 1)
                {
                    OutputFile.Write(BeerSizeArray[k] + "\t\t");
                }

                else if (k == 3)
                {
                    OutputFile.Write("\t" + BeerSizeArray[k] + "\t\t");
                }
                else
                {
                    OutputFile.Write(BeerSizeArray[k] + "\t");
                }
            }
            OutputFile.Write("\tSale Value");
            for (int x = 0; x < 14; x++)
            {
                double saleperitem = 0;
                OutputFile.WriteLine();
                if (x == 1 || x == 4 || x == 8 || x == 10)
                {
                    OutputFile.Write(BeerNameArray[x] + "\t\t");
                }
                else if (x == 2 || x == 5 || x == 0 || x == 7 || x == 11 || x == 13)
                {
                    OutputFile.Write(BeerNameArray[x] + "\t\t\t");
                }
                else if (x == 3 || x == 9)
                {
                    OutputFile.Write(BeerNameArray[x] + "\t");
                }
                else if (x == 6)
                {
                    OutputFile.Write(BeerNameArray[x] + "\t\t\t\t");
                }


                else
                {
                    OutputFile.Write(BeerNameArray[x] + "\t\t\t\t");
                }

                for (int y = 0; y <= 4; y++)
                {
                    OutputFile.Write("\t" + SoldItemArray[x, y].ToString() + "\t\t");
                    if (SoldItemArray[x, y] != 0)
                    {
                        TotalPriceValue += SoldItemArray[x, y] * PriceArray[x, y];
                    }
                    else
                    {
                        TotalPriceValue += 0;
                    }
                    saleperitem += SoldItemArray[x, y] * PriceArray[x, y];
                }
                OutputFile.Write("\t\t" + saleperitem);
            }
            OutputFile.WriteLine("\n" + "Total Sold Price :" + CURRENCY + TotalPriceValue);
            OutputFile.Close();
            MessageBox.Show("Sale Report generated for today", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /*// Use ExchangeSharpApi to display all Fills for a specified exchange for the past month (31 days)
         * private void DisplayFills(string exchange, DateTime? afterDate = null)
         *      {
         *  //DateTime? afterDate = new DateTime(2018, 5, 26);
         *  if (afterDate == null)
         *  {
         *      var now = DateTime.Now;
         *      var dt = now.Subtract(TimeSpan.FromDays(31));
         *      afterDate = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, DateTimeKind.Utc);
         *  }
         *
         *  Console.Write("Getting completed orders...");
         *              //var orders = m_api[exchange].GetCompletedOrderDetails(null, afterDate);
         *  var orders = m_api[exchange].GetCompletedOrderDetails();
         *  //var orders = m_api[exchange].GetOpenOrderDetails(null);
         *
         *  Console.WriteLine("Done.");
         *  orders.ToList().ForEach(o => Console.WriteLine("{0} {1}", o.OrderDate.ToLocalTime(), o));
         *
         *  var query = orders.GroupBy(o => new DateTime(o.OrderDate.Year, o.OrderDate.Month, o.OrderDate.Day));
         *  foreach (var dayGroup in query)
         *  {
         *      var fills = dayGroup.Where(o => o.Result == ExchangeAPIOrderResult.Filled || o.Result == ExchangeAPIOrderResult.FilledPartially);
         *      //fills.ToList().ForEach(o => Console.WriteLine(o));
         *
         *      int count = 0;
         *      if (fills.Count() > 0)
         *      {
         *          Console.WriteLine("---------------------------------- {0} ----------------------------------", dayGroup.Key.ToString("yyyy MMM-dd"));
         *          fills.ToList().ForEach(o => Console.WriteLine("{0, 3} {1}", ++count, o));
         *          Console.WriteLine("");
         *      }
         *  }
         *  //var d = dt1;
         *  //for (int d = 1; d <= 31; ++d)
         *  //{
         *  //    var dt1 = new DateTime(2018, m, d, 0, 0, 0, DateTimeKind.Utc);
         *  //    var dt2 = dt1.AddDays(1.0);
         *  //    //Console.WriteLine("{0}   {1}", dt1, dt2);
         *  //    var fills = orders.Where(o => o.Result == ExchangeAPIOrderResult.Filled || o.Result == ExchangeAPIOrderResult.FilledPartially)
         *  //                      .Where(o => o.OrderDate >= dt1 && o.OrderDate < dt2);
         *  //    //fills.ToList().ForEach(o => Console.WriteLine(o));
         *
         *  //    int count = 0;
         *  //    if (fills.Count() > 0)
         *  //    {
         *  //        Console.WriteLine("---------------------------------- {0} ----------------------------------", dt1.ToString("yyyy MMM-dd"));
         *  //        fills.ToList().ForEach(o => Console.WriteLine("{0, 3} {1}", ++count, o));
         *  //        Console.WriteLine("");
         *  //    }
         *  //}
         *      }*/

        private void ReadTradeSymbols(bool force = false)
        {
            if (m_tradeSymbols != null && force != true)
            {
                return;
            }

            Console.WriteLine("--- Reading trade symbols:");

            // Read symbols and symbol-related data from file
            using (var fin = new InputFile <TradeSymbolRawCsvRecord>("marketmaker_xsymbols", Folder.misc_folder))
            {
                m_tradeSymbols = fin.ReadAll().ToList();
            }

            /*// Reverse the coins within each symbol name ("XXX-YYY" => "YYY-XXX")
             * // I use this because the ExchangeSharp API seems to have a problem keeping its symbol order consistent!
             * // TODO: Look into fixing this at the ExchangeSharp level
             * foreach (var rec in m_tradeSymbols)
             * {
             *  var gs = rec.GlobalSymbol;
             *  var split = gs.Split('-');
             *  rec.GlobalSymbol = split[1] + "-" + split[0];
             * }
             * using (var fout = new OutputFile<TradeSymbolRawCsvRecord>("marketmaker_xsymbols_reverse", Folder.misc_folder))
             * {
             *  fout.WriteAll(m_tradeSymbols);
             * }*/

            m_activeTradeSymbols = new List <TradeSymbolRawCsvRecord>();

            int activeCount = 0;

            foreach (var ts in m_tradeSymbols)
            {
                if (ts.InitialSide != 0 && ts.Amount != 0)
                {
                    Console.WriteLine("[{0,-9} {1,9}]  init_side:{2} size:{3}", ts.Exchange, ts.GlobalSymbol, ts.InitialSide, ts.Amount);
                    m_activeTradeSymbols.Add(ts);
                    ++activeCount;
                }
            }
            Console.WriteLine("--- {0} active out of {1} symbols.", activeCount, m_tradeSymbols.Count);

            /*m_xsymbols = new List<ExchangeSymbol>();
             *
             * Console.WriteLine("--- Reading trade symbols:");
             *
             * int count = 0, activeCount = 0;
             * using (var fin = new InputFile<TradeSymbolRawCsvRecord>("marketmaker_xsymbols", Folder.misc_folder))
             * {
             *      string line;
             *      while ((line = fin.ReadLine()) != null)
             *      {
             *              if (string.IsNullOrWhiteSpace(line)) continue;
             *              var split = line.Split(',');
             *              bool active = bool.Parse(split[0]); //  (split[0] == "1" ? true : false);
             *              var exchange = split[1];
             *              var gsymbol = split[2];
             *              var amount = decimal.Parse(split[3]);
             *              var xs = GetExchangeSymbol(gsymbol);
             *              if (active)
             *              {
             *                      Console.WriteLine("[{0,-9} {1,9}]  size:{2}", xs.Exchange, xs.Symbol, amount);
             *                      m_xsymbols.Add(xs);
             ++activeCount;
             *              }
             ++count;
             *      }
             * }
             * Console.WriteLine("--- {0} active out of {1} symbols.", activeCount, count);*/
        }
Example #6
0
 public void MyClassInitialize()
 {
     _she = new InputFile(@"..\..\..\PFS\unittest\TestData\TestModel.she");
 }
Example #7
0
 // no pre-processing required
 public Task PreProcessAsync(InputFile file) => Task.CompletedTask;
Example #8
0
 public virtual void ParsePayload(InputFile file, ulong position)
 {
 }
Example #9
0
 public ReadTo()
 {
     fileContent = TestData.InputFileContent;
     inputStream = TestData.GenerateStream(fileContent);
     inputFile   = new InputFile(inputStream);
 }
Example #10
0
        public HbsCSharpScaffoldingGeneratorTests(NorthwindDbContextFixture fixture)
        {
            Fixture = fixture;
            Fixture.Initialize(useInMemory: false);

            var projectRootDir = Path.Combine("..", "..", "..", "..", "..");

            var contextTemplatesVirtualPath =
                $"{Constants.Templates.CodeTemplatesFolder}/{Constants.Templates.CSharpTemplateDirectories.ContextFolder}";
            var contextPartialsVirtualPath = contextTemplatesVirtualPath + $"/{Constants.Templates.PartialsFolder}";
            var contextTemplatesPath       = Path.Combine(projectRootDir, "src", Constants.Templates.ProjectFolder,
                                                          Constants.Templates.CodeTemplatesFolder, Constants.Templates.CSharpTemplateDirectories.ContextFolder);
            var contextPartialTemplatesPath = Path.Combine(contextTemplatesPath, Constants.Templates.PartialsFolder);

            var entityTemplatesVirtualPath =
                $"{Constants.Templates.CodeTemplatesFolder}/{Constants.Templates.CSharpTemplateDirectories.EntityTypeFolder}";
            var entityPartialsVirtualPath = entityTemplatesVirtualPath + $"/{Constants.Templates.PartialsFolder}";
            var entityTemplatesPath       = Path.Combine(projectRootDir, "src", Constants.Templates.ProjectFolder,
                                                         Constants.Templates.CodeTemplatesFolder, Constants.Templates.CSharpTemplateDirectories.EntityTypeFolder);
            var entityPartialTemplatesPath = Path.Combine(entityTemplatesPath, Constants.Templates.PartialsFolder);

            ContextClassTemplate = new InputFile
            {
                Directory = contextTemplatesVirtualPath,
                File      = Constants.Templates.ContextClassFile,
                Contents  = File.ReadAllText(Path.Combine(contextTemplatesPath, Constants.Templates.ContextClassFile))
            };
            ContextImportsTemplate = new InputFile
            {
                Directory = contextPartialsVirtualPath,
                File      = Constants.Templates.ContextImportsFile,
                Contents  = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextImportsFile))
            };
            ContextCtorTemplate = new InputFile
            {
                Directory = contextPartialsVirtualPath,
                File      = Constants.Templates.ContextCtorFile,
                Contents  = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextCtorFile))
            };
            ContextOnConfiguringTemplate = new InputFile
            {
                Directory = contextPartialsVirtualPath,
                File      = Constants.Templates.ContextOnConfiguringFile,
                Contents  = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextOnConfiguringFile))
            };
            ContextDbSetsTemplate = new InputFile
            {
                Directory = contextPartialsVirtualPath,
                File      = Constants.Templates.ContextDbSetsFile,
                Contents  = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextDbSetsFile))
            };

            EntityClassTemplate = new InputFile
            {
                Directory = entityTemplatesVirtualPath,
                File      = Constants.Templates.EntityClassFile,
                Contents  = File.ReadAllText(Path.Combine(entityTemplatesPath, Constants.Templates.EntityClassFile))
            };
            EntityImportsTemplate = new InputFile
            {
                Directory = entityPartialsVirtualPath,
                File      = Constants.Templates.EntityImportsFile,
                Contents  = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityImportsFile))
            };
            EntityCtorTemplate = new InputFile
            {
                Directory = entityPartialsVirtualPath,
                File      = Constants.Templates.EntityCtorFile,
                Contents  = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityCtorFile))
            };
            EntityPropertiesTemplate = new InputFile
            {
                Directory = entityPartialsVirtualPath,
                File      = Constants.Templates.EntityPropertiesFile,
                Contents  = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityPropertiesFile))
            };
        }
 public Task <OutputFile> ProcessAsync(InputFile file) => Task.FromResult <OutputFile>(null);
 public string getOutFileName()
 {
     return(InputFile.Insert(InputFile.LastIndexOf("."), "_"
                             + String.Format(@"I2P")));
 }
 public string getOutFileName()
 {
     return(InputFile.Insert(InputFile.LastIndexOf("."), "_"
                             + String.Format(@"HCSub_S{0}", Path.GetFileName(tbSubInput.Text))));
 }
Example #14
0
        /// <summary>
        /// Converts the relative input file to an absolute file path.
        /// </summary>
        public FileInfo GetAbsoluteInputFile()
        {
            string folder = new FileInfo(FileName).DirectoryName;

            return(new FileInfo(Path.Combine(folder, InputFile.Replace("/", "\\"))));
        }
Example #15
0
        public void Ctor_GivenFxtFile_RecognisesAsFxtFile()
        {
            var sut = new InputFile("BLAH.FXT");

            Assert.That(sut.IsFxt, Is.True);
        }
Example #16
0
 public override void ParsePayload(InputFile file, ulong position)
 {
     base.ParsePayload(file, position);
 }
Example #17
0
        private async Task Login()
        {
            flow.NeedCodeEvent += delegate(Login login) {
                Deployment.Current.Dispatcher.BeginInvoke(
                    delegate {
                    RestartTimer();
                    ShowCodeScene();
                    HeaderBlock.Text = "Your code";
                });
            };

            flow.WrongCodeEvent += delegate(Login login) {
                Deployment.Current.Dispatcher.BeginInvoke(
                    delegate {
                    ShowCodeScene();
                    HeaderBlock.Text = "Your code";
                    codeControl.SetCodeInvalid();
                });
            };

            flow.NeedSignupEvent += delegate(Login login) {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    HeaderBlock.Text = "Your name";
                    ShowNameScene();
                });
            };

            flow.LoginSuccessEvent += delegate(Login login) {
                Deployment.Current.Dispatcher.BeginInvoke(
                    delegate {
                    HideProgress();
                    new NotificationManager().RegisterPushNotifications();
                    NavigationService.Navigate(new Uri("/UI/Pages/StartPage.xaml", UriKind.Relative));



                    ContactManager cm = new ContactManager();
                    Task.Run(() => cm.SyncContacts());

                    PhotoResult avatarSource = nameControl.GetAvatarSource();

                    if (avatarSource != null)
                    {
                        Task.Run(async delegate {
                            InputFile file =
                                await TelegramSession.Instance.Files.UploadFile(avatarSource.OriginalFileName, avatarSource.ChosenPhoto, (progress) => { });

                            photos_Photo photo =
                                await
                                TelegramSession.Instance.Api.photos_uploadProfilePhoto(file, "", TL.inputGeoPointEmpty(),
                                                                                       TL.inputPhotoCropAuto());

                            Photos_photoConstructor photoConstructor = (Photos_photoConstructor)photo;

                            foreach (var user in photoConstructor.users)
                            {
                                TelegramSession.Instance.SaveUser(user);
                            }
                        });
                    }
                });
            };

            Task.Run(() => flow.Start());
//            flow.Start();
        }
Example #18
0
        static void Main(string[] args)
        {
            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName, RevisionResource);

            if (CreateContextMenuEntry)
            {
                // create context menu entry
                try
                {
                    TraceLogger.Info("Creating context menu entry for xls2x ...");
                    RegisterForContextMenu(GetContextMenuKey(ContextMenuInputExtension, ContextMenuText));
                    TraceLogger.Info("Succeeded.");
                }
                catch (Exception)
                {
                    TraceLogger.Info("Failed. Sorry :(");
                }
            }
            else
            {
                try
                {
                    //copy processing file
                    ProcessingFile procFile = new ProcessingFile(InputFile);

                    //make output file name
                    if (ChoosenOutputFile == null)
                    {
                        if (InputFile.Contains("."))
                        {
                            ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".xlsx";
                        }
                        else
                        {
                            ChoosenOutputFile = InputFile + ".xlsx";
                        }
                    }

                    //parse the document
                    using (StructuredStorageReader reader = new StructuredStorageReader(procFile.File.FullName))
                    {
                        XlsDocument xlsDoc = new XlsDocument(reader);

                        OpenXmlPackage.DocumentType outType = Converter.DetectOutputType(xlsDoc);
                        string conformOutputFile            = Converter.GetConformFilename(ChoosenOutputFile, outType);
                        using (SpreadsheetDocument spreadx = SpreadsheetDocument.Create(conformOutputFile, outType))
                        {
                            //start time
                            DateTime start = DateTime.Now;
                            TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile);

                            Converter.Convert(xlsDoc, spreadx);

                            DateTime end  = DateTime.Now;
                            TimeSpan diff = end.Subtract(start);
                            TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
                catch (ParseException ex)
                {
                    TraceLogger.Error("Could not convert {0} because it was created by an unsupported application (Excel 95 or older).", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (DirectoryNotFoundException ex)
                {
                    TraceLogger.Error(ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (FileNotFoundException ex)
                {
                    TraceLogger.Error(ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (ZipCreationException ex)
                {
                    TraceLogger.Error("Could not create output file {0}.", ChoosenOutputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (Exception ex)
                {
                    TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
            }
        }
        public bool Transcode()
        {
            bool exclusiveAccess = false;
            bool RetVal          = false;

            try
            {
                FileStream FileTest = InputFile.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                FileTest.Close();
                exclusiveAccess = true;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Couldn't get exclusive access to " + InputFile.Name + ", Skipping: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            if (!OutputFile.Exists && exclusiveAccess)
            {
                MediaFile F = new MediaFile(InputFile.FullName);

                if (F.HasStreams)
                {
                    if (F.Video.Count > 0)
                    {
                        string tempBannerRemove = null;
                        string tempAdremove     = null;

                        Console.CursorLeft = 0;
                        Console.Write("".PadRight(Console.WindowWidth - 1));
                        Console.CursorLeft = 0;

                        if (isPlayOnFile())
                        {
                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine(InputFile.Name + " is a PlayOn file.");
                            Console.ForegroundColor = ConsoleColor.Gray;


                            if (RemoveAds && hasAds())
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine(F.filePath + " has PlayOn Detected Commercials. Removing...");
                                Console.ForegroundColor = ConsoleColor.Gray;

                                tempAdremove = RemoveCommercials(F);

                                if (tempAdremove != null)
                                {
                                    F = new MediaFile(tempAdremove);

                                    if (!RemovePlayOnBanner && !h265Transcode)
                                    {
                                        File.Move(F.filePath, OutputFile.FullName);

                                        if (DeleteOriginal)
                                        {
                                            Console.ForegroundColor = ConsoleColor.Yellow;
                                            Console.WriteLine("Deleting " + InputFile.Name);
                                            InputFile.Delete();
                                            Console.ForegroundColor = ConsoleColor.Gray;
                                        }

                                        return(true);
                                    }
                                }
                            }

                            if (RemovePlayOnBanner)
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine(F.filePath + " has PlayOn Banner. Removing...");
                                Console.ForegroundColor = ConsoleColor.Gray;
                                tempBannerRemove        = RemoveBanner(F);

                                if (tempBannerRemove != null)
                                {
                                    F = new MediaFile(tempBannerRemove);

                                    if (tempAdremove != null)
                                    {
                                        File.Delete(tempAdremove);
                                    }

                                    if (!h265Transcode)
                                    {
                                        File.Move(F.filePath, OutputFile.FullName);

                                        if (DeleteOriginal)
                                        {
                                            Console.ForegroundColor = ConsoleColor.Yellow;
                                            Console.WriteLine("Deleting " + InputFile.Name);
                                            InputFile.Delete();
                                            Console.ForegroundColor = ConsoleColor.Gray;
                                        }
                                        return(true);
                                    }
                                }
                            }
                        }

                        if (h265Transcode)
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Transcoding (" + Preset.ToString() + "/" + CRF.ToString() + ") " + F.filePath + " to h.265 format...");
                            Console.ForegroundColor = ConsoleColor.Gray;
                            RetVal = (ffmpeg_h265_Transcode(F) != null);

                            if (tempAdremove != null && File.Exists(tempAdremove))
                            {
                                File.Delete(tempAdremove);
                            }

                            if (tempBannerRemove != null && File.Exists(tempBannerRemove))
                            {
                                File.Delete(tempBannerRemove);
                            }

                            if (RetVal)
                            {
                                Console.CursorLeft      = 0;
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine(("Transcode Complete for " + InputFile.Name + ".").PadRight(Console.WindowWidth - 1));
                                Console.ForegroundColor = ConsoleColor.Gray;

                                if (DeleteOriginal && File.Exists(OutputFile.FullName))
                                {
                                    Console.ForegroundColor = ConsoleColor.Yellow;
                                    Console.CursorLeft      = 0;
                                    Console.WriteLine(("Deleting " + InputFile.FullName).PadRight(Console.WindowWidth - 1));
                                    InputFile.Delete();
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                }
                            }
                        }
                        else
                        {
                            RetVal = ProcessNonMediaFile();
                        }
                    }
                    else
                    {
                        RetVal = ProcessNonMediaFile();
                    }
                }
            }
            else
            {
                throw new InvalidOperationException(OutputFile.FullName + " already exists or could not get exclusive access to original");
            }
            return(RetVal);
        }
Example #20
0
        public bool DropTextureEditor(Texture tex)
        {
            #if UNITY_EDITOR
            if (tex != null)
            {
                pathTexStamp = UnityEditor.AssetDatabase.GetAssetPath(tex);
                string path  = pathTexStamp;
                int    index = path.LastIndexOf("/");
                path = path.Insert(index, "/RawFiles");

                index = path.IndexOf("/Resources/");
                isStampInResourcesFolder = (index != -1);

                if (isStampInResourcesFolder)
                {
                    path            = path.Substring(index + 11);
                    path            = path.Remove(path.Length - 4);
                    resourcesFolder = path;
                    // Debug.Log(path);
                }
                else
                {
                    path = path.Remove(path.Length - 3) + "raw";

                    if (!TC.FileExistsPath(path))
                    {
                        path = path.Remove(path.Length - 3) + "r16";
                    }

                    if (!TC.FileExistsPath(path))
                    {
                        // TC.AddMessage("Cannot find the file " + path.Remove(path.Length - 3, 3) + "\n\nThe file extension needs to be .raw or .r16");
                        if (rawImage != null)
                        {
                            rawImage.UnregisterReference();
                        }
                        inputFile = InputFile.Image;
                        stampTex  = tex;
                        TC.AutoGenerate();
                        return(false);
                    }
                }

                TC_RawImage oldRawImage = rawImage;
                if (oldRawImage)
                {
                    oldRawImage.UnregisterReference();
                }

                // Debug.Log(path);

                rawImage = TC_Settings.instance.AddRawFile(path, isStampInResourcesFolder);
            }
            #else
            if (isStampInResourcesFolder)
            {
                rawImage = TC_Settings.instance.AddRawFile(resourcesFolder, isStampInResourcesFolder);
            }
            #endif

            if (rawImage != null)
            {
                stampTex = tex;
                TC.RefreshOutputReferences(outputId, true);

                // TC_Reporter.Log(path);
                TC_Reporter.Log("Node index " + rawImage.name);
                return(true);
            }
            else
            {
                TC.AddMessage("This is not a stamp preview image.\n\nThe raw heightmap file needs to be placed in a 'RawFiles' folder, then TC2 will automatically make a preview image one folder before it.\nThis image needs to be used for dropping on the node.", 0, 4);
            }

            return(false);
        }
Example #21
0
        /// <summary>
        /// Execute the task.
        /// </summary>
        /// <param name="Job">Information about the current job</param>
        /// <param name="BuildProducts">Set of build products produced by this node.</param>
        /// <param name="TagNameToFileSet">Mapping from tag names to the set of files they include</param>
        /// <returns>True if the task succeeded</returns>
        public override bool Execute(JobContext Job, HashSet <FileReference> BuildProducts, Dictionary <string, HashSet <FileReference> > TagNameToFileSet)
        {
            // Get the pattern to match against. If it's a simple pattern (eg. *.cpp, Engine/Build/...), automatically infer the source wildcard
            string FromPattern = Parameters.From;

            if (FromPattern == null)
            {
                List <string> Patterns = SplitDelimitedList(Parameters.Files);
                if (Patterns.Count != 1 || Patterns[0].StartsWith("#"))
                {
                    CommandUtils.LogError("Missing 'From' attribute specifying pattern to match source files against");
                    return(false);
                }

                FromPattern = Patterns[0];

                int SlashIdx = FromPattern.LastIndexOfAny(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
                if (SlashIdx != -1)
                {
                    FromPattern = FromPattern.Substring(SlashIdx + 1);
                }
                if (FromPattern.StartsWith("..."))
                {
                    FromPattern = "*" + FromPattern.Substring(3);
                }
            }

            // Convert the source pattern into a regex
            string EscapedFromPattern = "^" + Regex.Escape(FromPattern) + "$";

            EscapedFromPattern = EscapedFromPattern.Replace("\\*", "(.*)");
            EscapedFromPattern = EscapedFromPattern.Replace("\\?", "(.)");
            Regex FromRegex = new Regex(EscapedFromPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

            // Split the output pattern into fragments that we can insert captures between
            string[] FromFragments = FromPattern.Split('*', '?');
            string[] ToFragments   = Parameters.To.Split('*', '?');
            if (FromFragments.Length < ToFragments.Length)
            {
                CommandUtils.LogError("Too few capture groups in source pattern '{0}' to rename to '{1}'", FromPattern, Parameters.To);
                return(false);
            }

            // Find the input files
            HashSet <FileReference> InputFiles = ResolveFilespec(CommandUtils.RootDirectory, Parameters.Files, TagNameToFileSet);

            // Find all the corresponding output files
            Dictionary <FileReference, FileReference> RenameFiles = new Dictionary <FileReference, FileReference>();

            foreach (FileReference InputFile in InputFiles)
            {
                Match Match = FromRegex.Match(InputFile.GetFileName());
                if (Match.Success)
                {
                    StringBuilder OutputName = new StringBuilder(ToFragments[0]);
                    for (int Idx = 1; Idx < ToFragments.Length; Idx++)
                    {
                        OutputName.Append(Match.Groups[Idx].Value);
                        OutputName.Append(ToFragments[Idx]);
                    }
                    RenameFiles[InputFile] = FileReference.Combine(InputFile.Directory, OutputName.ToString());
                }
            }

            // Print out everything we're going to do
            foreach (KeyValuePair <FileReference, FileReference> Pair in RenameFiles)
            {
                CommandUtils.RenameFile(Pair.Key.FullName, Pair.Value.FullName, true);
            }

            // Add the build product
            BuildProducts.UnionWith(RenameFiles.Values);

            // Apply the optional output tag to them
            foreach (string TagName in FindTagNamesFromList(Parameters.Tag))
            {
                FindOrAddTagSet(TagNameToFileSet, TagName).UnionWith(RenameFiles.Values);
            }
            return(true);
        }
Example #22
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            var FFMPEGPath      = ffmpegPath.Get(context);
            var FFMPEGDirectory = FFMPEGPath.Substring(0, FFMPEGPath.LastIndexOf('\\'));

            FFMPEGPath = '"' + FFMPEGPath + '"';
            var inputFile       = InputFile.Get(context);
            var outputFolder    = OutputFolder.Get(context);
            var outputContainer = OutputContainer.Get(context);
            var command         = Command.Get(context);
            var fontFile        = FontFile.Get(context);
            var debuggingMode   = DebuggingMode.Get(context);
            var text            = Text.Get(context);


            string tempPath     = Path.GetTempPath();
            var    fontFileName = fontFile.Substring(fontFile.LastIndexOf(@"\"));

            fontFileName = fontFileName.Replace(@"\", "");

            String fontFilePath = Path.Combine(tempPath, fontFileName);

            if (!System.IO.File.Exists(fontFilePath))
            {
                System.IO.File.Copy(fontFile, fontFilePath, true);
            }

            var startInfo = new ProcessStartInfo(FFMPEGPath);

            startInfo.WindowStyle      = ProcessWindowStyle.Normal;
            startInfo.WorkingDirectory = tempPath;

            string inputContainer = inputFile.Substring(inputFile.LastIndexOf('.'));

            if (outputContainer == "")
            {
                outputContainer = inputContainer;
            }

            string fileNameWithoutExtensions = inputFile.Replace(inputContainer, "");
            var    fileName = fileNameWithoutExtensions.Substring(fileNameWithoutExtensions.LastIndexOf(@"\"));

            fileName = fileName.Replace(@"\", "");

            var uniqueId = (DateTime.Now.Ticks - new DateTime(2016, 1, 1).Ticks).ToString("x");

            startInfo.Arguments = "-i " + '"' + inputFile + '"' + " " + "-vf drawtext=enable='between(t,2,8)':\"fontfile = " + fontFileName + '"' + ":text=\"" + text + "\":fontcolor=white:fontsize=124:x=(w-text_w)/2:y=(h-text_h)/2 " + command + " " + '"' + outputFolder + @"\" + uniqueId + "." + outputContainer + '"';

            if (debuggingMode)
            {
                var processn = new Process();
                processn.StartInfo           = startInfo;
                processn.EnableRaisingEvents = true;
                processn.StartInfo.FileName  = "CMD.EXE";
                processn.StartInfo.Arguments = "/K " + '"' + @FFMPEGPath + " " + startInfo.Arguments + '"';
                processn.Start();
                processn.WaitForExit();
            }
            else
            {
                var processn = Process.Start(startInfo);
                processn.EnableRaisingEvents = true;

                processn.WaitForExit();
            }

            // Outputs
            return((ctx) => {
            });
        }
Example #23
0
        private void UploadButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var byteArray = File.ReadAllBytes(InputFile);
                var appointmentDataRepository = new AppointmentDataRepository(EHealthCareDesktopApp.Properties.Settings.Default.UniqueIdentifier);
                appointmentDataRepository.Upload(new AudioAppointment {
                    AppointmentId = this.appointmentID,
                    DateTime      = DateTime.Now,
                    PatientId     = EHealthCareDesktopApp.Properties.Settings.Default.PatientID,
                    FileName      = InputFile.Substring(InputFile.LastIndexOf("\\") + 1, (InputFile.Length - InputFile.LastIndexOf("\\") - 1)),
                    Audio         = byteArray,
                });

                LoadAudioFiles();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #24
0
        public void SaveTest()
        {
            var ms = new InputFile(@"..\..\..\TestData\Karup_Example_DemoMode.she");

            ms.SaveAs(@"..\..\..\TestData\Karup_Example_DemoMode1.she");
        }
Example #25
0
        static public void ClickMenuInput(object obj)
        {
            int    instanceID;
            string command = TD.ObjectToCommandAndInstanceID(obj, out instanceID);

            TC_Node node = EditorUtility.InstanceIDToObject(instanceID) as TC_Node;

            if (node != null)
            {
                int    index     = command.IndexOf("/");
                string inputKind = command.Substring(0, index);
                string input     = command.Substring(index + 1);
                bool   changed   = false;

                InputKind oldInputKind = node.inputKind;
                node.inputKind = (InputKind)Enum.Parse(typeof(InputKind), inputKind);

                if (node.inputKind != oldInputKind)
                {
                    changed = true;
                }

                if (inputKind == "Terrain")
                {
                    InputTerrain oldInputTerrain = node.inputTerrain;
                    node.inputTerrain = (InputTerrain)Enum.Parse(typeof(InputTerrain), input);
                    if (node.inputTerrain != oldInputTerrain)
                    {
                        changed = true;
                    }
                }
                else if (inputKind == "Noise")
                {
                    InputNoise oldInputNoise = node.inputNoise;
                    node.inputNoise = (InputNoise)Enum.Parse(typeof(InputNoise), input);
                    if (node.inputNoise != oldInputNoise)
                    {
                        changed = true;
                    }
                }
                else if (inputKind == "Shape")
                {
                    InputShape oldInputShape = node.inputShape;
                    node.inputShape = (InputShape)Enum.Parse(typeof(InputShape), input);
                    if (node.inputShape != oldInputShape)
                    {
                        changed = true;
                    }
                }
                else if (inputKind == "File")
                {
                    InputFile oldInputFile = node.inputFile;
                    node.inputFile = (InputFile)Enum.Parse(typeof(InputFile), input);
                    if (node.inputFile != oldInputFile)
                    {
                        changed = true;
                    }
                }
                else if (inputKind == "Current")
                {
                    InputCurrent oldInputCurrent = node.inputCurrent;
                    node.inputCurrent = (InputCurrent)Enum.Parse(typeof(InputCurrent), input);
                    if (node.inputCurrent != oldInputCurrent)
                    {
                        changed = true;
                    }
                }
                else if (inputKind == "Portal")
                {
                    InputPortal oldInputPortal = node.inputPortal;
                    node.inputPortal = (InputPortal)Enum.Parse(typeof(InputPortal), input);
                    if (node.inputPortal != oldInputPortal)
                    {
                        changed = true;
                    }
                }

                if (changed)
                {
                    node.Init();
                    EditorUtility.SetDirty(node);
                    TC.RefreshOutputReferences(node.outputId, true);
                }
            }
        }
Example #26
0
        // Confirm button which send transaction details to text file.
        private void button2_Click(object sender, EventArgs e)
        {
            ClearButton.Visible  = true;
            CancelButton.Visible = false;
            // Code to shift the focus to ClearButton.
            ClearButton.Focus();
            // Code to create string builder and formatted into Text File.
            StringBuilder sb = new StringBuilder();
            //Local variable declaration section.
            int DataGridCartLength = DataGridCart.RowCount;

            for (int i = 0; i < DataGridCartLength; i++)
            {
                // code to format the string and appended from datagrid view.
                sb.AppendLine(DataGridCart[0, i].Value?.ToString() + " 0f " + DataGridCart[2, i].Value?.ToString() + " " + DataGridCart[1, i].Value?.ToString() + " " + DataGridCart[3, i].Value?.ToString());
            }
            //decision construct to write the transaction text file.
            if (MessageBox.Show(string.Format(sb.ToString() + "Total Transaction Cost is" + CURRENCY + FinalValue.ToString()), "Confirmation Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //code which instanciates streamwriter class.
                StreamWriter OutputFile;
                //code to append the string to file.
                OutputFile = File.AppendText("TransactionsFile.txt");
                OutputFile.Close();
                // Local Variable declaration restriceted to this decision construct.
                string Temp;
                int    RandomNumber      = 0;
                int    BeerConfirmIndex  = BeerNamesListBox.SelectedIndex;
                int    BeerSizeConfirmed = BeerSubTypeListBox.SelectedIndex;
                //Code which copy the contents of original array to destination array.
                Array.Copy(TempStockArray, StockArray, TempStockArray.Length);
                //StockArray[BeerConfirmIndex, BeerSizeConfirmed] = TempStockArray[BeerConfirmIndex, BeerSizeConfirmed];
                // calling random number generation method.
                RandomNumberGenerator(ref RandomNumber);
                StreamReader InputFile;
                InputFile = File.OpenText("TransactionsFile.txt");
                while (!InputFile.EndOfStream)
                {
                    Temp = InputFile.ReadLine();
                    // To check and generate unique random number.
                    if (Temp == RandomNumber.ToString())
                    {
                        RandomNumberGenerator(ref RandomNumber);
                    }
                }
                InputFile.Close();
                //Code which appends transaction details from gridview to text file.
                StreamWriter FileOpen;
                FileOpen = File.AppendText("TransactionsFile.txt");
                FileOpen.WriteLine(RandomNumber);
                FileOpen.WriteLine(GetDateTime.ToShortDateString());
                for (int i = 0; i < DataGridCart.Rows.Count; i++)
                {
                    for (int j = 0; j < 4; j++)
                    {
                        FileOpen.WriteLine(DataGridCart[j, i].Value?.ToString());
                    }
                }
                FileOpen.WriteLine("123");
                FileOpen.Close();
            }
            // Decision construct if selected cart items will not be purchased.
            else
            {
                // code to clear the gridview cells.
                DataGridCart.ClearSelection();
                DataGridCart.Rows.Clear();
                TotalCostValueTextBox.Clear();
                QuantityValuesTextBox.Clear();
                ClearButton.Focus();
            }
        }
Example #27
0
 public string[][] GetFileGrid()
 {
     return(InputFile.ToArray());
 }
Example #28
0
 protected override StageResult Cleanup()
 {
     InputFile.Delete();
     L.Debug("Deleted temporary input file {0}.", InputFileName);
     return(StageResult.SUCCESS);
 }
Example #29
0
 public IList <string> InputOptions(InputFile inputFile) => new List <string>
 {
     "-ignore_loop", "0"
 };
Example #30
0
        public void Ctor_AnticipatedFile_PathIsStored()
        {
            var sut = new InputFile("BLAH.TXT");

            Assert.That(sut.Path, Is.EqualTo("BLAH.TXT"));
        }
Example #31
0
 internal TimeInfo(InputFile Input)
 {
     _input = Input;
 }
Example #32
0
        public async Task<bool> SendMediaMessage(int contactId, InputFile file)
        {
            var request = new Message_SendMediaRequest(
                new InputPeerContactConstructor(contactId),
                new InputMediaUploadedPhotoConstructor(file));

            await _sender.Send(request);
            await _sender.Recieve(request);

            return true;
        }
Example #33
0
 public SendPhotoArgs(string chatId, InputFile photo) : base(chatId)
 {
     Photo = photo;
 }
Example #34
0
        private async void OpenFiles(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                // Set the file dialog to filter for graphics files.
                Filter = "Text|*.txt|All|*.*",
                // Allow the user to select multiple images.
                Multiselect = true,
                Title       = "Select your TimeFrame Files..."
            };

            if (openFileDialog.ShowDialog() == true)
            {
                Task Preparation = Task.Run(() =>
                {
                    InputFile.AddFilesToList(openFileDialog);

                    foreach (InputFile file in Globals.GetFiles())
                    {
                        try
                        {
                            if (!file.Prepared)
                            {
                                file.PrepareFile();
                            }
                        }
                        catch (Exception ex)
                        {
                            file.Invalid = true;
                            if (MessageBox.Show(ex.Message + "\nError occured. Would you like to process all remaining files?", "Error occured!", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                            {
                                return;
                            }
                        }
                    }
                });

                await Preparation;

                Task Cleanup = Task.Run(() =>
                {
                    Globals.GetFiles().RemoveAll(file => file.Invalid == true);
                });

                await Cleanup;

                if (Globals.GetFiles().Count != 0)
                {
                    StatusBarLabel.Text = "Prepared all remaining files";
                }
                else
                {
                    StatusBarLabel.Text = "No files to process";
                }

                if (Globals.GetFiles().Count > 0)
                {
                    ClearButton.IsEnabled     = true;
                    CalculateButton.IsEnabled = true;
                }

                RefreshFilesDataGrid();
            }
        }
 /// <summary>
 /// Determine if the file is a CSHTML File or not
 /// </summary>
 /// <param name="file">File to determine if CSHTML</param>
 /// <returns>True of CSHTML, False if not</returns>
 private bool IsCshtmlFile(InputFile file)
 {
     return(file.Extension.IgnoreCaseEquals(".cshtml"));
 }
Example #36
0
 public override void ParsePayload(InputFile file, ulong position)
 {
     /* must not do anything */
 }
        static void Main(string[] args)
        {
            GdalConfiguration.ConfigureOgr();
            var dataSource = Ogr.Open("Electorates.shp", 0);
            try
            {
                ElectionResultSet results = new ElectionResultSet();

                var resultFiles = new InputFile[]
                {
                    //2004 Federal Election (9 October 2004)
                    new InputFile
                    {
                        Date = new DateTime(2004, 10, 9),
                        Source = File.OpenText("2004-HouseMembersElectedDownload-12246.csv"),
                        TPPSource = File.OpenText("2004-HouseTppByDivisionDownload-12246.csv"),
                        General = true
                    },
                    //2007 Federal Election (24 November 2007)
                    new InputFile
                    {
                        Date = new DateTime(2007, 11, 24),
                        Source = File.OpenText("2007-HouseMembersElectedDownload-13745.csv"),
                        TPPSource = File.OpenText("2007-HouseTppByDivisionDownload-13745.csv"),
                        General = true
                    },
                    //2008 Gippsland By-Election (28 June 2008)
                    new InputFile
                    {
                        Date = new DateTime(2008, 6, 28),
                        Source = File.OpenText("2008-Gippsland-HouseCandidatesDownload-13813.csv"),
                        TPPSource = File.OpenText("2008-Gippsland-HouseTppByPollingPlaceDownload-13813.csv"),
                        General = false
                    },
                    //2008 Lyne By-Election (6 September 2008)
                    new InputFile
                    {
                        Date = new DateTime(2008, 9, 6),
                        Source = File.OpenText("2008-Lyne-HouseCandidatesDownload-13827.csv"),
                        TPPSource = null,
                        General = false
                    },
                    //2008 Mayo By-Election (6 September 2008)
                    new InputFile
                    {
                        Date = new DateTime(2008, 9, 6),
                        Source = File.OpenText("2008-Mayo-HouseCandidatesDownload-13826.csv"),
                        TPPSource = null,
                        General = false
                    },
                    //2009 Bradfield By-Election (5 December 2009)
                    new InputFile
                    {
                        Date = new DateTime(2009, 12, 5),
                        Source = File.OpenText("2009-Bradfield-HouseCandidatesDownload-14357.csv"),
                        TPPSource = null,
                        General = false
                    },
                    //2009 Higgins By-Election (5 December 2009)
                    new InputFile
                    {
                        Date = new DateTime(2009, 12, 5),
                        Source = File.OpenText("2009-Higgins-HouseCandidatesDownload-14358.csv"),
                        TPPSource = null,
                        General = false
                    },
                    //2010 Federal Election (21 August 2010)
                    new InputFile
                    {
                        Date = new DateTime(2010, 8, 21),
                        Source = File.OpenText("2010-HouseMembersElectedDownload-15508.csv"),
                        TPPSource = File.OpenText("2010-HouseTppByDivisionDownload-15508.csv"),
                        General = true
                    },
                    //2013 Federal Election (7 September 2013)
                    new InputFile
                    {
                        Date = new DateTime(2013, 9, 7),
                        Source = File.OpenText("2013-HouseMembersElectedDownload-17496.csv"),
                        TPPSource = File.OpenText("2013-HouseTppByDivisionDownload-17496.csv"),
                        General = true
                    },
                    //2014 Griffith By-Election (8 February 2014)
                    new InputFile
                    {
                        Date = new DateTime(2014, 2, 8),
                        Source = File.OpenText("2014-Griffith-HouseCandidatesDownload-17552.csv"),
                        TPPSource = File.OpenText("2014-Griffith-HouseTppByPollingPlaceDownload-17552.csv"),
                        General = false
                    }
                };

                foreach (var resFile in resultFiles)
                {
                    try
                    {
                        var csvr = new CsvReader(resFile.Source);
                        if (resFile.General)
                        {
                            results.LoadElectionResults(resFile.Date, csvr.GetRecords<ElectionResult>());

                            if (resFile.TPPSource != null)
                            {
                                var tppr = new CsvReader(resFile.TPPSource);
                                tppr.Configuration.RegisterClassMap<FederalTPPResultClassMap>();
                                results.LoadTPPResults(resFile.Date, tppr.GetRecords<FederalTPPResult>());
                            }
                        }
                        else
                        {
                            results.LoadElectionResults(resFile.Date, csvr.GetRecords<ByElectionResult>().Where(e => e.Elected == "Y"));

                            if (resFile.TPPSource != null)
                            {
                                var tppr = new CsvReader(resFile.TPPSource);
                                tppr.Configuration.RegisterClassMap<ByElectionPollingBoothTPPResultClassMap>();
                                results.LoadTPPResults(resFile.Date, tppr.GetRecords<ByElectionPollingBoothTPPResult>());
                            }
                        }
                    }
                    finally
                    {
                        resFile.Close();
                    }
                }

                //_parties = results.GetParties();

                var layer = dataSource.GetLayerByIndex(0);
                using (var fw = new StreamWriter("elections.czml", false))
                {
                    using (var writer = new JsonTextWriter(fw))
                    {
                        writer.Formatting = Formatting.Indented;

                        //The root element of a CZML document is a JSON array
                        writer.WriteStartArray();
                        
                        //Which contains a series of CZML packets, uniquely identified

                        //Starts with the header
                        WriteCzmlDocumentHeader(writer);

                        var feat = layer.GetNextFeature();
                        while (feat != null)
                        {
                            string electorateName = feat.GetFieldAsString("ELECT_DIV");
                            var elecResults = results.GetResultsForDivison(electorateName);
                            var tppResults = results.GetTPPForDivison(electorateName);
                            if (elecResults.Length > 0)
                            {
                                WritePacket(writer, feat, electorateName, elecResults, tppResults);
                            }
                            feat = layer.GetNextFeature();
                        }

                        writer.WriteEndArray();
                    }
                }
            }
            finally
            {
                dataSource.Dispose();
            }

            //double smallestArea = _areas.Values.Min();
            //Debug.WriteLine($"Smallest area: {smallestArea}");
        }