public void GivenAEmptyBoard2By2_GameIsDraw__NoTokenWouldBeFlipped() { currentBoard = emptyBoard2By2; string winner = CalcGameOutcome(this.currentBoard, this.emptyBoard2By2, drawGame); Assert.AreEqual(drawGame, winner); }
//------------------------------------------------------------- /* Method: Reset(); */ public ActionResult Reset() { fruits = GenerateRandomFruits(); gameOver = false; score = 0; return RedirectToAction("Index"); }
public clsRarray(double[,] mat, string[] rows, string[] cols) { matrix = mat; mstrMatrix = null; rowNames = rows; colHeaders = cols; }
public void SetAllCharacterData () { charactersCSV = Resources.Load("CSV/characters") as TextAsset; avatarCSV = Resources.Load("CSV/avatar") as TextAsset; jobCSV = Resources.Load("CSV/job") as TextAsset; modeCSV = Resources.Load("CSV/mode") as TextAsset; personalityCSV = Resources.Load("CSV/personality") as TextAsset; stageCSV = Resources.Load("CSV/stage") as TextAsset; teamCSV = Resources.Load("CSV/team") as TextAsset; weakModeCSV = Resources.Load("CSV/weakMode") as TextAsset; workModeCSV = Resources.Load("CSV/workMode") as TextAsset; print (charactersCSV.text); characterDataBase = CSVReader.SplitCsvGrid(charactersCSV.text); avatarDataBase = CSVReader.SplitCsvGrid(avatarCSV.text); jobDataBase = CSVReader.SplitCsvGrid(jobCSV.text); modeDataBase = CSVReader.SplitCsvGrid(modeCSV.text); personalityDataBase = CSVReader.SplitCsvGrid(personalityCSV.text); stageDataBase = CSVReader.SplitCsvGrid(stageCSV.text); teamDataBase = CSVReader.SplitCsvGrid(teamCSV.text); weakModeDataBase = CSVReader.SplitCsvGrid(weakModeCSV.text); workModeDataBase = CSVReader.SplitCsvGrid(workModeCSV.text); }
public override void Initialize() { screenWidth = ScreenManager.GraphicsDevice.Viewport.Width; screenHeight = ScreenManager.GraphicsDevice.Viewport.Height; colorDataList = new List<byte[]>(); player = new Player(); generator = new ItemsGenerator(); current = generator.GenerateMore(); bgLayer1 = new ParallaxingBackground(); bgLayer2 = new ParallaxingBackground(); bgLayer3 = new ParallaxingBackground(); bar = new Bar(100, 20, 15, 270, 30); score = new Score(870, 10, Color.Peru); currentSprite = new List<Sprite>(); items = new List<Texture2D>(); songs = new Song[2]; soundEffects = new SoundEffect[10]; updateImmunityCounter = 0; alertTimer = 0; playQueue = 1; displayAlert = false; enablePause = true; Constants.ResetFlags(); player.Initialize(); base.Initialize(); }
private static void Main(string[] args) { ConsoleMio.Setup(); while ((maze = TestMazeFactory.GetNext()) != null) { ConsoleMio.PrintHeading("Task 14 Minimal Distances In The Labyrinth Of Doom"); ConsoleMio.WriteLine("Labyrinth Before: ", DarkCyan); PrintLabyrinth(maze); ConsoleMio.WriteLine(); unexploredPositions = new LinkedQueue<MatrixPosition>(); DoNextLabyrinth(); ConsoleMio.WriteLine("Labyrinth After: ", DarkGreen); PrintLabyrinth(maze); ConsoleMio.WriteLine(); ConsoleMio.WriteLine("Press a key to test the next labyrinth...", DarkRed); Console.ReadKey(true); Console.Clear(); } ConsoleMio.WriteLine( "Completed!!! Thank you very much for looking all the tasks!", DarkGreen); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack && Session["field"] != null) { LoadButtons(); } if (Session["field"] == null) { this.field = new string[3, 3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { this.field[i, j] = string.Empty; } } Session.Add("field", this.field); Session.Add("turns", 0); } else { this.field = (string[,])Session["field"]; this.turns = (int)Session["turns"]; } }
public static void Main() { //const int n = 5; //matrix = new string[n, n] //{ // {"s", " ", " ", " ", " "}, // {" ", "*", " ", "*", " "}, // {" ", "*", "*", "*", " "}, // {" ", "*", " ", "*", " "}, // {" ", " ", " ", " ", "e"}, //}; //100 on 100 gives stack overflow exception. matrix = GenerateEmptyMatrix(40, 40); path = new List<char>(); try { FindPaths(0, 0, 'S'); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } }
public Business() { DBData = new NorthWindAccess(); updateCustomerInformation(); updateProductsInformation(); updateEmployeesInformation(); updateCategoryInformation(); updateShippersInformation(); updateSupplierInformation(); nameAndIds = getCustomerNamesAndIDs(); employees = getEmployeesInformation(); //pictures = DBData.getPictures(); pictureList = getCategoryPictureList(); DBData.employeeInfChange += new Update(updateEmployeesInformation); DBData.customerInfChange += new Update(updateCustomerInformation); DBData.productInfChange += new Update(updateProductsInformation); DBData.categoryInfChange += new Update(updateCategoryInformation); DBData.ShipperInfChange += new Update(updateShippersInformation); DBData.SupplierInfChange += new Update(updateSupplierInformation); Application.Run(new frmControl(this)); }
public void CreateMatrix() { switch (chosenLevel) { case 1: levelMatrix = Levels.LevelOne(); break; case 2: levelMatrix = Levels.LevelTwo(); break; case 3: levelMatrix = Levels.LevelThree(); break; default: levelMatrix = Levels.LevelOne(); Console.Clear(); Console.SetCursorPosition(0, 0); Console.WriteLine("Error occured with the level choice.\nThe entered level is: {0}. Level 1 will be chosen by default.", chosenLevel); break; } //to position the cursor matrixOffsetX = (Console.WindowWidth - levelMatrix.GetLength(0)) / 2; matrixOffsetY = (Console.WindowHeight - levelMatrix.GetLength(1)) / 2 + 4; //getting the matrix borders to limit the player movements(to not be able to move outside the matrix) leftBorder = matrixOffsetX; rightBorder = matrixOffsetX + (levelMatrix.GetLength(0) - 1); topBorder = matrixOffsetY; bottomBorder = matrixOffsetY + (levelMatrix.GetLength(1) - 1); }
void Gather() { numQuestions = TriviaLoadScript.GetNumberOfQuestion(); questions = TriviaLoadScript.GetQuestions(); answers = TriviaLoadScript.GetAnswers(); correct = TriviaLoadScript.GetCorrectAnswers(); // Gather question location question = GameObject.Find("Question").GetComponent<Text>(); // Gather answer locations and contents answerButtons = GameObject.Find("Buttons").GetComponentsInChildren<Button>(); answerButtonTexts = GameObject.Find("Buttons").GetComponentsInChildren<Text>(); // Gather response location response = GameObject.Find("Response").GetComponent<Text>(); // Gather next button location next = GameObject.Find("btn_Next"); // Gather counter locations questionNumber = GameObject.Find("QuestionsCount").GetComponent<Text>(); currentScore = GameObject.Find("ScoreCount").GetComponent<Text>(); // Gather endgame info gameEndScreen = GameObject.Find("GameOver").GetComponent<Image>(); gameOverText = GameObject.Find("GameOver").GetComponentsInChildren<Text>(); finalScore = GameObject.Find("FinalScore").GetComponent<Text>(); resetButton = GameObject.Find("RestartButton"); endGameButton = GameObject.Find("EndGame"); SendMessage("Begin"); }
private void button2_Click(object sender, EventArgs e) { switch (comboBox1.Text) { case "Amun-Ra": { Hero1 = amun_ra; selected1 = true; break; } default: selected1 = false; break; } switch (comboBox3.Text) { case "War Beast": { Hero2 = war_beast; selected2 = true; break; } default: selected2 = false; break; } if (selected1 == true && selected2 == true) { Choose2(Hero1, Hero2); selected1 = selected2 = false; } }
public CLSCOBO_ConsolidationEngine(CLSCOBO_ConsolidationProblem po_ConsolidationProblem) { ao_ConsolidationSolutions = new List<CLSCOBO_ConsolidationSolution>(); as_PointsDistanceMatrix = FillInDistancesMatrix(po_ConsolidationProblem); for(int vi_IterationTotal=1;vi_IterationTotal<=1;vi_IterationTotal++) { vo_ConsolidationSolutions=new List<CLSCOBO_ConsolidationSolution>(); for(int vi_Iteration=0;vi_Iteration<2;vi_Iteration++) { vo_ConsolidationSolution=null; CLSCOBO_ConsolidationSolution vo_PreviousConsolidationSolution=null; if(vi_Iteration==0) { vo_ConsolidationSolution=new CLSCOBO_ConsolidationSolution(po_ConsolidationProblem); vo_ConsolidationSolutions.Add(vo_ConsolidationSolution); } else { vo_PreviousConsolidationSolution=vo_ConsolidationSolutions[0]; while(vo_PreviousConsolidationSolution.TruckItineraries.Count>4) { vo_ConsolidationSolution=new CLSCOBO_ConsolidationSolution(vo_PreviousConsolidationSolution.TruckItineraries, vi_Iteration); if(vo_ConsolidationSolution.TruckItineraries.Count!=0) { vo_ConsolidationSolutions.Add(vo_ConsolidationSolution); } vo_PreviousConsolidationSolution=vo_ConsolidationSolutions[vo_ConsolidationSolutions.Count-1]; } } } ao_ConsolidationSolutions.AddRange(vo_ConsolidationSolutions); vo_ConsolidationSolutions=null; } }
public clsRarray() { matrix = null; mstrMatrix = null; rowNames = null; colHeaders = null; }
public clsRarray(double[,] mat, string[] rows, string col) { matrix = mat; mstrMatrix = null; rowNames = rows; colHs = col; }
private void button1_Click(object sender, EventArgs e) { if (comboBox1.Text == "Amun-Ra") { Hero = amun_ra; Choose2(amun_ra, war_beast); } }
public LabyrinthSolver(string[,] labyrinth) { this.labyrinth = (string[,])labyrinth.Clone(); if (!this.InitialiseStartPoint(this.labyrinth)) { throw new ArgumentException("Labyrinth do not contains expected start point."); } }
void Start() { if (!newElementClass){newElementClass = this;} else{return;} elementsMultiplier = CSVReader.SplitCsvGrid (elementsSchemeCSV.text); GetMultiplayerForAttackerElement (GameElement.NORMAL,GameElement.NORMAL); }
public BaseAdapter (string database) { con = null; cmd = null; dataAdapter = null; dataset = null; setOfChanges = null; configDoc = (XmlNode) ConfigurationSettings.GetConfig (database); }
public void GivenAnEmptyReversiBoardOneByOne_WhenBlackPlacesToken_BlackWins() { string blackPlayer = "black"; currentBoard = this.emptyBoardOneByOne; string winner = CalcGameOutcome(this.currentBoard, this.emptyBoardOneByOne, "black"); Assert.AreEqual(blackPlayer, winner); }
public int ySize; //the number of the rows of the matrix #endregion Fields #region Constructors // class constructor public RandomStringMatrix( int rows, int columns) { this.xSize = rows; this.ySize = columns; // build a matrix with size xSize columns and ySize rows // and populate it with random strings from stringList this.matrix = BuildRandomStringMatrix(this.ySize, this.xSize, this.stringList); // do the actual work FindLongestSequence(this.matrix); }
IEnumerator firstdelay(float time) { yield return new WaitForSeconds(time); usersinfo = GlobalObject.getusers (); if (usersinfo [0, 0] == uid) { offset = -50f; } else { offset = 50f; } }
public void GivenAnSimplestReversiBoardEver_NoTokenPlacementPossible() { int expectedTokenPossibilitiesCount = 0; Func<int> computePossibleNumberOfPlacements = () => 2; currentBoard = this.emptyBoard0By0; int tokenPlacementPossiblitiesCount = currentBoard == this.emptyBoard0By0 ? 0 : computePossibleNumberOfPlacements(); Assert.AreEqual(expectedTokenPossibilitiesCount, tokenPlacementPossiblitiesCount); }
// Use this for initialization void Start() { talks = CSVReader.SplitCsvGrid(csv.text); row = 0; col = 4; talkText.text = talks[col,0] + " : " + talks[col,row]; //print(talks[row,cal]); talkText.text = talks[col,row]; }
// Update is called once per frame void Update() { if(DoSetUpNow) { dataMatrix = CSVReader.SplitCsvGrid(dataSource.text); //GeneratePlotNumberBasedOnName(); DoSetUpNow = false; } }
private void expendictionnary() { //Console.WriteLine("This function is not implemented yet"); string[,] newDict = new string[indexe * 2 , 2]; for (int row = 0; row < dict.GetLength(0); row++) { newDict[row, 0] = this.dict[row, 0]; newDict[row, 1] = this.dict[row, 1]; } this.dict = newDict; }
protected void Page_Load(object sender, EventArgs e) { theStaff = (staff)Session["Staff"]; order[] getAllStaffOrder = DBModel.sharedDBModel().getAllOrderInfo(theStaff.staffId); for (int i = 0; i < 5; i++) { getStaffOrder[i] = getAllStaffOrder[i]; } orderMonthChart = DBModel.sharedDBModel().getEverySumOfThisMonth(theStaff.staffId); hotItems = DBModel.sharedDBModel().topFiveItems(theStaff.staffId); System.Diagnostics.Debug.WriteLine("size of the hotItems:" + hotItems.GetLength(0)); }
private void Form_Load(object sender, EventArgs e) { helpTopics = _XmlEngine.PullHelpTopics(); helpContent = _XmlEngine.PullHelpContent(); for (int x = 0; x <= helpTopics.GetUpperBound(0); x++) { TreeNode tmpNode = new TreeNode(helpTopics[x, 1]); tmpNode.Tag = helpTopics[x, 0].ToString(); treTopics.Nodes.Add(tmpNode); } }
private void button2_Click(object sender, EventArgs e) { stop = false; winner = ""; which_piece = x.clear(which_piece); Invalidate(); button2.Enabled = false; count = 0; firstturn = true; cPUToolStripMenuItem.Enabled = false; playerToolStripMenuItem.Enabled = false; }
public void Start() { mapData = null; mapWidth = mapHeight = mapSize = 0; //var allResource = Resources.LoadAll("Level"); //for(int a = 0; a < allResource.Length; ++a) { //Object filenames = allResource[a]; //levelName.Add(a + 1, filenames.name); } }
static void Main(string[] args) { Random rnd = new Random(); //это для заполнения массива string userInput; do { Console.WriteLine("Выберите пункт домашнего задания (цифры 1-5, exit или q-для выхода)"); userInput = Console.ReadLine().ToLower(); switch (userInput) { case "1": { // вывести диагональ двумерного массива Console.Clear(); uint arrayDim; do { Console.Write("Введите размер n для массива [n*n]: "); } while (!uint.TryParse(Console.ReadLine(), out arrayDim) || arrayDim == 0); int[,] array = new int[arrayDim, arrayDim]; //в этом цикле заполняем массив случайными значениями for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { array[i, j] = rnd.Next(10, 100); if ((i == j) || (j == (array.GetLength(1) - i - 1))) { Console.ForegroundColor = ConsoleColor.Green; Console.Write(array[i, j] + " "); Console.ResetColor(); } else { Console.Write(array[i, j] + " "); } } Console.WriteLine(); } Console.WriteLine("\nПервая диагональ:"); for (int i = 0; i < array.GetLength(0); i++) { Console.Write(array[i, i] + " "); } Console.WriteLine("\nВторая диагональ:"); for (int i = array.GetLength(0) - 1; i >= 0; i--) { Console.Write(array[i, array.GetLength(1) - i - 1] + " "); } Console.WriteLine(); } break; case "2": { // Телефонный справочник: массив 5х2 Console.Clear(); string[,] userList = { { "Alice", "Bob", "Chuck", "Don", "Eva" }, { "651981", "6489", "8495", "4577", "3216849" } }; Console.WriteLine("Имя\t\tКонтакт\n"); for (int i = 0; i < userList.GetLength(1); i++) { Console.WriteLine($"{userList[0, i]}\t\t{userList[1, i]}"); } Console.WriteLine(); } break; case "3": { // Написать программу, выводящую введённую пользователем строку в обратном порядке Console.Clear(); Console.WriteLine("Введите строку:"); string userString = Console.ReadLine(); Console.WriteLine("Перевернутая строка:"); for (int i = userString.Length; i > 0; i--) { Console.Write(userString[i - 1]); } Console.WriteLine(); } break; case "4": { //Смещение элементов одномерного массива на заданное количество позиций Console.Clear(); uint arraySize; do { Console.Write($"Введите количество элементов массива: "); } while (!uint.TryParse(Console.ReadLine(), out arraySize) || arraySize == 0); int[] arr = new int[arraySize]; Console.WriteLine("Массив заполнен случайными значениями:"); for (int i = 0; i < arr.Length; i++) { arr[i] = rnd.Next(10, 100); Console.Write(arr[i] + " "); } int offset, tmp; do { Console.Write("\nВведите сдвиг: "); } while (!int.TryParse(Console.ReadLine(), out offset)); offset %= arr.Length; // противодействие лишним вычислениям если пользователь ввёл сдвиг больше длины массива #region Сдвигаем циклически if (offset > 0) // 0 не рассматриваем, т.к. ничего никуда не перемещается { //выполняем если сдвиг положительный for (int i = 0; i < offset; i++) { tmp = arr[arr.Length - 1]; for (int j = arr.Length - 2; j >= 0; j--) { arr[j + 1] = arr[j]; } arr[0] = tmp; } } if (offset < 0) { //выполняем если сдвиг отрицательный for (int i = 0; i > offset; i--) { tmp = arr[0]; for (int j = 0; j < arr.Length - 1; j++) { arr[j] = arr[j + 1]; } arr[arr.Length - 1] = tmp; } } #endregion Console.WriteLine("Результат:"); for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } break; case "5": { //TODO *«Морской бой»: вывести на экран массив 10х10, состоящий из символов X и O, где Х — элементы кораблей, а О — свободные клетки Console.Clear(); char[,] sea = { { 'X', 'O', 'O', 'X', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'X', 'O', 'O', 'X', 'O', 'O', 'O', 'O', 'X', 'O' }, { 'O', 'O', 'O', 'X', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'X', 'O', 'O', 'O', 'O', 'X', 'O', 'O', 'O' }, { 'O', 'X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'X', 'O', 'X', 'X', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'X', 'X', 'X', 'O', 'X', 'X', 'O', 'O', 'O', 'X' }, }; for (int i = 0; i < sea.GetLength(0); i++) //показали итоговый массив { for (int j = 0; j < sea.GetLength(1); j++) { if (sea[i, j] == 'O') { Console.ForegroundColor = ConsoleColor.Blue; } if (sea[i, j] == 'X') { Console.ForegroundColor = ConsoleColor.Green; } Console.Write(" " + sea[i, j]); } Console.WriteLine(); } Console.ResetColor(); } break; case "q": case "Q": { userInput = "exit"; } break; default: { Console.WriteLine("Введено что-то непонятное, повторите ввод"); } break; } } while (userInput != "exit"); }
} // isAlertPresent() public void link_mv(string target_link, string[,] sum_link, int arr_first, int arr_sec, string[] info) { if (dr != null) { try { dr.Url = target_link + sum_link[arr_first, arr_sec]; } catch { dr = new ChromeDriver(); dr.Url = "https://door.deu.ac.kr/sso/login.aspx"; IWebElement ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[2]/input")); ele.Clear(); ele.SendKeys(info[0]); ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[2]/td/input")); ele.Clear(); ele.SendKeys(info[1]); dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[3]/a")).Click(); dr.Url = target_link + sum_link[arr_first, arr_sec]; } //driverService.HideCommandPromptWindow = true; } else { dr = new ChromeDriver(); dr.Url = "https://door.deu.ac.kr/sso/login.aspx"; IWebElement ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[2]/input")); ele.Clear(); ele.SendKeys(info[0]); ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[2]/td/input")); ele.Clear(); ele.SendKeys(info[1]); dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[3]/a")).Click(); dr.Url = target_link + sum_link[arr_first, arr_sec]; //driverService.HideCommandPromptWindow = true; //if (dr != null) //{ // dr.Url = lectureDoweek + room_code[cB_site.SelectedIndex, 0]; // driverService.HideCommandPromptWindow = true; //} //else //{ // dr = new ChromeDriver(); // dr.Url = "https://door.deu.ac.kr/sso/login.aspx"; // IWebElement ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[2]/input")); // ele.Clear(); // ele.SendKeys(id); // ele = dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[2]/td/input")); // ele.Clear(); // ele.SendKeys(pwd); // dr.FindElement(By.XPath("/html/body/form/div[2]/div[1]/div/table/tbody/tr[1]/td[3]/a")).Click(); // dr.Url = lectureRoom_door + room_code[cB_site.SelectedIndex, 0]; // driverService.HideCommandPromptWindow = true; //} } }
private static string Tens(string[,] numbers, int t, int d) { return(t > 1 ? $" {numbers[1, t]}" + $" {numbers[0, d]}" : t == 1 ? $" {numbers[2, d]}" : $" {numbers[0, d]}"); }
static void Main(string[] args) { string[,] matrix = { { "ha", "fifi", "ho" }, { "fo", "ha", "hi" }, { "xxx", "ho", "ha" } }; string currentStr = ""; string mostCommonstr = ""; int lenght = 1; int bestLenght = 1; // row test for (int row = 0; row < 3; row++) { for (int col = 0; col < 2; col++) { currentStr = matrix[row, col]; if (currentStr == matrix[row, col + 1]) { lenght++; if (lenght > bestLenght) { bestLenght = lenght; mostCommonstr = currentStr; } } else { lenght = 1; } } } //col test lenght = 1; for (int col = 0; col < 3; col++) { for (int row = 0; row < 2; row++) { currentStr = matrix[col, row]; if (currentStr == matrix[col, row + 1]) { lenght++; if (lenght > bestLenght) { bestLenght = lenght; mostCommonstr = currentStr; } } else { lenght = 1; } } } // diagonal test lenght = 1; for (int row = 0; row < 2; row++) { for (int col = 0; col < 2; col++) { currentStr = matrix[row, col]; if (currentStr == matrix[row + 1, col + 1]) { lenght++; if (lenght > bestLenght) { bestLenght = lenght; mostCommonstr = currentStr; } } } } Console.WriteLine($"The best lenght is: {bestLenght}"); Console.WriteLine(); Console.Write("{ "); for (int i = 0; i < bestLenght; i++) { Console.Write(mostCommonstr + " "); } Console.WriteLine("}"); }
private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, Dictionary <int, bool> defaultChoiceKeys, bool shouldEmulateForMultipleChoiceSelection) { System.Management.Automation.Diagnostics.Assert(defaultChoiceKeys != null, "defaultChoiceKeys cannot be null."); ConsoleColor fg = RawUI.ForegroundColor; ConsoleColor bg = RawUI.BackgroundColor; int lineLenMax = RawUI.WindowSize.Width - 1; int lineLen = 0; string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { ConsoleColor cfg = PromptColor; if (defaultChoiceKeys.ContainsKey(i)) { // Should be a skin lookup cfg = DefaultPromptColor; } string choice = String.Format( CultureInfo.InvariantCulture, choiceTemplate, hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i]); WriteChoiceHelper(choice, cfg, bg, ref lineLen, lineLenMax); if (shouldEmulateForMultipleChoiceSelection) { WriteLineToConsole(); } } WriteChoiceHelper( ConsoleHostUserInterfaceStrings.PromptForChoiceHelp, fg, bg, ref lineLen, lineLenMax); if (shouldEmulateForMultipleChoiceSelection) { WriteLineToConsole(); } string defaultPrompt = ""; if (defaultChoiceKeys.Count > 0) { string prepend = ""; StringBuilder defaultChoicesBuilder = new StringBuilder(); foreach (int defaultChoice in defaultChoiceKeys.Keys) { string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; if (string.IsNullOrEmpty(defaultStr)) { defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } defaultChoicesBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0}{1}", prepend, defaultStr)); prepend = ","; } string defaultChoices = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) { defaultPrompt = shouldEmulateForMultipleChoiceSelection ? StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoiceForMultipleChoices, defaultChoices) : StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoicePrompt, defaultChoices); } else { defaultPrompt = StringUtil.Format(ConsoleHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, defaultChoices); } } WriteChoiceHelper(defaultPrompt, fg, bg, ref lineLen, lineLenMax); }
public List <RequestRow> GetAllRequests() { List <RequestRow> requestList = new List <RequestRow>(); List <string> randomNames = new List <string>() { "Joe Smith", "Sophia-Rose Bush", "Shabaz Zavala", "Zach Sheppard", "Kierran Johnston", "Aliya Dolan", "Kurt Bassett", "Lilly-May Larson", "Ellie-May Murray", "Jasmin Bradshaw", "Matei Hackett", "Fredrick Mahoney", "Miles Boyer", "Nikodem Cairns", "Suman Metcalfe", "Hari Shepherd", "Krystal Sparks", "Melisa Hamilton", "Lottie Nixon", "Kacey Rios", "Adem Giles", "Isla-Mae Bellamy", "Nikki Odom", "Samirah Burrows", "Alice Gordon", "Lavinia Olsen", "Tom Braun", "Yosef Molina", "Nabila Harris", "Hasan Forster", "Kester Gale", "Henna Mckee", "Anne-Marie Howell", "Anastazja Mcguire", "Lorelei Bowes", "Alvin Kaye", "Ronnie Hobbs", "Umaima Whelan", "Jannat Dalby", "Hamaad Robinson", "Shaunna Humphrey", "Farhaan Conley", "Bryan Wardle", "Brandon Carpenter", "Leigha Garrison", "Jay Felix", "Landon Ferreira", "Caine Haigh", "Emilio Trujillo", "Humera Willis", "Saara Krueger", "Roma Sweeney", "Malak Macleod", "Nellie Southern", "Marcie Noble", "Huzaifah Curtis", "Kendall Forrest", "Jayden-Lee Almond", "Clifford Hartley", "Shae Rayner", "Charlotte Traynor", "Sofia Leon", "Ibrar Saunders", "Omari Connelly", "Yousaf Jeffery", "Nyle Shields", "Vinnie Hatfield", "Humaira Davey", "Marguerite Hough", "Abbie Mason", "Luella Chaney", "Teigan Hail", "Renzo Strong", "Yahya Sutton", "Elwood Kaur", "Lily-Grace Arias", "Franco Owen", "Kaiden Rocha", "Angelica Cisneros", "Nico Hall", "Isaac Shea", "Barbara Britt", "Akbar Tierney", "Lillia Sosa", "Agatha Andersen", "Maude John", "Tayla Mccallum", "Aairah Perry", "Rory Greer", "Komal East", "Shyam Porter", "Brendon Torres", "Velma Sanderson", "Cleveland Kemp", "Patrick Moody", "Tyron Downes", "Ruby-Rose Wheatley", "Adnaan Figueroa", "Terence Miles", "Charlton Mathis", "Greyson Monroe" }; List <string> randomStaffs = new List <string>() { "Ida Ghahremani", "Kay Nadalin ", "Samir Sheikh ", "Paul Delannoy", "Gunanayagam", "Tibo Phung" }; List <string> processingPhases = new List <string>() { "New", "Initial Review", "On Hold", "Completed" }; string[,] certificates = { { "0", " ", " " }, { "1", "2010-M500-NC-LCWV.", "CAPITAINE, JAUGE BRUTE 500, À PROXIMITÉ DU LITTORAL (M500-NC-LCWV)." }, { "2", "ABLE SEAFARER DECK", "MARIN QUALIFIÉ PONT" }, { "3", "ADVANCED FIRE FIGHTING", "TECHNIQUES AVANCÉES DE LUTTE CONTRE L'INCENDIE" }, { "4", "ADVANCED TRAINING FOR CHEMICAL TANKER CARGO OPERATIONS", "FORMATION AVANCÉE AUX OPÉRATIONS LIÉES À LA CARGAISON DES NAVIRES-CITERNES POUR PRODUITS CHIMIQUES" }, { "7", "ADVANCED TRAINING FOR LIQUEFIED GAS TANKER CARGO OPERATIONS", "FORMATION AVANCÉE AUX OPÉRATIONS LIÉES À LA CARGAISON DES NAVIRES-CITERNES POUR GAZ LIQUÉFIÉS" }, { "10", "ADVANCED TRAINING FOR OIL TANKER CARGO OPERATIONS", "FORMATION AVANCÉE AUX OPÉRATIONS LIÉES À LA CARGAISON DES PÉTROLIERS" }, { "13", "ADVANCED TRAINING FOR PERSONNEL ON SHIPS OPERATING IN POLAR WATERS", "FORMATION AVANCÉE POUR LE PERSONNEL DE BÂTIMENTS NAVIGUANT DANS LES EAUX POLAIRES" }, { "14", "Advanced Training For Personnel On Ships Operating In Polar Waters ", "Formation avancée pour le personnel de bâtiments naviguant dans les eaux polaires " }, { "15", "BASIC TRAINING FOR LIQUEFIED GAS TANKER CARGO OPERATIONS - OFFICER", "FORMATION DE BASE AUX OPÉRATIONS LIÉES À LA CARGAISON DES NAVIRES-CITERNES POUR GAZ LIQUÉFIÉS - OFFICIER" }, { "18", "BASIC TRAINING FOR LIQUEFIED GAS TANKER CARGO OPERATIONS - RATING", "FORMATION DE BASE AUX OPÉRATIONS LIÉES À LA CARGAISON DES NAVIRES-CITERNES POUR GAZ LIQUÉFIÉS - MATELOT" }, { "21", "BASIC TRAINING FOR OIL AND CHEMICAL TANKER CARGO OPERATIONS - OFFICER", "FORMATION DE BASE AUX OPÉRATIONS LIÉES À LA CARGAISON DES PÉTROLIERS ET DES NAVIRES-CITERNES POUR PRODUITS CHIMIQUES - OFFICIER" }, { "24", "BASIC TRAINING FOR OIL AND CHEMICAL TANKER CARGO OPERATIONS - RATING", "FORMATION DE BASE AUX OPÉRATIONS LIÉES À LA CARGAISON DES PÉTROLIERS ET DES NAVIRES-CITERNES POUR PRODUITS CHIMIQUES - MATELOT" }, { "27", "BASIC TRAINING FOR PERSONNEL ON SHIPS IN POLAR WATERS", "FORMATION DE BASE POUR LE PERSONNEL DE BATIMENTS NAVIGUANT DANS LES EAUX POLAIRES " }, { "28", "BRIDGE WATCH RATING", "MATELOT DE QUART À LA PASSERELLE" }, { "29", "Basic Training For Personnel On Ships Operating In Polar Waters ", "Formation de base pour le personnel de bâtiments naviguant dans les eaux polaires" }, { "30", "CERTIFICATE OF PROFICIENCY IN ADVANCED TRAINING FOR PERSONNEL ON SHIPS OPERATING IN POLAR WATERS ", "CERTIFICAT D'APTITUDE EN FORMATION AVANCÉE POUR LE PERSONNEL DE BATIMENTS NAVIGUANT DANS LES EAUX POLAIRES " }, { "31", "CERTIFICATE OF PROFICIENCY IN BASIC TRAINING FOR PERSONNEL ON SHIPS OPERATING IN POLAR WATERS", "CERTIFICAT D'APTITUDE EN FORMATION DE BASE POUR LE PERSONNEL DE BATIMENT NAVIGUANT DANS LES EAUX POLAIRES " }, { "32", "CHIEF ENGINEER, MOTORSHIP", "CHEF MÉCANICIEN, NAVIRE À MOTEUR" }, { "33", "CHIEF ENGINEER, STEAMSHIP", "CHEF MÉCANICIEN, NAVIRE À VAPEUR" }, { "34", "CHIEF MATE", "PREMIER OFFICIER DE PONT" }, { "35", "CHIEF MATE, NEAR COASTAL", "PREMIER OFFICIER DE PONT, À PROXIMITÉ DU LITTORAL" }, { "36", "CHIEF MATE.", "PREMIER OFFICIER DE PONT." }, { "37", "Certificate Of Proficiency In Advanced Training For Personnel On Ships Operating In Polar Waters ", "Certificat d’aptitude en formation avancée pour le personnel de bâtiments naviguant dans les eaux polaires " }, { "38", "Certificate Of Proficiency In Basic Training For Personnel On Ships Operating In Polar Waters ", "Certificat d’aptitude en formation de base pour le personnel de bâtiments naviguant dans les eaux polaires " }, { "39", "ENGINE-ROOM RATING", "MATELOT DE LA SALLE DES MACHINES" }, { "40", "FAST RESCUE BOATS", "EXPLOITATION DES CANOTS DE SECOURS RAPIDES" }, { "43", "FIRST MATE LONG RUN FERRY", "PREMIER LIEUTENANT DE TRANSBORDEUR À TRAJET LONG" }, { "44", "FIRST-CLASS ENGINEER, MOTOR SHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À MOTEUR" }, { "45", "FIRST-CLASS ENGINEER, MOTOR SHIP AND STEAMSHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À MOTEUR ET NAVIRE À VAPEUR" }, { "46", "FIRST-CLASS ENGINEER, MOTOR SHIP FOURTH-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À VAPEUR" }, { "47", "FIRST-CLASS ENGINEER, MOTOR SHIP SECOND-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À VAPEUR " }, { "48", "FIRST-CLASS ENGINEER, MOTOR SHIP THIRD-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À VAPEUR" }, { "49", "FIRST-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE PREMIÈRE CLASSE, NAVIRE À VAPEUR" }, { "50", "FOURTH-CLASS ENGINEER, MOTOR SHIP", "OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À MOTEUR" }, { "51", "FOURTH-CLASS ENGINEER, MOTOR SHIP AND STEAMSHIP", "OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À MOTEUR ET NAVIRE À VAPEUR" }, { "52", "FOURTH-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À VAPEUR" }, { "53", "MARINE ADVANCED FIRST AID", "SECOURISME AVANCÉ EN MER" }, { "54", "MARINE MEDICAL CARE", "SOINS MÉDICAUX EN MER" }, { "55", "MASTER 3000 GROSS TONNAGE, NEAR COASTAL", "CAPITAINE, BÂTIMENT D'UNE JAUGE BRUTE DE 3000, À PROXIMITÉ DU LITTORAL" }, { "56", "MASTER 500 GROSS TONNAGE, NEAR COASTAL (M500-NC)", "CAPITAINE, BÂTIMENT D'UNE JAUGE BRUTE DE 500, À PROXIMITÉ DU LITTORAL (M500-NC)" }, { "57", "MASTER 500 GROSS TONNAGE, NEAR COASTAL (M500-NC-LCWV)", "CAPITAINE, JAUGE BRUTE 500, À PROXIMITÉ DU LITTORAL (M500-NC-LCWV)" }, { "58", "MASTER 500 GROSS TONNAGE, NEAR COASTAL (M500-NC-TNC2)", "CAPITAINE, BÂTIMENT D'UNE JAUGE BRUTE DE 500, À PROXIMITÉ DU LITTORAL (M500-NC-TNC2)" }, { "59", "MASTER 500 GROSS TONNAGE, NEAR COASTAL (M500-T3000)", "CAPITAINE, BÂTIMENT D'UNE JAUGE BRUTE DE 500, À PROXIMITÉ DU LITTORAL (M500-T3000)" }, { "60", "MASTER MARINER", "CAPITAINE AU LONG COURS" }, { "61", "MASTER NEAR COASTAL", "CAPITAINE À PROXIMITÉ DU LITTORAL" }, { "62", "PASSENGER SAFETY MANAGEMENT", "GESTION DE LA SÉCURITÉ DES PASSAGERS" }, { "63", "SECOND ENGINEER, MOTORSHIP", "MÉCANICIEN EN SECOND, NAVIRE À MOTEUR" }, { "64", "SECOND ENGINEER, STEAMSHIP", "MÉCANICIEN EN SECOND, NAVIRE À VAPEUR" }, { "65", "SECOND-CLASS ENGINEER, MOTOR SHIP", "OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À MOTEUR" }, { "66", "SECOND-CLASS ENGINEER, MOTOR SHIP AND STEAMSHIP", "OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À MOTEUR ET NAVIRE À VAPEUR" }, { "67", "SECOND-CLASS ENGINEER, MOTOR SHIP FOURTH-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À VAPEUR" }, { "68", "SECOND-CLASS ENGINEER, MOTOR SHIP THIRD-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE TROISIÉME CLASSE, NAVIRE À VAPEUR" }, { "69", "SECOND-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE DEUXIÈME CLASSE, NAVIRE À VAPEUR" }, { "70", "SHIP PERSONNEL WITH DESIGNATED SECURITY DUTIES", "PERSONNEL DU NAVIRE AYANT DES RESPONSABILITÉS EN MATIÈRE DE SÛRETÉ" }, { "71", "SHIP PERSONNEL WITHOUT DESIGNATED SECURITY DUTIES", "PERSONNEL DU NAVIRE N'AYANT PAS DE RESPONSABILITÉS EN MATIÈRE DE SÛRETÉ" }, { "72", "SHIP SECURITY OFFICER", "AGENT DE SÛRETÉ DU NAVIRE" }, { "73", "SPECIALIZED PASSENGER SAFETY MANAGEMENT (RO-RO VESSELS)", "GESTION SPÉCIALISÉE DE LA SÉCURITÉ DES PASSAGERS (BÂTIMENTS ROULIERS)" }, { "74", "STCW BASIC SAFETY", "SÉCURITÉ DE BASE STCW" }, { "75", "SURVIVAL CRAFT AND RESCUE BOATS OTHER THAN FAST RESCUE BOATS", "EXPLOITATION DES BATEAUX DE SAUVETAGE ET CANOTS DE SECOURS, AUTRES QUE DES CANOTS DE SECOURS RAPIDES" }, { "78", "THIRD-CLASS ENGINEER, MOTOR SHIP (3M)", "OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À MOTEUR (3M)" }, { "79", "THIRD-CLASS ENGINEER, MOTOR SHIP (3MN)", "OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À MOTEUR (3MN)" }, { "80", "THIRD-CLASS ENGINEER, MOTOR SHIP FOURTH-CLASS ENGINEER, STEAMSHIP", "OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À MOTEUR OFFICIER MÉCANICIEN DE QUATRIÈME CLASSE, NAVIRE À VAPEUR" }, { "81", "THIRD-CLASS ENGINEER, STEAMSHIP (3S)", "OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À VAPEUR (3S)" }, { "82", "THIRD-CLASS ENGINEER, STEAMSHIP (3SN)", "OFFICIER MÉCANICIEN DE TROISIÈME CLASSE, NAVIRE À VAPEUR (3SN)" }, { "83", "WATCHKEEPING MATE", "OFFICIER DE PONT DE QUART" }, { "84", "WATCHKEEPING MATE, NEAR COASTAL", "OFFICIER DE PONT DE QUART, À PROXIMITÉ DU LITTORAL" }, }; Random random = new Random(); for (int n = 0; n < 100; n++) { RequestRow request = new RequestRow(); request.RequestId = 1000 + n; request.FullName = randomNames[n]; int random_6_diget_number = random.Next(100001, 999999); request.CDN = random_6_diget_number + "K"; int certificateIndex = random.Next(1, 66); string certificateType = certificates[certificateIndex, 1]; // 1 is for getting English value request.RequestCertificateType = certificateType; int staffIndex = random.Next(1, 6); request.AssignedTo = randomStaffs[staffIndex]; int randomDays = random.Next(1, 60); request.ServiceStandard = randomDays + " days remaining"; int processingPhaseIndex = random.Next(0, 4); request.ProcessingPhase = processingPhases[processingPhaseIndex]; requestList.Add(request); } return(requestList); }
private static bool IsInside(int firstRow, int firstCol, string[,] matrix) { return(firstRow >= 0 && firstRow < matrix.GetLength(0) && firstCol >= 0 && firstCol < matrix.GetLength(1)); }
public static void AddCodeToLink(int i, LinkCollection iLinks, long linkIndex, string[,] strArrCode) { if (iLinks == null) { throw new ArgumentNullException("iLinks"); } if ((i < 0) | (i > Information.UBound(strArrCode))) { throw new ArgumentOutOfRangeException("i"); } checked { for (int j = 0; j <= Information.UBound(strArrCode, 2) && Operators.CompareString(strArrCode[i, j], "", TextCompare: false) != 0; j++) { iLinks.get_Item((int)linkIndex).Codes.TryAdd(strArrCode[i, j]); } } }
/// <summary> /// 插入实卡记录 /// </summary> /// <param name="livcardAssociator"></param> /// <returns></returns> public void InsertLivcardAssociator(LivcardAssociator livcardAssociator, string[,] list) { aideTreasureData.InsertLivcardAssociator(livcardAssociator, list); }
public ArrayStylingSpreadsheetWriter(string[,] spreadsheet) : base(DefaultXPosition, DefaultYPosition) { Spreadsheet = spreadsheet; CurrentPosition = new Point(DefaultXPosition, DefaultYPosition); }
/// <summary> /// Generate new password. /// </summary> protected void Button2_Click(object sender, System.EventArgs e) { string _uname = Convert.ToString(HttpContext.Current.Request["username"]); string _passwd = class_login.CreateRandomPassword(10); int _salt = class_login.CreateRandomSalt(); string hash = IN.ComputeSaltedHash(_passwd, _salt); string _email = string.Empty; string UserQuery = "SELECT * FROM users WHERE UserName = "******"UserEmail"]); r.Close(); } catch { string LabelColor = "red"; string PageTitle = "No user in database"; LabelTextFunc(LabelColor, PageTitle); } finally { con.Close(); } ///----------------------------------------- /// Set up array ///----------------------------------------- string[,] user_data = { { "UserPassWD", _passwd }, { "UserPassSalt", Convert.ToString(_salt) } }; string dbup = DB.do_update("users", user_data, "UserName="******"") { string LabelColor = "red"; string PageTitle = dbup; LabelTextFunc(LabelColor, PageTitle); } else { ///----------------------------------------- /// Send email and redirect ///----------------------------------------- string msgTo = _email; string msgFrom = "*****@*****.**"; string msgSubject = "Password recovery GreenPanda"; string msgBody = @"Your new password for GreenPanda System is:" + _passwd + @"\n\n------------------------\nThe GreenPanda Administrator"; string MySmtpMailServerName = "localhost"; int MySmtpMailServerPort = 25; //25 is the default for SMTP SmtpClient MySmtpClient = new SmtpClient(MySmtpMailServerName, MySmtpMailServerPort); MySmtpClient.Send(msgFrom, msgTo, msgSubject, msgBody); Response.Redirect("login.aspx"); } }
/// <summary> /// Register new account. /// </summary> private void Register() { ///----------------------------------------- /// Set up variables ///----------------------------------------- string _reg_gid = "2"; string _reg_uname = Convert.ToString(HttpContext.Current.Request["usernamesignup"]); int _reg_psalt = class_login.CreateRandomSalt(); string _reg_fname = Convert.ToString(HttpContext.Current.Request["fnamesignup"]); string _reg_lname = Convert.ToString(HttpContext.Current.Request["lnamesignup"]); string _reg_email = Convert.ToString(HttpContext.Current.Request["emailsignup"]); string _reg_passwd = Convert.ToString(HttpContext.Current.Request["passwordsignup"]); string _reg_passwd_confirm = Convert.ToString(HttpContext.Current.Request["passwordsignup_confirm"]); /*string _reg_utitle = string.Empty; * string _reg_workarea = string.Empty; * string _reg_org = string.Empty; * string _reg_phone = string.Empty; * string _reg_cell = string.Empty;*/ string _reg_cdate = Convert.ToString(DateTime.Now); string _reg_lang = "es-HN"; string _reg_skin = "skyblue"; ///----------------------------------------- /// Check if username already exists ///----------------------------------------- int _user_checked = 0; string valUserName = string.Empty; string wsQuery = "SELECT * FROM users WHERE UserName='******'"; SqlCommand cmdws = new SqlCommand(wsQuery, con); SqlDataReader wsr; try { con.Open(); wsr = cmdws.ExecuteReader(); wsr.Read(); valUserName = Convert.ToString(wsr["UserName"]); wsr.Close(); } catch { } finally { con.Close(); } if (String.IsNullOrEmpty(valUserName)) { _user_checked = 1; } else { _user_checked = 0; } ///----------------------------------------- /// Check if email already exists ///----------------------------------------- int _email_checked = 0; string valUserEmail = string.Empty; string ueQuery = "SELECT * FROM users WHERE UserEmail='" + _reg_email + "'"; SqlCommand cmdue = new SqlCommand(ueQuery, con); SqlDataReader uer; try { con.Open(); uer = cmdue.ExecuteReader(); uer.Read(); valUserEmail = Convert.ToString(uer["UserEmail"]); uer.Close(); } catch { } finally { con.Close(); } if (String.IsNullOrEmpty(valUserEmail)) { _email_checked = 1; } else { _email_checked = 0; } ///----------------------------------------- /// Check confirmation of both passwords ///----------------------------------------- int _passwd_checked = 0; if (_reg_passwd == _reg_passwd_confirm) { _passwd_checked = 1; } if (_passwd_checked == 1 && _user_checked == 1 && _email_checked == 1) { ///----------------------------------------- /// Insert data into DB ///----------------------------------------- string hash = IN.ComputeSaltedHash(_reg_passwd, _reg_psalt); string salt = Convert.ToString(_reg_psalt); string[,] user_data = { { "GroupID", _reg_gid }, { "UserName", _reg_uname }, { "UserPassWD", hash }, { "UserPassSalt", salt }, { "UserFirstName", _reg_fname }, { "UserLastName", _reg_lname }, { "UserEmail", _reg_email }, /*{ "UserTitle", _reg_utitle }, * { "UserWorkArea", _reg_workarea }, * { "UserOrganization", _reg_org }, * { "UserWorkPhone", _reg_phone }, * { "UserCellular", _reg_cell },*/ { "UserCreationDate", _reg_cdate }, { "UserLanguage", _reg_lang }, { "UserSkin", _reg_skin } }; string ins = DB.do_insert("users", user_data); if (String.IsNullOrEmpty(ins)) { if (sendAdminEmails == true) { ///----------------------------------------- /// SEND EMAILS TO ADMIN USERS ///----------------------------------------- /// Get emails of admin users from DB /// ---------------------------------------- string _admin_emails = std.get_admin_emails(); ///----------------------------------------- /// Send email to Admin /// ---------------------------------------- string[] emails_array = _admin_emails.Split(';'); string admsubj = "Nuevo Usuario se ha Registrado"; string admbodymsg = "Un nuevo usuario se ha registrado en la " + PageTitle + ", está pendiente de aprobación, ingresa al sistema para aprobar o denegar su solicitud."; for (var i = 0; i < emails_array.Length; i++) { string[] email_vars = emails_array[i].Split(','); std.global_send_email(email_vars[0], email_vars[1], admsubj, admbodymsg); } ///----------------------------------------- /// Send email to new user /// ---------------------------------------- string ufullname = _reg_fname + " " + _reg_lname; string usbj = "Bienvenido a la " + PageTitle; string ubmsg = @" " + ufullname + @", muchas gracias por suscribirte a la " + PageTitle + @". Tu registro está pendiente de aprobación, tu usuario será habilitado a mas tardar 24 horas. Saludos. "; std.global_send_email(_reg_email, ufullname, usbj, ubmsg); } ///----------------------------------------- /// Redirect /// ---------------------------------------- HttpContext.Current.Response.Redirect("login.aspx?dologin=1&username="******"&password="******"red"); } } else if (_user_checked == 0) { Labeltext.Text = skin.error_page("El usuario seleccionado ya existe! Escribe uno nuevo.", "red"); unamesignup.Text = _reg_uname; fnamesignup.Text = _reg_fname; lnamesignup.Text = _reg_lname; email.Text = _reg_email; } else if (_email_checked == 0) { Labeltext.Text = skin.error_page("El email escrito ya es usado por otra cuenta! Escribe uno nuevo.", "red"); unamesignup.Text = _reg_uname; fnamesignup.Text = _reg_fname; lnamesignup.Text = _reg_lname; email.Text = _reg_email; } else if (_passwd_checked == 0) { Labeltext.Text = skin.error_page("Las claves introducidas no concuerdan una con la otra!", "red"); unamesignup.Text = _reg_uname; fnamesignup.Text = _reg_fname; lnamesignup.Text = _reg_lname; email.Text = _reg_email; } }
public JsonResult SelectUsers(string key, string value, string orgIDs, string roleIDs) { SQLHelper sqlHelper = SQLHelper.CreateSqlHelper("Base"); string whereStr = string.Empty; if (!string.IsNullOrEmpty(key)) { int firstCode = (int)key[0]; if (48 <= firstCode && firstCode <= 57) //number { whereStr = " WorkNo like '" + key + "%'"; } else if ((65 <= firstCode && firstCode <= 90) || (97 <= firstCode && firstCode <= 122)) //letter { string[,] hz = GetHanziScope(key); for (int i = 0; i < hz.GetLength(0); i++) { if (!string.IsNullOrEmpty(whereStr)) { whereStr += " and "; } if (Config.Constant.IsOracleDb) { whereStr += "nlssort(SUBSTR(\"Name\", " + (i + 1) + ", 1),'NLS_SORT=SCHINESE_PINYIN_M') >= nlssort('" + hz[i, 0] + "','NLS_SORT=SCHINESE_PINYIN_M') AND nlssort(SUBSTR(\"Name\", " + (i + 1) + ", 1),'NLS_SORT=SCHINESE_PINYIN_M') <= nlssort('" + hz[i, 1] + "','NLS_SORT=SCHINESE_PINYIN_M')"; } else { whereStr += "SUBSTRING(Name, " + (i + 1) + ", 1) >= '" + hz[i, 0] + "' AND SUBSTRING(Name, " + (i + 1) + ", 1) <= '" + hz[i, 1] + "'"; } } } else if (firstCode >= 255) { //chinese if (Config.Constant.IsOracleDb) { whereStr = "\"Name\" like '%" + key + "%'"; } else { whereStr = "Name like '%" + key + "%'"; } } } if (!string.IsNullOrEmpty(value)) { if (!string.IsNullOrEmpty(whereStr)) { whereStr += " and "; } whereStr += "ID not in ('" + value.Replace(",", "','") + "')"; } string sql = ""; if (Config.Constant.IsOracleDb) { sql = "select * from (select ID, WORKNO as \"WorkNo\", NAME as \"Name\",DEPTNAME as \"DeptName\" from S_A_User where nvl(IsDeleted,0) = 0) Users "; } else { sql = "select * from (select * from S_A_User where isnull(IsDeleted,0) = 0) Users "; } if (!string.IsNullOrEmpty(orgIDs) || !string.IsNullOrEmpty(roleIDs)) { sql = "select * from (" + GetScopeSql(orgIDs, roleIDs) + ") Users "; } if (!string.IsNullOrEmpty(whereStr)) { sql += " where " + whereStr; } if (Config.Constant.IsOracleDb) { sql = "select * from (" + sql + ") FilterUsers Where rownum <= 10"; } else { sql = "select top 10 * from (" + sql + ") FilterUsers"; } return(Json(sqlHelper.ExecuteDataTable(sql), JsonRequestBehavior.AllowGet)); }
// print tiles on console for development purposes.. private void debugTiles() { /*Debug section to test tiles values*/ string msg = "\t\t\t\t"; string [,] orange = cube2d.GetOrangeFaceTiles(); string [,] green = cube2d.GetGreenFaceTiles(); string [,] white = cube2d.GetWhiteFaceTiles(); string [,] blue = cube2d.GetBlueFaceTiles(); string [,] red = cube2d.GetRedFaceTiles(); string [,] yellow = cube2d.GetYellowFaceTiles(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { msg += orange[i, j] + " "; } msg += "\n\t\t\t\t"; } msg += "\n"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { if (j < 3) { msg += green[i, j] + " "; } else if (j > 2 && j < 6) { msg += white[i, j - 3] + " "; } else { msg += blue[i, j - 6] + " "; } if (j == 2 || j == 5) { msg += "\t\t"; } } msg += "\n"; } msg += "\n\t\t\t\t"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { msg += red[i, j] + " "; } msg += "\n\t\t\t\t"; } msg += "\n\t\t\t\t"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { msg += yellow[i, j] + " "; } msg += "\n\t\t\t\t"; } print(msg); }
private void rotation() { // Mouse Drag Cube Rotation if (Input.GetMouseButton(1)) // mouse right click hold { float rotationX = Input.GetAxis("Mouse X") * sensitivityX; float rotationY = Input.GetAxis("Mouse Y") * sensitivityY; transform.Rotate(cameraTm.up, -Mathf.Deg2Rad * rotationX * Time.deltaTime * 5000, Space.World); transform.Rotate(cameraTm.right, Mathf.Deg2Rad * rotationY * Time.deltaTime * 5000, Space.World); } // rotate cube face if (rotate) { if (!rotateInit) { if (piston != null) { GameObject.Find("Piston").GetComponent <Toggle>().interactable = false; } // get selected face face = cube2d.getFace(selection); //int res = 0; pistonEdges.Clear(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // preparing edges for piston movement logic (for future development) /*if(GameObject.FindWithTag(face[i,j]).name.StartsWith("Edge")){ * //print(GameObject.FindWithTag(face[i,j]).name + " " + GameObject.FindWithTag(face[i,j]).transform.localPosition); * * float x = GameObject.FindWithTag(face[i,j]).transform.localPosition.x; * float y = GameObject.FindWithTag(face[i,j]).transform.localPosition.y; * float z = GameObject.FindWithTag(face[i,j]).transform.localPosition.z; * * // Top Face Check * if( (int) y == 1 && (int)z == -1){ //move -z axis * pistonEdges.Add(GameObject.FindWithTag(face[i,j]).transform); * pistonEdgesAxis[res] = "-y"; * res++; * }else if((int)x == -1 && (int)y == 1){ //move -x axis * pistonEdges.Add(GameObject.FindWithTag(face[i,j]).transform); * pistonEdgesAxis[res] = "-z"; * res++; * }else if((int)y == 1 && (int)z == 1){ //move z axis * pistonEdges.Add(GameObject.FindWithTag(face[i,j]).transform); * pistonEdgesAxis[res] = "y"; * res++; * }else if((int)x == 1 && (int)y == 1){ //move x axis * pistonEdges.Add(GameObject.FindWithTag(face[i,j]).transform); * pistonEdgesAxis[res] = "z"; * res++; * } * * }*/ // Assign lightning effect end points if (GameObject.FindWithTag(face[i, j]).name.StartsWith("Corner")) { GameObject.FindWithTag(face[i, j]).GetComponent <LightningGenerator>().EndPoint = centerP[selection].gameObject; } else if (GameObject.FindWithTag(face[i, j]).name.StartsWith("Edge")) { GameObject.FindWithTag(face[i, j]).GetComponent <LightningGenerator>().EndPoint = centerP[selection].gameObject; } else if (GameObject.FindWithTag(face[i, j]).name.StartsWith("Center")) { GameObject.FindWithTag(face[i, j]).GetComponent <LightningGenerator>().EndPoint = GameObject.FindWithTag("Core").gameObject; } // assign face cubies to parent GameObject.FindWithTag(face[i, j]).transform.parent = centerP[selection]; } } // rotate 2d cube cube2d.Rotate(selection); if (reverse) // a little cheat so I don't have to code too much = slight performance impact :] { cube2d.Rotate(selection); cube2d.Rotate(selection); } count = speed = rotationSpeeds [selectedItemIndex]; // set rotation speed rotateInit = true; // play cube turning sound if sfx is enabled if (audioCon != null && audioCon.enableSFX) { audioCon.sfxsource.PlayOneShot(audioCon.rubikturnsfx); } // calculate if increments total results in odd or even number state = 90 / speed; stateOddOrEven = state % 2 == 0 ? false : true; } // rotate face centerP [selection].Rotate(new Vector3(reverse ? -speed : speed, 0, 0)); countState++; // piston effect if (pistonEnabled) { if (stateOddOrEven) // if odd { if (countState > ((state / 2) + 1)) { centerPSpacing(centerP[selection], (-1f / state) * pistonLength); foreach (Transform child in centerP[selection]) { if (child.name.StartsWith("Corner")) { cornerPSpacing(child, (-1f / state) * pistonLength); } else if (child.name.StartsWith("Edge")) { edgePSpacing(child, (-1f / state) * pistonLength); } } } else if (countState < ((state / 2) + 1)) { centerPSpacing(centerP[selection], (1f / state) * pistonLength); foreach (Transform child in centerP[selection]) { if (child.name.StartsWith("Corner")) { cornerPSpacing(child, (1f / state) * pistonLength); } else if (child.name.StartsWith("Edge")) { edgePSpacing(child, (1f / state) * pistonLength); } } } } else if (!stateOddOrEven) // if even { if (countState > (state / 2)) { centerPSpacing(centerP[selection], (-1f / state) * pistonLength); foreach (Transform child in centerP[selection]) { if (child.name.StartsWith("Corner")) { cornerPSpacing(child, (-1f / state) * pistonLength); } else if (child.name.StartsWith("Edge")) { edgePSpacing(child, (-1f / state) * pistonLength); } } } else if (countState <= (state / 2)) { centerPSpacing(centerP[selection], (1f / state) * pistonLength); foreach (Transform child in centerP[selection]) { if (child.name.StartsWith("Corner")) { cornerPSpacing(child, (1f / state) * pistonLength); } else if (child.name.StartsWith("Edge")) { edgePSpacing(child, (1f / state) * pistonLength); } } } } } // check if rotation should finish to reset state if (count >= 90) { resetParents(); rotateInit = false; rotate = false; count = 0; countState = 0; if (piston != null) { piston.interactable = true; } if (cube2d.isSolved()) { if (solved != null) { solved.enabled = true; } timerStarted = false; } else { if (solved != null) { solved.enabled = false; } } //debugTiles(); } // update count flag to keep up with rotation bounds count += speed; } // update time on screen if (timerStarted) { time += Time.deltaTime; timeText.text = "Timer : " + time.ToString("F2") + "s"; } }
/// <summary> /// /// See base class /// /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoice"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// /// If <paramref name="choices"/> is null. /// /// </exception> /// <exception cref="ArgumentException"> /// /// If <paramref name="choices"/>.Count is 0. /// /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// /// If <paramref name="defaultChoice"/> is greater than /// the length of <paramref name="choices"/>. /// /// </exception> /// <exception cref="PromptingException"> /// /// when prompt is canceled by, for example, Ctrl-c. /// /// </exception> public override int PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, int defaultChoice) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } if ((defaultChoice < -1) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceErrorTemplate, "defaultChoice", "choice"); } // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); WriteLineToConsole(); } if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } int result = defaultChoice; string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); // add the default choice key only if it is valid. -1 is used to specify // no default. if (defaultChoice >= 0) { defaultChoiceKeys.Add(defaultChoice, true); } do { WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, false); ReadLineResult rlResult; string response = ReadLine(false, "", out rlResult, true, true); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } if (response.Length == 0) { // they just hit enter. if (defaultChoice >= 0) { // if there's a default, pick that one. result = defaultChoice; break; } continue; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } result = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (result >= 0) { break; } // their input matched none of the choices, so prompt again }while (true); return(result); } }
public static void LoadNand(string NandPath, string WadDirectory) { if (Directory.Exists(NandPath + "/ticket")) { string[] tiks = Directory.GetFiles(NandPath + "/ticket/", "*.tik", SearchOption.AllDirectories); foreach (string tik in tiks) { bool exists = false; if (exists == false) { string[] Infos = new string[11]; try { string path1 = tik.Remove(tik.LastIndexOf('/')); path1 = path1.Remove(0, path1.LastIndexOf('/') + 1); string path2 = tik.Remove(0, tik.LastIndexOf('/') + 1); path2 = path2.Remove(path2.LastIndexOf('.')); byte[] tikarray = Wii.Tools.LoadFileToByteArray(tik); if (File.Exists(NandPath + "/title/" + path1 + "/" + path2 + "/content/title.tmd")) { byte[] tmd = Wii.Tools.LoadFileToByteArray(NandPath + "/title/" + path1 + "/" + path2 + "/content/title.tmd"); string[,] continfo = Wii.WadInfo.GetContentInfo(tmd); string cid = "00000000"; for (int j = 0; j < continfo.GetLength(0); j++) { if (continfo[j, 1] == "00000000") { cid = continfo[j, 0]; } } byte[] nullapp = Wii.Tools.LoadFileToByteArray(NandPath + "/title/" + path1 + "/" + path2 + "/content/" + cid + ".app"); Infos[0] = tik.Remove(0, tik.LastIndexOf('/') + 1); Infos[1] = Wii.WadInfo.GetTitleID(tikarray, 0); //Infos[2] = Wii.WadInfo.GetNandBlocks(tmd); //Infos[3] = Wii.WadInfo.GetNandSize(tmd, true); Infos[4] = Wii.WadInfo.GetIosFlag(tmd); Infos[5] = Wii.WadInfo.GetRegionFlag(tmd); //Infos[6] = Wii.WadInfo.GetContentNum(tmd).ToString(); Infos[7] = Wii.WadInfo.GetNandPath(tikarray, 0); Infos[8] = Wii.WadInfo.GetChannelType(tikarray, 0); Infos[9] = Wii.WadInfo.GetTitleVersion(tmd).ToString(); string language = "English"; switch (language) { case "Dutch": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[6]; break; case "Italian": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[5]; break; case "Spanish": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[4]; break; case "French": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[3]; break; case "German": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[2]; break; case "Japanese": Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[0]; break; default: Infos[10] = Wii.WadInfo.GetChannelTitlesFromApp(nullapp)[1]; break; } string[] titlefiles = Directory.GetFiles(NandPath + "/title/" + path1 + "/" + path2, "*", SearchOption.AllDirectories); Infos[6] = (titlefiles.Length - 1).ToString(); int nandsize = 0; foreach (string titlefile in titlefiles) { FileInfo fi = new FileInfo(titlefile); nandsize += (int)fi.Length; } FileInfo fitik = new FileInfo(tik); nandsize += (int)fitik.Length; double blocks = (double)((Convert.ToDouble(nandsize) / 1024) / 128); Infos[2] = Math.Ceiling(blocks).ToString(); string size = Convert.ToString(Math.Round(Convert.ToDouble(nandsize) * 0.0009765625 * 0.0009765625, 2)); if (size.Length > 4) { size = size.Remove(4); } Infos[3] = size.Replace(",", ".") + " MB"; //lvNand.Items.Add(new ListViewItem(Infos)); PackVCWads(NandPath, WadDirectory, Infos); } } catch { } } } } //pbProgress.Value = 100; //SaveListNand(); //lbFileCount.Text = lvNand.Items.Count.ToString(); }
/// <summary> /// Presents a dialog allowing the user to choose options from a set of options. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A message that describes what the choice is for. /// </param> /// <param name="choices"> /// An Collection of ChoiceDescription objects that describe each choice. /// </param> /// <param name="defaultChoices"> /// The index of the labels in the choices collection element to be presented to the user as /// the default choice(s). /// </param> /// <returns> /// The indices of the choice elements that corresponds to the options selected. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> public Collection <int> PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (null != defaultChoices) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } if (!defaultChoiceKeys.ContainsKey(defaultChoice)) { defaultChoiceKeys.Add(defaultChoice, true); } } } Collection <int> result = new Collection <int>(); // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { // write caption on the console, if present. if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); WriteLineToConsole(); } // write message if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, true); if (defaultChoiceKeys.Count > 0) { WriteLineToConsole(); } // used to display ChoiceMessage like Choice[0],Choice[1] etc int choicesSelected = 0; do { // write the current prompt string choiceMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.ChoiceMessage, choicesSelected); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(choiceMsg)); ReadLineResult rlResult; string response = ReadLine(false, "", out rlResult, true, true); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // prompt for multiple choices }while (true); return(result); } }
private Sound sound;//サウンドオブジェクト /// <summary> /// コンストラクタ /// </summary> /// <param name="resources"></param> public BGMLoader(string[,] resources) : base(resources) { sound = GameDevice.Instance().GetSound(); //GameDeviceからサウンドオブジェクトを取得 base.Initialize(); }
public Astronave(string shape, int x, int y, string[,] matriceSfondo, int velocita) : base(shape, x, y, matriceSfondo) { _velocita = velocita; i = Y; _matBackground = matriceSfondo; }
public Graphic(string[,] design) { graphic = design; }
//! @brief Loads the tpose from a byte array. //! @returns True if load was successful, false otherwise. public bool loadFromBytes(byte [] data) { if (data == null) { return(false); } // create 2D grid of the file string text = System.Text.Encoding.UTF8.GetString(data); string[,] grid = split_t_pose_file(text); //Debug.Log("size = " + grid.GetLength(0) + " , " + grid.GetLength (1)); // first row contains version, number of joints int row = 0; int col = 0; Int32 version = 0; try { Convert.ToInt32(grid[row, col + 0]); } catch (Exception) { return(false); } if (version != TPOSE_FILE_VERSION) { return(false); } Int32 number_of_joints = Convert.ToInt32(grid[row, col + 1]); ArrayList new_joints = new ArrayList(); for (int i = 0; i < number_of_joints; i++) { TransformationInformation joint = new TransformationInformation(); int start_row = 1 + 2 * i; joint.rotation.x = (float)Convert.ToDouble(grid[start_row, 0]); joint.rotation.y = (float)Convert.ToDouble(grid[start_row, 1]); joint.rotation.z = (float)Convert.ToDouble(grid[start_row, 2]); joint.rotation.w = (float)Convert.ToDouble(grid[start_row, 3]); joint.localRotation.x = (float)Convert.ToDouble(grid[start_row, 4]); joint.localRotation.y = (float)Convert.ToDouble(grid[start_row, 5]); joint.localRotation.z = (float)Convert.ToDouble(grid[start_row, 6]); joint.localRotation.w = (float)Convert.ToDouble(grid[start_row, 7]); joint.position.x = (float)Convert.ToDouble(grid[start_row, 8]); joint.position.y = (float)Convert.ToDouble(grid[start_row, 9]); joint.position.z = (float)Convert.ToDouble(grid[start_row, 10]); joint.localPosition.x = (float)Convert.ToDouble(grid[start_row, 11]); joint.localPosition.y = (float)Convert.ToDouble(grid[start_row, 12]); joint.localPosition.z = (float)Convert.ToDouble(grid[start_row, 13]); joint.parentRotation.x = (float)Convert.ToDouble(grid[start_row, 14]); joint.parentRotation.y = (float)Convert.ToDouble(grid[start_row, 15]); joint.parentRotation.z = (float)Convert.ToDouble(grid[start_row, 16]); joint.parentRotation.w = (float)Convert.ToDouble(grid[start_row, 17]); joint.transformPath = grid[start_row + 1, 0]; if (grid[start_row + 1, 1] != null) { joint.transformName = grid[start_row + row + 1, 1]; } new_joints.Add(joint); } // Apply m_joints = new_joints; return(true); }
private void btn_show_world_vac_data_Click(object sender, EventArgs e) { int num_rows = 0; //int num_cols = 0; //string short_date = ""; if (cmbobx_world_vac.SelectedItem.ToString() != "World") { //////////////////////////////////////////////////////////////// // Load for countries /////////////////////////////////////////////////////////////// // we need these int in case no 1st vacs have taken place int big = 0; int small = 0; // Get the data. string[,] values = Load_vac_Csv("Country_Files\\" + cmbobx_world_vac.SelectedItem + ".csv"); num_rows = values.GetUpperBound(0) + 1; dgv_vac_world_unverified.Columns.Clear(); dgv_vac_world_unverified.Columns.Add("Date", "Date"); dgv_vac_world_unverified.Columns["Date"].DefaultCellStyle.Format = "dd/MM/yyyy"; dgv_vac_world_unverified.Columns["Date"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Vaccine", "Vaccine"); dgv_vac_world_unverified.Columns["Vaccine"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Last Period", "New 1st Vac"); dgv_vac_world_unverified.Columns["Last Period"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Last Period"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Last Period"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Total", "1st Vac Total"); dgv_vac_world_unverified.Columns["Total"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Total"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Last Period 2", "New 2nd Vac"); dgv_vac_world_unverified.Columns["Last Period 2"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Last Period 2"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Last Period 2"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Total 2", "Fully Vac Total"); dgv_vac_world_unverified.Columns["Total 2"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Total 2"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Total 2"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("last_boost1", "New 1st Boost"); dgv_vac_world_unverified.Columns["last_boost1"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["last_boost1"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["last_boost1"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("boost1", "Tot 1st Boost"); dgv_vac_world_unverified.Columns["boost1"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["boost1"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["boost1"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; DataGridViewLinkColumn url_col = new DataGridViewLinkColumn(); //make URL clickable url_col.DataPropertyName = "Source"; url_col.Name = "Data Source"; dgv_vac_world_unverified.Columns.Add(url_col); dgv_vac_world_unverified.CellContentClick += new DataGridViewCellEventHandler(dgv_vac_world_unverified_CellContentClick); dgv_vac_world_unverified.Columns["Data Source"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; string[] country_data = File.ReadAllLines("Country_Files\\" + cmbobx_world_vac.SelectedItem + ".csv"); //get the item number in the array. string[] headings = Regex.Split(country_data[0], ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // location,ISO Code,date,vaccine,total_vaccinations,source_url int vac = Array.IndexOf(headings, "vaccine"); int dat = Array.IndexOf(headings, "date"); int tot = Array.IndexOf(headings, "people_vaccinated"); int tot2 = Array.IndexOf(headings, "people_fully_vaccinated"); int boost = Array.IndexOf(headings, "total_boosters"); int url = Array.IndexOf(headings, "source_url"); // Add the data. for (int r = 1; r < num_rows; r++) { string[] fields = Regex.Split(country_data[r], ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); dgv_vac_world_unverified.Rows.Add(); dgv_vac_world_unverified.Rows[r - 1].Cells[0].Value = Convert.ToDateTime(values[r, dat]); //Date dgv_vac_world_unverified.Rows[r - 1].Cells[1].Value = values[r, vac]; //Vaccine if (fields[tot] == "") //1st { dgv_vac_world_unverified.Rows[r - 1].Cells[3].Value = 0; } else { dgv_vac_world_unverified.Rows[r - 1].Cells[3].Value = Convert.ToInt32(values[r, tot]);//Total } if (fields[tot2] == "") //2nd { dgv_vac_world_unverified.Rows[r - 1].Cells[5].Value = 0; } else { dgv_vac_world_unverified.Rows[r - 1].Cells[5].Value = Convert.ToInt32(values[r, tot2]); } if (fields[boost] == "") //1st booster { dgv_vac_world_unverified.Rows[r - 1].Cells[7].Value = 0; } else { dgv_vac_world_unverified.Rows[r - 1].Cells[7].Value = Convert.ToInt32(values[r, boost]); } dgv_vac_world_unverified.Rows[r - 1].Cells[8].Value = values[r, url]; //Data Source if (r > 1) //work out daily 1st vac totals { if (values[r, tot] != "") { big = Convert.ToInt32(values[r, tot]); } if (values[r - 1, tot] != "") { small = Convert.ToInt32(values[r - 1, tot]); } dgv_vac_world_unverified.Rows[r - 1].Cells[2].Value = big - small; } else if (r == 1) { dgv_vac_world_unverified.Rows[r - 1].Cells[2].Value = Convert.ToInt32(dgv_vac_world_unverified.Rows[r - 1].Cells[3].Value).ToString(); } big = small = 0; //reset if (values[r, tot2] == values[r, tot]) { dgv_vac_world_unverified.Rows[r - 1].Cells[4].Value = 0; } else { if (r > 1) //work out 2nd vac daily totals { if (values[r, tot2] != "") { big = Convert.ToInt32(values[r, tot2]); } if (values[r - 1, tot2] != "") { small = Convert.ToInt32(values[r - 1, tot2]); } dgv_vac_world_unverified.Rows[r - 1].Cells[4].Value = big - small; } else if (r == 1) { dgv_vac_world_unverified.Rows[r - 1].Cells[4].Value = Convert.ToInt32(dgv_vac_world_unverified.Rows[r - 1].Cells[5].Value).ToString(); } // big = small = 0; //reset } big = small = 0; //reset if (r > 1) //work out daily 1st boost totals { if (values[r, boost] != "") { big = Convert.ToInt32(values[r, boost]); } if (values[r - 1, boost] != "") { small = Convert.ToInt32(values[r - 1, boost]); } dgv_vac_world_unverified.Rows[r - 1].Cells[6].Value = big - small; } else if (r == 1) { dgv_vac_world_unverified.Rows[r - 1].Cells[6].Value = Convert.ToInt32(dgv_vac_world_unverified.Rows[r - 1].Cells[7].Value).ToString(); } big = small = 0; //reset } dgv_vac_world_unverified.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[7].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[8].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.FirstDisplayedScrollingRowIndex = dgv_vac_world_unverified.RowCount - 1; dgv_vac_world_unverified.RowHeadersVisible = false; } else { //////////////////////////////////////////////////////////////// // Load for world /////////////////////////////////////////////////////////////// // Get the data. string[,] values = Load_vac_Csv("world_vac.csv"); string SelectedCountry = ""; int count = 0; num_rows = values.GetUpperBound(0) + 1; dgv_vac_world_unverified.Columns.Clear(); //location,date,total_vaccinations,daily_vaccinations,total_vaccinations_per_hundred,daily_vaccinations_per_million dgv_vac_world_unverified.Columns.Add("Country", "Country"); dgv_vac_world_unverified.Columns["Country"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Date", "Date"); dgv_vac_world_unverified.Columns["Date"].DefaultCellStyle.Format = "dd/MM/yyyy"; dgv_vac_world_unverified.Columns["Date"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Total", "Had min 1 Vac"); dgv_vac_world_unverified.Columns["Total"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Total"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Total"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Coverage", "% Min 1 Vac Coverage"); dgv_vac_world_unverified.Columns["Coverage"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns["Coverage"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns.Add("Total2", "Fully Vac Total"); dgv_vac_world_unverified.Columns["Total2"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["Total2"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["Total2"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("Coverage2", "% Fully Vac Coverage"); dgv_vac_world_unverified.Columns["Coverage2"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns["Coverage2"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns.Add("last_boost1", "New 1st Boost"); dgv_vac_world_unverified.Columns["last_boost1"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["last_boost1"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["last_boost1"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("boost1", "% 1st Boost"); dgv_vac_world_unverified.Columns["boost1"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["boost1"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; dgv_vac_world_unverified.Columns.Add("GTotal", "Tot Doses Given"); dgv_vac_world_unverified.Columns["GTotal"].DefaultCellStyle.Format = "### ### ### ##0"; dgv_vac_world_unverified.Columns["GTotal"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; dgv_vac_world_unverified.Columns["GTotal"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; world_data = File.ReadAllLines("world_vac.csv"); //get the item number in the array. string[] headings = Regex.Split(world_data[0], ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); //location,iso_code,date,total_vaccinations,people_vaccinated,people_fully_vaccinated,total_boosters,daily_vaccinations_raw, //daily_vaccinations,total_vaccinations_per_hundred,people_vaccinated_per_hundred,people_fully_vaccinated_per_hundred, //total_boosters_per_hundred,daily_vaccinations_per_million int loc = Array.IndexOf(headings, "location"); int dat = Array.IndexOf(headings, "date"); long gtot = Array.IndexOf(headings, "total_vaccinations"); //Number doses administered long tot = Array.IndexOf(headings, "people_vaccinated"); //At least one long pop = Array.IndexOf(headings, "people_vaccinated_per_hundred"); long tot2 = Array.IndexOf(headings, "people_fully_vaccinated"); //Fully long pop2 = Array.IndexOf(headings, "people_fully_vaccinated_per_hundred"); long boost = Array.IndexOf(headings, "total_boosters"); long boost2 = Array.IndexOf(headings, "total_boosters_per_hundred"); // Add the data. for (int r = 1; r < num_rows; r++) { if (SelectedCountry != values[r, loc]) { dgv_vac_world_unverified.Rows.Add(); SelectedCountry = values[r, 0]; dgv_vac_world_unverified.Rows[count].Cells[0].Value = SelectedCountry; //Country dgv_vac_world_unverified.Rows[count].Cells[1].Value = Convert.ToDateTime(values[r, dat]); //Date if (values[r, tot] != "") //Total { dgv_vac_world_unverified.Rows[count].Cells[2].Value = Convert.ToInt64(values[r, tot]); //Total } else { dgv_vac_world_unverified.Rows[count].Cells[2].Value = Convert.ToInt64(0); } if (values[r, tot2] != "") //Fully { dgv_vac_world_unverified.Rows[count].Cells[4].Value = Convert.ToInt64(values[r, tot2]); } else { dgv_vac_world_unverified.Rows[count].Cells[4].Value = Convert.ToInt64(0); } if (values[r, boost] != "") //boost { dgv_vac_world_unverified.Rows[count].Cells[6].Value = Convert.ToInt64(values[r, boost]); } else { dgv_vac_world_unverified.Rows[count].Cells[6].Value = Convert.ToInt64(0); } if (values[r, pop] != "") //Total { dgv_vac_world_unverified.Rows[count].Cells[3].Value = float.Parse(values[r, pop]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count].Cells[3].Value = (float)0; } if (values[r, pop2] != "") //Fully { dgv_vac_world_unverified.Rows[count].Cells[5].Value = float.Parse(values[r, pop2]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count].Cells[5].Value = (float)0; } if (values[r, boost2] != "") //Fully { dgv_vac_world_unverified.Rows[count].Cells[7].Value = float.Parse(values[r, boost2]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count].Cells[7].Value = (float)0; } if (values[r, gtot] != "") //Total vac administered { dgv_vac_world_unverified.Rows[count].Cells[8].Value = Convert.ToInt32(values[r, gtot]); } else { dgv_vac_world_unverified.Rows[count].Cells[8].Value = Convert.ToInt32(0); } count++; } else { dgv_vac_world_unverified.Rows[count - 1].Cells[0].Value = SelectedCountry; //Country dgv_vac_world_unverified.Rows[count - 1].Cells[1].Value = Convert.ToDateTime(values[r, dat]); //Date if (values[r, tot] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[2].Value = Convert.ToInt64(values[r, tot]); //Total } if (values[r, tot2] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[4].Value = Convert.ToInt64(values[r, tot2]); //Total } else { dgv_vac_world_unverified.Rows[count - 1].Cells[4].Value = Convert.ToInt32(0); } if (values[r, pop] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[3].Value = float.Parse(values[r, pop]); //% Population Covered } if (values[r, pop2] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[5].Value = float.Parse(values[r, pop2]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count - 1].Cells[5].Value = (float)0; } if (values[r, boost] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[6].Value = float.Parse(values[r, boost]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count - 1].Cells[6].Value = (float)0; } if (values[r, boost2] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[7].Value = float.Parse(values[r, boost2]); //% Population Covered } else { dgv_vac_world_unverified.Rows[count - 1].Cells[7].Value = (float)0; } if (values[r, gtot] != "") { dgv_vac_world_unverified.Rows[count - 1].Cells[8].Value = Convert.ToInt64(values[r, gtot]); //Total } else { dgv_vac_world_unverified.Rows[count - 1].Cells[8].Value = Convert.ToInt64(0); } } } dgv_vac_world_unverified.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[7].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Columns[8].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgv_vac_world_unverified.Sort(dgv_vac_world_unverified.Columns["Coverage"], ListSortDirection.Descending); dgv_vac_world_unverified.FirstDisplayedScrollingRowIndex = 0; dgv_vac_world_unverified.RowHeadersVisible = false; } }
private static string Hundreds(string[,] numbers, int h, int t, int d, int numberLenght) { string hundred = numbers[0, h]; return(hundred += t == 0 && d == 0 ? "-hundred " : "-hundred and"); }
bool comprobar(string[,] gato, string posicion) { bool band = false; switch (posicion) { case "1": if (gato[2, 0] != "") { band = true; } else { band = false; } break; case "2": if (gato[2, 1] != "") { band = true; } else { band = false; } break; case "3": if (gato[2, 2] != "") { band = true; } else { band = false; } break; case "4": if (gato[1, 0] != "") { band = true; } else { band = false; } break; case "5": if (gato[1, 1] != "") { band = true; } else { band = false; } break; case "6": if (gato[1, 2] != "") { band = true; } else { band = false; } break; case "7": if (gato[0, 0] != "") { band = true; } else { band = false; } break; case "8": if (gato[0, 1] != "") { band = true; } else { band = false; } break; case "9": if (gato[0, 2] != "") { band = true; } else { band = false; } break; } return(band); }
protected void doLogin() { String UserNameIn = Convert.ToString(HttpContext.Current.Request["username"]); String PasswdIn = Convert.ToString(HttpContext.Current.Request["password"]); string userpass = string.Empty; string sessid = string.Empty; string userid = string.Empty; string UPasswd = string.Empty; if (String.IsNullOrEmpty(UserNameIn)) { string LabelColor = "red"; string PageTitle = "<b>Error:</b> Este usuario no existe!"; //string PageTitle = err.Message; LabelTextFunc(LabelColor, PageTitle); } else { string LoginQuery = "SELECT * FROM users WHERE UserName = '******'"; SqlCommand cmd = new SqlCommand(LoginQuery, con); SqlDataReader userq; // Try to open database and read information. try { con.Open(); userq = cmd.ExecuteReader(); userq.Read(); int _salt = Convert.ToInt32(userq["UserPassSalt"]); UPasswd = IN.ComputeSaltedHash(PasswdIn, _salt); userpass = Convert.ToString(userq["UserPassWD"]); userid = Convert.ToString(userq["UserID"]); userq.Close(); } catch //(Exception err) { string LabelColor = "red"; string PageTitle = "<b>Database Error:</b> Server not found!"; //string PageTitle = err.Message; LabelTextFunc(LabelColor, PageTitle); } finally { con.Close(); } if (String.IsNullOrEmpty(userid)) { string LabelColor = "red"; string PageTitle = "<b>Error:</b> Este usuario no existe!"; //string PageTitle = err.Message; LabelTextFunc(LabelColor, PageTitle); } else { if (userpass == UPasswd) { if (addupi == true) { ///--------------------------------------- /// Close/Delete any prior addUPI session ///--------------------------------------- string sid = string.Empty; string addUPIQuery = "SELECT * FROM users_addupi_sessions WHERE UserID = '" + userid + "'"; SqlCommand cmdb = new SqlCommand(addUPIQuery, con); SqlDataReader upiq; // Try to open database and read information. try { con.Open(); upiq = cmdb.ExecuteReader(); upiq.Read(); sid = upiq["SessionID"].ToString(); upiq.Close(); } catch { } finally { con.Close(); } ///--------------------------------------- std.addupi_logout(sid); DB.do_delete("users_addupi_sessions", "UserID=" + userid); ///--------------------------------------- /// Get addUPI Session ///--------------------------------------- string SessionID = std.connect_to_addupi(); ///--------------------------------------- /// Insert addUPI Session to DB ///--------------------------------------- string ntime = datenow.ToString("yyyy-MM-dd HH:mm:ss"); string[,] sessdata = { { "UserID", userid }, { "SessionID", SessionID }, { "SessionDate", ntime } }; string ins = DB.do_insert("users_addupi_sessions", sessdata); if (ins != "") { string LabelColor = "yellow"; string PageTitle = ins; LabelTextFunc(LabelColor, PageTitle); } else { FormsAuthentication.RedirectFromLoginPage(UserNameIn, false); } } else { FormsAuthentication.SetAuthCookie(UserNameIn, true); FormsAuthentication.RedirectFromLoginPage(UserNameIn, false); ///--------------------------------------- /// Insert log into db ///--------------------------------------- std.save_log(userid, "El usuario " + UserNameIn + " a ingresado al sistema.", "Login"); ///--------------------------------------- /// Update user last login in DB ///--------------------------------------- string [,] wl_data = new string[, ] { { "UserLastLogin", datenow.ToString("yyyy-MM-dd HH:mm:ss") } }; DB.do_update("users", wl_data, "UserID=" + userid); } } else { string LabelColor = "yellow"; string PageTitle = "Clave erronea, intenta de nuevo!"; LabelTextFunc(LabelColor, PageTitle); } } } }
public static void Main() { int n = int.Parse(Console.ReadLine()); string[,] labyrinth = ReadLab(n); bool[,] visited = new bool[labyrinth.GetLength(0), labyrinth.GetLength(1)]; int row = 0; int col = 0; bool isfound = false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (labyrinth[i, j] == "*") { row = i; col = j; isfound = true; break; } } if (isfound) { break; } } Queue <Cell> queue = new Queue <Cell>(); queue.Enqueue(new Cell(row, col, 0, true)); while (queue.Count != 0) { Cell currentCell = queue.Dequeue(); visited[currentCell.Row, currentCell.Col] = true; row = currentCell.Row; col = currentCell.Col; if (labyrinth[row, col] != "*") { labyrinth[row, col] = currentCell.Moves.ToString(); } //up if (row - 1 >= 0 && labyrinth[row - 1, col] != "x" && !visited[row - 1, col]) { queue.Enqueue(new Cell(row - 1, col, currentCell.Moves + 1, false)); } //right if (col + 1 < labyrinth.GetLength(1) && labyrinth[row, col + 1] != "x" && !visited[row, col + 1]) { queue.Enqueue(new Cell(row, col + 1, currentCell.Moves + 1, false)); } //down if (row + 1 < labyrinth.GetLength(0) && labyrinth[row + 1, col] != "x" && !visited[row + 1, col]) { queue.Enqueue(new Cell(row + 1, col, currentCell.Moves + 1, false)); } //left if (col - 1 >= 0 && labyrinth[row, col - 1] != "x" && !visited[row, col - 1]) { queue.Enqueue(new Cell(row, col - 1, currentCell.Moves + 1, false)); } } PrintLabyrintg(labyrinth); }