public async Task <DocumentReference> Duplicate(IFileSystem fs)
        {
            var baseName = Name;

            if (!baseName.EndsWith("Copy", StringComparison.Ordinal))
            {
                baseName = baseName + " Copy";
            }

            var             directory = Path.GetDirectoryName(File.Path);
            LocalFileAccess local     = null;
            var             contents  = "";

            try {
                local = await File.BeginLocalAccess();

                var localPath = local.LocalPath;
                contents = System.IO.File.ReadAllText(localPath);
            } catch (Exception ex) {
                Debug.WriteLine(ex);
            }
            if (local != null)
            {
                await local.End();
            }

            var ext = Path.GetExtension(File.Path);

            var dr = await New(directory, baseName, ext, fs, dctor, contents);

            dr.IsNew = false;

            return(dr);
        }
Exemple #2
0
        private static List <BuildMsgTemplate> LoadMsgs(string jsonFilePath)
        {
            var content = LocalFileAccess.ReadFile(jsonFilePath);

            if (content == null)
            {
                return(null);
            }
            return(JsonConvert.DeserializeObject <List <BuildMsgTemplate> >(content));
        }
 private void button1_Click(object sender, EventArgs e)
 {
     lfa = new LocalFileAccess();
     if (!File.Exists(rootPath + @"\" + Environment.MachineName))
     {
         File.Create(rootPath + @"\" + Environment.MachineName).Close();
     }
     timer2.Enabled = true;
     Task.Run(() => Experiments.ExperimentsA(numOfLablesArray.ToArray(), entropyPropotionArray.ToArray(), rootPath));
 }
        public async Task <int> Invoke(EnvironmentVar enVar)
        {
            Task monitor = Task.Run(() =>
            {
                LocalFileAccess lfa = new LocalFileAccess();
                while (!_enVars.All(x => x.finishIndicate == true))
                {
                    for (int i = 0; i < _enVars.Length; i++)
                    {
                        if (_record.updateIndicate[i] == true)
                        {
                            /** update fitRecord to File **/
                            lfa.StoreListToLinesAppend(Directory.GetCurrentDirectory() + @"\OUT\MOGA\" + _enVars[i].pmProblem["Name"] + @"\CEOutput_" + i.ToString(), _record.currentGen[i]);
                            lfa.StoreListToLinesAppend(Directory.GetCurrentDirectory() + @"\OUT\MOGA\" + _enVars[i].pmProblem["Name"] + @"\CEOutput_" + i.ToString(), _record.currentCElist[i]);

                            List <string> tmpStr = new List <string>();
                            for (int j = 0; j < _record.currentFitnessList[i].Count; j++)
                            {
                                tmpStr.Add(_record.currentFitnessList[i][j].Item1 + " " + _record.currentFitnessList[i][j].Item2);
                            }
                            lfa.StoreListToLinesAppend(Directory.GetCurrentDirectory() + @"\OUT\MOGA\" + _enVars[i].pmProblem["Name"] + @"\CEOutput_" + i.ToString(), tmpStr);

                            for (int k = 0; k < _record.currentBestSolution[i].Length; k++)
                            {
                                if (_record.currentBestSolution[i][k] != null)
                                {
                                    lfa.StoreListToLinesAppend(Directory.GetCurrentDirectory() + @"\OUT\MOGA\" + _enVars[i].pmProblem["Name"] + @"\CEOutput_" + i.ToString(), _record.currentBestSolution[i][k]);
                                }
                            }
                            _record.updateDisplay[i] = true;
                            while (_record.updateDisplay[i] == true)
                            {
                                ;
                            }
                            _record.updateIndicate[i] = false;
                        }
                    }
                }
                for (int i = 0; i < _enVars.Length; i++)
                {
                    string timeElaspe = @"Total Time: " + Math.Round(_record.Watch[i].ElapsedMilliseconds * 1.0 / (1000 * 60), 3).ToString();
                    lfa.StoreListToLinesAppend(Directory.GetCurrentDirectory() + @"\OUT\MOGA\" + _enVars[i].pmProblem["Name"] + @"\CEOutput_" + i.ToString(), new List <string>()
                    {
                        timeElaspe
                    });
                }
            });
            await monitor;

            Console.WriteLine("Mointor Closed.");
            return(0);
        }
        public async Task Close()
        {
            if (Document == null)
            {
                throw new InvalidOperationException("Trying to Close an unopened document");
            }

            await Document.CloseAsync();

            Document = null;

            if (local != null)
            {
                await local.End();

                local = null;
            }
        }
        public async Task <IDocument> Open()
        {
            if (Document != null)
            {
                throw new InvalidOperationException("Cannot Open already opened document");
            }

            if (local != null)
            {
                throw new InvalidOperationException("Cannot Open already locally accessed document");
            }

            local = await File.BeginLocalAccess();

            try {
                var doc = dctor(LocalFilePath);
                if (doc == null)
                {
                    throw new ApplicationException("CreateDocument must return a document");
                }

                if (!System.IO.File.Exists(LocalFilePath))
                {
                    Debug.WriteLine("CREATE " + LocalFilePath);
                    await doc.SaveAsync(LocalFilePath, DocumentSaveOperation.ForCreating);
                }
                else
                {
                    Debug.WriteLine("OPEN " + LocalFilePath);
                    await doc.OpenAsync();
                }
                Document = doc;
            } catch (Exception ex) {
                Document = null;
                Debug.WriteLine(ex);
            }

            return(Document);
        }
Exemple #7
0
        public void MOGA_Start()
        {
            LocalFileAccess lfa = new LocalFileAccess();

            _record.Watch[_runIndex].Start();
            MOGA_Initialization();
            int[] token = new int[1];
            Console.WriteLine("In Fitness Evaluation...");
            MOGA_FitnessEvaluation(token);
            while (token[0] == 0)
            {
                ;
            }
            token[0] = 0;
            MOGA_NormalizeFitness();
            PopulationGen(); //tmpPool -> cePool
            UpdateRecordAndDisplay();

            // Start MOGA
            while (gen < maxGen)
            {
                gen = gen + 1;
                Reproduction();
                MOGA_FitnessEvaluation(token);
                while (token[0] == 0)
                {
                    ;
                }
                token[0] = 0;
                MOGA_NormalizeFitness();
                PopulationGen();
                UpdateRecordAndDisplay();
            }
            _record.Watch[_runIndex].Stop();
            enVar.finishIndicate = true;
        }
Exemple #8
0
        private static List <InputTemplate> CheckAndGetInputContent(string inputFilePath)
        {
            var content = LocalFileAccess.ReadFile(inputFilePath);

            //if local file not exist
            if (content == null)
            {
                return(null);
            }
            try
            {
                //judge the input format match to input template
                return(JsonConvert.DeserializeObject <List <InputTemplate> >(content, new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                }));
            }
            catch (Exception e)
            {
                //if input json format not match to InputTemplate structure then failed.
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Exemple #9
0
        public static bool Run(string inputFilePath, string outputFilePath)
        {
            var inputJsonArray = CheckAndGetInputContent(inputFilePath);

            if (inputJsonArray == null)
            {
                return(false);
            }

            var outputObj     = GetRestAPIOutput(inputJsonArray);
            var outputJsonStr = JsonConvert.SerializeObject(outputObj, Formatting.Indented);
            var writeSuccess  = LocalFileAccess.WriteFile(outputFilePath, outputJsonStr);

            if (writeSuccess)
            {
                Console.WriteLine("Save file successfully!");
                return(true);
            }
            else
            {
                Console.WriteLine("Save file failed with errors.");
                return(false);
            }
        }
Exemple #10
0
        //
        // Helper function to get all the questions
        //
        private List <FlashCardModels> getAllFlashCards()
        {
            List <FlashCardModels> FCModels = new List <FlashCardModels>();
            // Grab list of csv.
            string FlashCardCSV = ControllerContext.HttpContext.
                                  Server.MapPath("~/Content/flashcards/animal-flashcards.csv");

            string[] Lines = LocalFileAccess.ReadFileLines(FlashCardCSV);
            // Build list of flash cards
            int Walker = -1;

            foreach (string Row in Lines)
            {
                // skip the first line
                Walker++;
                if (Walker == 0)
                {
                    continue;
                }
                string[]        items  = StringParser.FromCSV(Row, false);
                FlashCardModels Animal = new FlashCardModels()
                {
                    Name        = items[0],
                    DisplayName = items[0].Replace('-', ' '),
                    FileName    = items[1],
                    Clue1       = items[2],
                    Clue2       = items[3],
                    Clue3       = items[4],
                    Clue4       = items[5]
                };
                // Clean up displyname
                string [] DisplayNames = Animal.DisplayName.Split(' ');
                for (int i = 0; i < DisplayNames.Length; i++)
                {
                    string Name = DisplayNames[i];
                    if (string.Compare(Name.Trim(), "Large", true) != 0)
                    {
                        Name            = Char.ToUpper(Name[0]) + Name.Substring(1);
                        DisplayNames[i] = Name;
                    }
                }
                Animal.DisplayName = string.Join(" ", DisplayNames);
                FCModels.Add(Animal);
            }

            for (int i = 0; i < FCModels.Count; i++)
            {
                FlashCardModels FC = FCModels[i];
                if (i == 0)
                {
                    FC.Previous = FCModels[FCModels.Count - 1].Name;
                    FC.Next     = FCModels[i + 1].Name;
                }
                else if (i == (FCModels.Count - 1))
                {
                    FC.Next     = FCModels[i].Name;
                    FC.Previous = FCModels[i - 1].Name;
                }
                else
                {
                    FC.Previous = FCModels[i - 1].Name;
                    FC.Next     = FCModels[i + 1].Name;
                }
            }

            ControllerContext.HttpContext.Cache.Add("FeaturesFlashCardAnimals", FCModels,
                                                    new System.Web.Caching.CacheDependency(FlashCardCSV),
                                                    DateTime.MaxValue, TimeSpan.FromDays(1), System.Web.Caching.CacheItemPriority.Normal, null);
            return(FCModels);
        }
Exemple #11
0
        static async Task Main(string[] args)
        {
            string input = "";
            Dictionary <string, Category> categoryLookup = new Dictionary <string, Category>()
            {
                { "wishlist", Category.Wishlist },
                { "collection", Category.Collection }
            };

            IFileAccess      azureFileAccess = new AzureFileAccess(Constants.AzureFileConnectionString, Constants.AzureFileShareName);
            IFileAccess      localFileAccess = new LocalFileAccess();
            IAlbumRepository repository      = new SqlRepository(Constants.DbConnectionString);

            // IAlbumRepository repository = new JsonRepository(Constants.AzureFileFilepath, azureFileAccess);
            //IAlbumRepository repository = new JsonRepository(Constants.LocalFilePath, localFileAccess);
            //IAlbumRepository repository = new CosmosRepository(Constants.CosmosEndpointUri, Constants.CosmosPrimaryKey, Constants.CosmosDatabaseId, Constants.CosmosContainerId);

            while (input != "9")
            {
                Console.WriteLine("Main Menu");
                Console.WriteLine("1. Enter new Album");
                Console.WriteLine("2. Edit Album");
                Console.WriteLine("3. Display All");
                Console.WriteLine("4. Display Wishlist");
                Console.WriteLine("5. Display Collection");
                Console.WriteLine("6. Display filtered albums");
                Console.WriteLine("7. Display Totals");
                Console.WriteLine("8. Delete Album");
                Console.WriteLine("9. Exit");
                input = Console.ReadLine();

                if (input == "1")
                {
                    Console.Write("Artist: ");
                    string artist = Console.ReadLine();
                    Console.Write("Title: ");
                    string title = Console.ReadLine();
                    Console.Write("Year: ");
                    int year = 0;
                    int.TryParse(Console.ReadLine(), out year);
                    Console.Write("Format: ");
                    string format = Console.ReadLine();
                    Console.Write("Store: ");
                    string  store = Console.ReadLine();
                    decimal price = 0;
                    Console.Write("Price: ");
                    decimal.TryParse(Console.ReadLine(), out price);
                    Console.Write("Symbol: ");
                    string symbol = Console.ReadLine();
                    Console.Write("Location: ");
                    string   location = Console.ReadLine();
                    Category c        = Category.Wishlist;
                    categoryLookup.TryGetValue(location.ToLower(), out c);

                    await repository.Add(new Album()
                    {
                        Id       = 0,
                        Artist   = artist,
                        Title    = title,
                        Year     = year == 0 ? "" : year.ToString(),
                        Format   = format,
                        Store    = store,
                        Price    = price,
                        Symbol   = symbol,
                        Location = c
                    });
                }

                else if (input == "2")
                {
                    int id = 0;
                    Console.WriteLine("Edit Album");
                    Console.Write("Id to edit: ");
                    int.TryParse(Console.ReadLine(), out id);

                    Album e = await repository.GetBy(id);

                    if (e != null)
                    {
                        string   artist   = e.Artist;
                        string   title    = e.Title;
                        string   year     = e.Year;
                        string   format   = e.Format;
                        string   store    = e.Store;
                        decimal  price    = e.Price;
                        string   symbol   = e.Symbol;
                        Category location = e.Location;

                        Console.Write("Artist (" + artist + "): ");
                        string artistIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(artistIn))
                        {
                            e.Artist = artistIn;
                        }
                        Console.Write("Title (" + title + "): ");
                        string titleIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(titleIn))
                        {
                            e.Title = titleIn;
                        }
                        Console.Write("Year (" + year + "): ");
                        string yearIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(yearIn))
                        {
                            int y = 0;
                            int.TryParse(yearIn, out y);

                            e.Year = y == 0 ? "" : y.ToString();
                        }
                        Console.Write("Format (" + format + "): ");
                        string formatIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(formatIn))
                        {
                            e.Format = formatIn;
                        }
                        Console.Write("Store (" + store + "): ");
                        string storeIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(storeIn))
                        {
                            e.Store = storeIn;
                        }

                        Console.Write("Price (" + price + "): ");
                        string priceIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(priceIn))
                        {
                            decimal p = 0;
                            decimal.TryParse(priceIn, out p);

                            e.Price = p;
                        }

                        Console.Write("Symbol (" + symbol + "): ");
                        string symbolIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(symbolIn))
                        {
                            e.Symbol = symbolIn;
                        }
                        Console.Write("Location (" + location + "): ");
                        string locationIn = Console.ReadLine();
                        if (!string.IsNullOrEmpty(locationIn))
                        {
                            Category c = Category.Wishlist;
                            categoryLookup.TryGetValue(locationIn.ToLower(), out c);
                            e.Location = c;
                        }

                        await repository.Edit(e);
                    }
                    else
                    {
                        Console.WriteLine("Could not find album with id = " + id);
                    }
                }

                else if (input == "3")
                {
                    printAlbums(await repository.GetAll());
                }
                else if (input == "4")
                {
                    printAlbums(repository.GetAll().Result.Where(a => a.Location == Category.Wishlist));
                }
                else if (input == "5")
                {
                    printAlbums(repository.GetAll().Result.Where(a => a.Location == Category.Collection));
                }
                else if (input == "6")
                {
                    Console.Write("Filter Expression: ");
                    string filter = Console.ReadLine();

                    // var result = repository.GetFilteredAlbums(filter);
                    var result = GetFilteredAlbums(filter, repository.GetAll().Result);
                    printAlbums(result);
                }
                else if (input == "7")
                {
                    decimal wishListTotal   = repository.GetAll().Result.Where(a => a.Location == Category.Wishlist).Sum(a => a.Price);
                    decimal collectionTotal = repository.GetAll().Result.Where(a => a.Location == Category.Collection).Sum(a => a.Price);

                    Console.WriteLine("Wishlist total: " + wishListTotal.ToString("C", CultureInfo.CurrentCulture));
                    Console.WriteLine("Collection total: " + collectionTotal.ToString("C", CultureInfo.CurrentCulture));
                }
                else if (input == "8")
                {
                    Console.WriteLine("Delete album");
                    Console.Write("Id to delete: ");
                    string id       = Console.ReadLine();
                    int    parsedId = 0;
                    if (!int.TryParse(id, out parsedId))
                    {
                        Console.WriteLine("Id must be a number");
                        continue;
                    }
                    var a = await repository.GetBy(parsedId);

                    if (a != null)
                    {
                        Console.WriteLine("*** WARNING *** This operation cannot be undone. Please type the name of the album to delete below");
                        string titleToDelete = Console.ReadLine();
                        if (a.Title == titleToDelete)
                        {
                            await repository.Delete(a.Id);
                        }
                        else
                        {
                            Console.WriteLine("Album not found, nothing deleted");
                        }
                    }
                }

                else if (input == "9")
                {
                    Console.WriteLine("Bye");
                }
            }
        }
Exemple #12
0
        public void CACO_Start()
        {
            LocalFileAccess lfa = new LocalFileAccess();

            _record.Watch[_runIndex].Start();
            CACO_Initialization();
            int[] token = new int[1];
            Console.WriteLine("In Fitness Evaluation...");
            CACO_FitnessEvaluation(token);   //Find unqualied ce, find out test size, evaluate those
            while (token[0] == 0)
            {
                ;
            }
            token[0] = 0;
            Console.WriteLine("In Update Ranks, Parameters Update...");
            CACO_UpdateRanks();      // Update ranks for unqualified ce
            CACO_ParametersUpdate(); // Update the parameters for unqualified ce

            // Update Records
            List <string> generation = new List <string>()
            {
                gen.ToString()
            };
            List <string> currentCElist       = new List <string>();
            List <string> currentBestSolution = new List <string>();
            List <double> currentFitnessList  = new List <double>();

            Console.WriteLine("Generation: {0}", gen);
            for (int i = 0; i < cePool.Length; i++)
            {
                string dataOut = "CE: " + i.ToString() + ", " + "Fit: " + ceFitHistoryAry[i].Last().ToString();
                currentCElist.Add(dataOut);
                currentFitnessList.Add(ceFitHistoryAry[i].Last());
                Console.WriteLine(dataOut);
            }
            // Output CurrentBest Result;
            for (int i = 0; i < (int)enVar.pmProblem["NumOfCE"]; i++)
            {
                CACO3 currentBest = cePool[i].Keys.Where(x => x.rank == 1).First();
                _record.currentBestSolution[_runIndex][i] = Print_Solution(currentBest);
            }

            _record.currentGen[_runIndex]         = generation;
            _record.currentCElist[_runIndex]      = currentCElist;
            _record.currentFitnessList[_runIndex] = currentFitnessList;
            _record.updateIndicate[_runIndex]     = true;
            while (_record.updateIndicate[_runIndex] == true)
            {
                ;
            }

            // Start C-ACOs
            while (gen < maxGen)
            {
                gen = gen + 1;
                if (disQualifyCEAry.Sum() == 0)
                {
                    var a = cePool[0].First(x => x.Key.rank == 1);
                    break;
                }
                Console.WriteLine("In Solution Construction...");
                CACO_SolutionConstruction();
                Console.WriteLine("In Fitness Evaluations...");
                CACO_FitnessEvaluation(token);
                while (token[0] == 0)
                {
                    ;
                }
                token[0] = 0;
                Console.WriteLine("In Rank update and parameter update...");
                CACO_UpdateRanks();
                CACO_ParametersUpdate();

                Array.Clear(disQualifyCEAry, 0, disQualifyCEAry.Length);
                for (int i = 0; i < (int)enVar.pmProblem["NumOfCE"]; i++)
                {
                    disQualifyCEAry[2] = 0; //IMPORTANT: THIS IS ONLY FOR calday
                    disQualifyCEAry[6] = 0; //IMPORTANT: THIS IS ONLY FOR calday
                    if (ceFitHistoryAry[i].Last() < fitThreshold[0])
                    {
                        disQualifyCEAry[i] = 1;
                    }
                    else
                    {
                        if (usedgranttestinputs[i] == 0)
                        {
                            int worstPerformanceCEIndex = cePool.OrderBy(x => x.Values.Average(y => y[(int)enVar.evaToken]))
                                                          .Where(x => x.Keys.First().ceIndex != 2) //IMPORTANT This is only for CALDAY SUT
                                                          .Where(x => x.Keys.First().ceIndex != 6) //IMPORTANT This is only for CALDAY SUT
                                                          .First()
                                                          .Keys.First().ceIndex;
                            testSizeOfCEx[i] = 0;
                            testSizeOfCEx[worstPerformanceCEIndex] = testSizeOfCEx[worstPerformanceCEIndex] + initialtestsize;
                            usedgranttestinputs[i] = 1;
                        }
                    }
                    if (ceFitHistoryAry[i].Count > numOfRecordHistory)
                    {
                        ceFitHistoryAry[i].Dequeue();
                    }
                }

                // Update Records
                generation = new List <string>()
                {
                    gen.ToString()
                };
                currentCElist       = new List <string>();
                currentBestSolution = new List <string>();
                currentFitnessList  = new List <double>();
                Console.WriteLine("Generation: {0}", gen);
                for (int i = 0; i < cePool.Length; i++)
                {
                    string dataOut = "CE: " + i.ToString() + ", " + "Fit: " + ceFitHistoryAry[i].Last().ToString();
                    currentCElist.Add(dataOut);
                    currentFitnessList.Add(ceFitHistoryAry[i].Last());
                    Console.WriteLine(dataOut);
                }
                // Output CurrentBest Result;
                for (int i = 0; i < (int)enVar.pmProblem["NumOfCE"]; i++)
                {
                    CACO3 currentBest = cePool[i].Keys.Where(x => x.rank == 1).First();
                    _record.currentBestSolution[_runIndex][i] = Print_Solution(currentBest);
                }

                _record.currentGen[_runIndex]         = generation;
                _record.currentCElist[_runIndex]      = currentCElist;
                _record.currentFitnessList[_runIndex] = currentFitnessList;
                _record.updateIndicate[_runIndex]     = true;
                while (_record.updateIndicate[_runIndex] == true)
                {
                    ;
                }
            }
            _record.Watch[_runIndex].Stop();
            enVar.finishIndicate = true;
        }