private List <Conclusion> search()
        {
            List <Conclusion> list = new List <Conclusion>();

            connection = new MySqlConnection(connString);
            try
            {
                connection.Open();
                command    = new MySqlCommand(sql, connection);
                dataReader = command.ExecuteReader();
                while (dataReader.Read())
                {
                    Conclusion cncl = new Conclusion();
                    cncl.BussinesPlanId = dataReader.GetInt32(0);
                    cncl.Text           = dataReader.GetString(1);
                    list.Add(cncl);
                }
                dataReader.Close();
                command.Dispose();
                connection.Close();
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(list);
        }
 public override bool PerformRule(Dictionary <string, object> externalData, List <Conclusion> myConclusionSet)
 {
     if ((myConclusionSet.Find(delegate(Conclusion P) { return(P.GetConclusion <Material>() != null && P.GetConclusion <Material>().GetName().CompareTo("Iron") == 0); }) == null))
     {
         Random myRandom = new Random();
         int    Rand     = myRandom.Next(0, 1);
         if (Rand == 0)
         {
             Material   Silicon  = new Material("Silicon", 14);
             Conclusion cSilicon = new Conclusion(0, Silicon);
             Material   Iron     = new Material("Iron", 26);
             Conclusion cIron    = new Conclusion(0, Iron);
             myConclusionSet.Add(cSilicon);
             myConclusionSet.Add(cIron);
         }
         else
         {
             Material   Silicon  = new Material("Silicon", 26);
             Conclusion cSilicon = new Conclusion(0, Silicon);
             Material   Iron     = new Material("Iron", 14);
             Conclusion cIron    = new Conclusion(0, Iron);
             myConclusionSet.Add(cSilicon);
             myConclusionSet.Add(cIron);
         }
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #3
0
        public MethodCherepaha()
        {
            conclMass[0]      = new Conclusion(1, 63, @"«Черепаха» (уникнення) - стратегія 
відходу під панцир, тобто відмови від 
досягнення особистої мети, та участі 
у взаємостосунках з оточуючими.");
            conclMass[1]      = new Conclusion(64, 91, @"«Акула» (конкуренція) - силова стратегія: 
мета дуже важлива, взаємовідношення немає.
Таким людям не важливо, чи люблять 
їх, вони вважають, що конфлікти розв'язуються 
виграшем однієї із сторін і поразкою другої.");
            conclMass[2]      = new Conclusion(92, 119, @"«Ведмідь» (пристосування) — стратегія
обходу гострих кутів: взаємостосунки важливі, 
мети немає. Такі люди хочуть, 
щоб їх приймали і любили, ради чого жертвують
метою.");
            conclMass[3]      = new Conclusion(120, 147, @"«Лисиця» - (стратегія компромісу: 
помірне відношення і до мети, і до 
взаємовідношень. Такі люди готові відмовитися 
від деякої мети, щоб зберегти взаємовідношення.");
            conclMass[4]      = new Conclusion(148, 175, @"«Сова» - стратегія відкритої 
і чесної конфронтації і співпраці. 
Представники цього типу цінують і мету, 
і взаємостосунки. Відкрито визначають 
позиції і шукають виходу в сумісній 
роботі по досягненню мети, прагнуть 
знайти рішення, що задовольняють всіх.");
            numberOfQuestions = 35;
        }
        private void AddConclusion(string variableName, string termName)
        {
            var variable = _variables.FirstOrDefault(x => x.Name == variableName);
            var term     = variable.Terms.FirstOrDefault(x => x.Name == termName);

            _conclusion = new Conclusion(variable, term);
        }
        public void LoadResult(Conclusion conclusion)
        {
            lblResult.Text = lblResult.Text.Replace("<<conclusionname>>", conclusion.ConclusionName)
                             .Replace("<<VALIDITITY>>", conclusion.ConclusionValidity.ToString());

            if (Preview.CorrespondingAllignedStatements != null)
            {
                switch (Preview.CorrespondingAllignedStatements.Count)
                {
                case 1:
                    lblResult.Text = lblResult.Text.Replace("<<aligned statements>>", conclusion.CorrespondingAlignedStatements[0].StatementName)
                                     .Replace("<<Result Statement>>", conclusion.ResultStatement.StatementName);
                    break;

                case 2:

                    lblResult.Text = lblResult.Text.Replace("<<aligned statements>>", "\n 1) " + conclusion.CorrespondingAlignedStatements[0].StatementName +
                                                            "\n 2) " + conclusion.CorrespondingAlignedStatements[1].StatementName)
                                     .Replace("<<Result Statement>>", conclusion.ResultStatement.StatementName);

                    break;

                case 3:
                    lblResult.Text = lblResult.Text.Replace("<<aligned statements>>", "\n 1) " + conclusion.CorrespondingAlignedStatements[0].StatementName +
                                                            "\n 2) " + conclusion.CorrespondingAlignedStatements[1].StatementName +
                                                            "\n 3) " + conclusion.CorrespondingAlignedStatements[2].StatementName);
                    break;

                default:
                    lblResult.Text = lblResult.Text.Replace("<<aligned statements>>", "some error occured")
                                     .Replace("<<Result Statement>>", "no result");
                    break;
                }
            }
        }
Example #6
0
        public static Conclusion ProcessText(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(null);
            }
            Conclusion result = new Conclusion();
            double     maxSum = double.MinValue;

            string[] lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            for (int i = 0; i < lines.Length; i++)
            {
                try
                {
                    var sum = lines[i].Split(',').Select(x => double.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture)).Sum();
                    if (sum > maxSum)
                    {
                        maxSum = sum;
                        result.lineNumberWithMaxSum = i + 1;
                    }
                }
                catch (FormatException)
                {
                    result.wrongFormatLineNumbers.Add(i + 1);
                }
            }
            return(result);
        }
Example #7
0
 private static bool CheckCorrespondingPairs(Conclusion conclusion, Statement resultConclusion)
 {
     if (conclusion.Subject.ToUpper() == resultConclusion.Subject.ToUpper() &&
         conclusion.Predicate.ToUpper() == resultConclusion.Predicate.ToUpper())
     {
         return(true);
     }
     else if (conclusion.Predicate.ToUpper() == resultConclusion.Subject.ToUpper() &&
              conclusion.Subject.ToUpper() == resultConclusion.Predicate.ToUpper())
     {
         return(true);
     }
     else if (conclusion.Subject.ToUpper() == resultConclusion.Subject.ToUpper() ||
              conclusion.Subject.ToUpper() == resultConclusion.Predicate.ToUpper())
     {
         return(true);
     }
     else if (conclusion.Predicate.ToUpper() == resultConclusion.Subject.ToUpper() ||
              conclusion.Predicate.ToUpper() == resultConclusion.Predicate.ToUpper())
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #8
0
 static void PrintConclusion(string prefix, Conclusion conclusion)
 {
     if (conclusion is MultiConclusions)
     {
         foreach (var c in ((MultiConclusions)conclusion).Conclusions)
         {
             PrintConclusion(prefix + "    ", c);
         }
     }
     else if (conclusion is SuccessConclusion)
     {
         FancyConsole.WriteLine("#g" + prefix + ((SuccessConclusion)conclusion).Message);
     }
     else if (conclusion is ExceptionConclusion)
     {
         FancyConsole.DumpException(prefix, ((ExceptionConclusion)conclusion).Exception);
     }
     else if (conclusion is SingeOutputConclusion)
     {
         FancyConsole.WriteLine(prefix + ((SingeOutputConclusion)conclusion).Output);
     }
     else if (conclusion is MultiOutputConclusion)
     {
         var result  = (MultiOutputConclusion)conclusion;
         var outputs = result.GetOutputStrings();
         if (outputs != null && outputs.Count > 0)
         {
             foreach (var s in outputs)
             {
                 FancyConsole.WriteLine(prefix + s);
             }
         }
     }
 }
Example #9
0
 public MethodOptimist2()
 {
     conclMass[0]      = new Conclusion(7, 100, @"У вас явно склалося негативне світосприйняття. Швидше за все, причина тому - ваші минулі невдачі. Звичайно, важко повірити, що завтра у вас буде все добре якщо сьогодні, так само, як і вчора, життя схоже на кошмарний сон. Тому радимо почитати біографії відомих людей. Після цього прочитання власні кошмари здаватимуться вам навіть забавними. Якщо конкретно, то в першу чергу починайте переорієнтувати свій настрій на позитивний полюс. Марно що-небудь робити для зміни ситуації, якщо наперед узята негативна установка");
     conclMass[1]      = new Conclusion(3, 7, @"Це добре, що ви прагнете мислити позитивними категоріями, але, на жаль, це не завжди виходить. Річ у тім, що у вас сформувалося похмуре світовідчування. А результат? Похмурість в оцінках породжує тільки песимізм. Втім, не все втрачено. Насамперед припиніть озиратися на минуле або «повертайтеся в нього» тільки за добрим. Коли ви перестанете у всіх своїх починах відштовхуватися від негативу, візьметеся як би почати все з чистого листа, вам здаватиметься, що все йде добрие (або непогано) і є певні шанси на успіх. Відчуття і думки можна коректувати, в усякому разі, це простіше, ніж впливати на ситуацію. Настроюйтеся на позитивну хвилю і — вперед по життю!");
     conclMass[2]      = new Conclusion(0, 3, @"Ви дивитеся на життя ясно і радісно. Люди вашого типу зазвичай мають шалений успіх у представників протилежної статі. Нічого дивного - з вами легко, весело і завжди можна зарядитись позитивною енергією. Наперекір труднощам життя ви вірите, що важливо залишатися оптимістом, навіть якщо доля буває не цілком справедливою до вас. Така позиція рятує не тільки від сьогодніщніх проблем та зневір, але є і заставою майбутнього процвітання. Постарайтеся не угра-тить цієї «легкості» в сприйнятті життя.");
     numberOfQuestions = 15;
 }
Example #10
0
        private static List <Rule> ReadRules(XElement node, List <FuzzyVariable> variables)
        {
            var result = new List <Rule>();

            foreach (var ruleNode in node.Elements(StringResources.RuleNodeName))
            {
                var inputs     = GetElement(ruleNode, StringResources.RuleNodeInputSectionName);
                var conditions = new List <Condition>();
                foreach (var inputVariableNode in inputs.Elements(StringResources.RuleVariableNodeName))
                {
                    var inputVariableNameAttribute = GetAttriute(inputVariableNode, StringResources.RuleVariableNodeNameAttribute);
                    var inputVariableName          = inputVariableNameAttribute.Value;

                    var variable = GetVariable(variables, inputVariableName);

                    var inputVariableValueAttribute = GetAttriute(inputVariableNode, StringResources.RuleVariableNodeValueAttribute);
                    var inputVariableValue          = inputVariableValueAttribute.Value;

                    var term      = GetTerm(variable, inputVariableValue);
                    var condition = new Condition(variable, term);
                    conditions.Add(condition);
                }

                var        outputs    = GetElement(ruleNode, StringResources.RuleNodeOutputSectionName);
                Conclusion conclusion = null;
                foreach (var outputVariableNode in outputs.Elements(StringResources.RuleVariableNodeName))
                {
                    var outputVariableNameAttribute = GetAttriute(outputVariableNode, StringResources.RuleVariableNodeNameAttribute);
                    var outputVariableName          = outputVariableNameAttribute.Value;

                    var variable = GetVariable(variables, outputVariableName);

                    var outputVariableValueAttribute = GetAttriute(outputVariableNode, StringResources.RuleVariableNodeValueAttribute);
                    var outputVariableValue          = outputVariableValueAttribute.Value;

                    var term = GetTerm(variable, outputVariableValue);
                    conclusion = new Conclusion(variable, term);
                }

                if (conclusion == null)
                {
                    throw new ProblemConditionsParseException("В правиле должно быть задано заключение, т.е. элемент " + StringResources.RuleVariableNodeName + " в секции " + StringResources.RuleNodeOutputSectionName);
                }

                if (conditions.Any(x => x.FuzzyVariable.Name == conclusion.FuzzyVariable.Name))
                {
                    throw new ProblemConditionsParseException("В правиле переменные условия и заключения не должны пересекаться.");
                }

                var rule = new Rule(conditions, conclusion);
                result.Add(rule);
            }

            if (result.Count == 0)
            {
                throw new ProblemConditionsParseException("Не найдено ни одного элемента " + StringResources.RuleNodeName);
            }

            return(result);
        }
Example #11
0
 public HiddenSingleInfo(
     Conclusion conclusion, ICollection <View> views, Region region,
     int digit, bool isFullHouse)
     : base(conclusion, views)
 {
     (Region, Digit, IsFullHouse) = (region, digit, isFullHouse);
 }
Example #12
0
        protected string GetConclusion()
        {
            switch (Thread.CurrentThread.CurrentUICulture.Name)
            {
            case "uk-UA":
                conclMass[0] = new Conclusion(1, 5, @"На жаль, вас не можна назвати творчою особистістю");
                conclMass[1] = new Conclusion(6, 10, @"Ви — повноцінна творча особистість!");
                break;

            case "ru-RU":
                conclMass[0] = new Conclusion(1, 5, @"К сожалению, Вас нельзя назвать творческой личностью");
                conclMass[1] = new Conclusion(6, 10, @"Вы — полноценная творческая личность! ");
                break;

            case "en-US":
                conclMass[0] = new Conclusion(1, 5, @"Unfortunatelly, you don't seem to be artistic person.");
                conclMass[1] = new Conclusion(6, 10, @"You are completely artistic person!");
                break;

            default:
                conclMass[0] = new Conclusion(1, 5, @"Unfortunatelly, you don't seem to be artistic person.");
                conclMass[1] = new Conclusion(6, 10, @"You are completely artistic person!");
                break;
            }
            for (int i = 0; i < conclMass.Length; i++)
            {
                if (summResult <= conclMass[i].b && summResult >= conclMass[i].a)
                {
                    return(conclMass[i].textOfConclusion);
                }
            }
            return("");
        }
Example #13
0
        public MethodOptimist()
        {
            conclMass[0]      = new Conclusion(0, 13, @"Схоже, життя вас не раз випробувало,
і ви вже не чекаєте від нього нічого доброго.
Невдачі вважаєте неминучими,
радощі - випадковими.
Жалість до себе і недовіра до людей заважають
вам радіти життю.
Щоб підбадьоритися, навчіться цінувати ті маленькі радощі,
які випадають кожному з нас. Не забувайте:
життя ніколи не є настільки поганим,
щоб його не можна було змінити нашим ставленням до нього.");
            conclMass[1]      = new Conclusion(14, 23, @"Ви розсудлива людина, що знає ціну собі і людям.
Ви вмієте ставити перед собою реальну мету і добиватися її.
Ясно бачите тіньові сторони життя, але не схильні їх смакувати.
Для своїх друзів і близьких ви — надійна опора,
тому що вмієте і втішити в горі,
і остудити надмірне захоплення.");
            conclMass[2]      = new Conclusion(24, 30, @"Ваш оптимізм просто б'є через край.
Неприємності для вас немов і не існують,
і ви від них просто відмахуєетесь і поспішаєте
назустріч новим радощам. Проте задумайтеся:
чи не дуже легковажна ваша позиція?
Не виключено, що недооцінка серйозних проблем одного
разу примусить вас зіткнутися з несподіваними засмученнями.");
            numberOfQuestions = 35;
        }
Example #14
0
 /// <summary>Reports test error conclusion.</summary>
 /// <param name="message">Message text.</param>
 /// <param name="report">The report the message belongs to.</param>
 public void AddTestErrorConclusion(
     string message,
     BenchmarkReport report = null)
 {
     this.WriteTestErrorMessage(message);
     ConclusionsList.Add(Conclusion.CreateWarning(Id, message, report));
 }
Example #15
0
        private static IList <Statement> GetSortedStatementsByConclusion(Conclusion conclusion,
                                                                         IList <Statement> stetementList)
        {
            IList <Statement> sortedList = new List <Statement>();

            foreach (var statement in stetementList)
            {
                if (conclusion.Subject.ToUpper() == statement.Subject.ToUpper() &&
                    conclusion.Predicate.ToUpper() == statement.Predicate.ToUpper())
                {
                    sortedList.Clear();
                    sortedList.Add(statement);
                    break;
                }
                else if (conclusion.Predicate.ToUpper() == statement.Subject.ToUpper() &&
                         conclusion.Subject.ToUpper() == statement.Predicate.ToUpper())
                {
                    sortedList.Clear();
                    sortedList.Add(statement);
                    break;
                }
                else if (conclusion.Subject.ToUpper() == statement.Subject.ToUpper() ||
                         conclusion.Subject.ToUpper() == statement.Predicate.ToUpper())
                {
                    sortedList.Add(statement);
                }
                else if (conclusion.Predicate.ToUpper() == statement.Subject.ToUpper() ||
                         conclusion.Predicate.ToUpper() == statement.Predicate.ToUpper())
                {
                    sortedList.Add(statement);
                }
            }
            return(sortedList);
        }
Example #16
0
 /// <summary>Reports test error conclusion.</summary>
 /// <param name="message">Message text.</param>
 /// <param name="report">The report the message belongs to.</param>
 public override void AddTestErrorConclusion(
     string message,
     BenchmarkReport report = null)
 {
     base.AddTestErrorConclusion(message, report);
     ConclusionsList.Add(Conclusion.CreateWarning(Id, message, report));
 }
Example #17
0
        public MethodLeader()
        {
            conclMass[0] = new Conclusion(0, 91, @"Ваша роль - в добросовісному виконанні чужих ініціатив.
Ви звикли підтримувати чужу думку і слідувати генеральній лінії,
прокладеній іншими. Легко і приємно знати,
що за тебе вже всі вирішили і відповідальність
лежить не на тобі.");

            conclMass[1] = new Conclusion(92, 150, @"Тому людству і вдалося добитися таких успіхів,
що кожний з нас готовий у будь-який момент
стати провідним або відомим, лідером або підлеглим.
Вам обидві ці ролі властиві приблизно в рівному степені,
тому для вас знайдеться місце в будь-якому колективі.
Залишається сподіватися, що це місце вас влаштовує.");

            conclMass[2] = new Conclusion(151, 250, @"Ініціатива у вас незламна.
Ви у будь-який момент готові зайняти лідируючу позицію
в будь-якому колективі, роздавати доручення, 
указувати як краще і пояснювати як правильно.
Ви можете вказати шлях і повести за собою і на 
вас чекає велике майбутнє - за однієї умові:
якщо при цьому за вами йдуть.");

            numberOfQuestions = 24;
        }
Example #18
0
 public MethodLeaderPotential()
 {
     conclMass[0]      = new Conclusion(0, 70, @"Ви — дисциплінований працівник, але не упевнені в собі, тому не проявляєте ініціативу і навряд чи поведете за собою колектив");
     conclMass[1]      = new Conclusion(75, 100, @"Ви володієте виключно цінною якістю - вмінням приймати роль ведучого або відомого залежно від обставин. Пошана до авторитету не заважає вам мати власну точку зору. Для вас знайдеться місце в будь-якому колективі. Залишається тільки вибрати таке місце, яке б вас влаштовувало");
     conclMass[2]      = new Conclusion(100, 150, @"Вам не позичати ініціативи і впевненості в собі. Схоже, сама природа підготувала вам роль ватажка, забезпечивши для цього необхідними якостями — сміливістю, цілеспрямованістю, твердою волею. Проте у цих достоїнств буває і зворотна сторона — завищена самооцінка, безцеремонність, невміння зважати на чужі інтереси. Ви зумієте добитися чималих успіхів, якщо пам'ятатимете: люди охоче йдуть за лідерами, але неполюбляють диктаторів");
     numberOfQuestions = 15;
 }
Example #19
0
 /// <summary>Reports analyser warning conclusion.</summary>
 /// <param name="message">Message text.</param>
 /// <param name="hint">Hint how to fix the warning.</param>
 /// <param name="report">The report the message belongs to.</param>
 public void AddWarningConclusion(
     string message,
     string hint,
     BenchmarkReport report = null)
 {
     this.WriteWarningMessage(message, hint);
     ConclusionsList.Add(Conclusion.CreateWarning(Id, message, report));
 }
Example #20
0
 // POST api/conclusion
 public Conclusion Post(Conclusion con)
 {
     if (conService.Insert(con))
     {
         return(con);
     }
     return(null);
 }
Example #21
0
 /// <summary>Reports test error conclusion.</summary>
 /// <param name="target">Target the message applies for.</param>
 /// <param name="message">Message text.</param>
 /// <param name="report">The report the message belongs to.</param>
 public void AddTestErrorConclusion(
     Target target,
     string message,
     BenchmarkReport report = null)
 {
     this.WriteTestErrorMessage(target, message);
     ConclusionsList.Add(Conclusion.CreateWarning(Id, FormatMessage(target, message), report));
 }
Example #22
0
 public override void Start()
 {
     score           = new Score();
     player.isFreeze = true;
     introduction    = GetComponent <Introduction>();
     conclusion      = GetComponent <Conclusion>();
     base.Start();
 }
Example #23
0
        protected override void ModifyEntity(ConclusionEssential entity)
        {
            Conclusion conclusion = SampleEntity.CreateConclusion(Session);

            Session.Save(conclusion);
            Session.Evict(conclusion);

            entity.Conclusion = conclusion;
        }
Example #24
0
        public static TaskFunc DownloadFile(string url, string fileName)
        {
            return((Tasker tasker, Object sync) =>
            {
                Debug.WriteLine($"Downloading: {url} to {fileName}");
                Conclusion result = Conclusion.Success;
                var wc = new HakchiWebClient();
                wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);

                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(async(object sender, DownloadProgressChangedEventArgs e) =>
                {
                    tasker.SetProgress(e.BytesReceived, e.TotalBytesToReceive);
                    tasker.SetStatus(String.Format(Resources.DownloadingProgress, Shared.SizeSuffix(e.BytesReceived), Shared.SizeSuffix(e.TotalBytesToReceive)));
                });
                wc.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) =>
                {
                    if (e.Error != null)
                    {
                        File.Delete(fileName);
                        result = Conclusion.Error;
                    }
                    else
                    {
                        try
                        {
                            var date = DateTime.ParseExact(wc.ResponseHeaders.Get("Last-Modified"),
                                                           "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                                                           CultureInfo.InvariantCulture.DateTimeFormat,
                                                           DateTimeStyles.AssumeUniversal);

                            File.SetLastWriteTimeUtc(fileName, date);
                        } catch (Exception) { }
                    }
                };
                var downloadTask = wc.DownloadFileTaskAsync(new Uri(url), fileName);
                new Thread(() =>
                {
                    while (true)
                    {
                        if (tasker.TaskConclusion == Conclusion.Abort)
                        {
                            Debug.WriteLine("Download Aborted");
                            wc.CancelAsync();
                            break;
                        }
                        if (downloadTask.IsCanceled || downloadTask.IsCompleted || downloadTask.IsFaulted)
                        {
                            break;
                        }

                        Thread.Sleep(100);
                    }
                }).Start();
                downloadTask.Wait();
                return result;
            });
        }
        public EditRuleForm(List <FuzzyVariable> variables, Rule rule)
            : this(variables)
        {
            _conditions = rule.Conditions;
            _conclusion = rule.Conclusion;

            RefreshConditionsListView();
            RefreshConclusionListView();
        }
 private void deleteConclusion_Click(object sender, System.EventArgs e)
 {
     if (_conclusion == null)
     {
         MessageBox.Show("Заключение можно удалить только после заполнения", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     _conclusion = null;
     RefreshConclusionListView();
 }
Example #27
0
 /// <summary>Reports analyser warning conclusion.</summary>
 /// <param name="target">Target the message applies for.</param>
 /// <param name="message">Message text.</param>
 /// <param name="hint">Hint how to fix the warning.</param>
 /// <param name="report">The report the message belongs to.</param>
 public void AddWarningConclusion(
     Target target,
     string message,
     string hint,
     BenchmarkReport report = null)
 {
     this.WriteWarningMessage(target, message, hint);
     ConclusionsList.Add(Conclusion.CreateWarning(Id, FormatMessage(target, message), report));
 }
Example #28
0
        private void button7_Click(object sender, EventArgs e)
        {
            Statement1 = txtStatement1.Text;
            Statement2 = txtStatement2.Text;
            Statement3 = txtStatement3.Text;

            Conclusion4 = txtConclusion4.Text;

            Statement         s1            = new Statement(Statement1.ToUpper().Trim());
            Statement         s2            = new Statement(Statement2.ToUpper().Trim());
            Statement         s3            = new Statement(Statement3.ToUpper().Trim());
            IList <Statement> StatementList = new List <Statement> {
            };

            if (!String.IsNullOrEmpty(Statement1.Trim()))
            {
                StatementList.Add(s1);
            }
            if (!String.IsNullOrEmpty(Statement2.Trim()))
            {
                StatementList.Add(s2);
            }
            if (!String.IsNullOrEmpty(Statement3.Trim()))
            {
                StatementList.Add(s3);
            }

            Conclusion c4 = null;

            if (!String.IsNullOrEmpty(Conclusion4.Trim()))
            {
                c4 = new Conclusion(Conclusion4.ToUpper().Trim(), StatementList);
            }
            IList <Statement> sList = new List <Statement>();

            StatementList = CorrespondingPair.GetCorrespondingAlignedStatementsByConclusion(c4, StatementList, out sList);

            if (StatementList.Count == 1)
            {
                lblResult.Text = "Corresponding Statement is : " + "\n\n" +
                                 "1 ) " + StatementList[0].StatementName.ToUpper() + "\n";
            }
            else if (StatementList.Count == 2)
            {
                lblResult.Text = "Corresponding Statements are : " + "\n\n" +
                                 "1 ) " + StatementList[0].StatementName.ToUpper() + "\n" +
                                 "2 ) " + StatementList[1].StatementName.ToUpper() + "\n";
            }
            else if (StatementList.Count == 3)
            {
                lblResult.Text = "Corresponding Statements are : " + "\n\n" +
                                 "1 ) " + StatementList[0].StatementName.ToUpper() + "\n" +
                                 "2 ) " + StatementList[1].StatementName.ToUpper() + "\n" +
                                 "3 ) " + StatementList[2].StatementName.ToUpper() + "\n";
            }
        }
Example #29
0
        public MethodVouting()
        {
            conclMass[0] = new Conclusion(0, 5, @"На жаль, ваш рівень незадовільний");
            conclMass[1] = new Conclusion(6, 7, @"ваш рівень задовільний, і не більше");
            conclMass[2] = new Conclusion(8, 9, @"ви добре впоралися із завданням");
            conclMass[3] = new Conclusion(9, 10, @"ви відмінно впоралися із завданнм");
            conclMass[4] = new Conclusion(11, 11, @"Ви дали правильні відповіді на всі поставлені запитання");


            numberOfQuestions = 12;
        }
Example #30
0
 /// <summary>Reports test error conclusion.</summary>
 /// <param name="target">Target the message applies for.</param>
 /// <param name="message">Message text.</param>
 /// <param name="report">The report the message belongs to.</param>
 public override void AddTestErrorConclusion(
     Target target,
     string message,
     BenchmarkReport report = null)
 {
     base.AddTestErrorConclusion(target, message, report);
     ConclusionsList.Add(
         Conclusion.CreateWarning(
             Id, $"Target {target.MethodDisplayInfo}. {message}",
             report));
 }
Example #31
0
        public Conclusion Run(ExecuterStartInfo executerStartInfo)
        {
            //paranoidal checks
            if (string.IsNullOrEmpty(executerStartInfo.InputStream) == false)
            {
                var inputFileFullPath = executerStartInfo.InputStream;
                if (string.IsNullOrEmpty(executerStartInfo.WorkingDirectory) == false)
                    inputFileFullPath = Path.Combine(executerStartInfo.WorkingDirectory, executerStartInfo.InputStream);
                if (!File.Exists(inputFileFullPath))
                    throw new FileNotFoundException(string.Format("File \"{0}\" is missing.", inputFileFullPath));
            }

            //runexe.exe -i a.in -t 3500ms -m 2048K -xml a.exe
            string options = "";

            if (executerStartInfo.WorkingDirectory == null)
                executerStartInfo.WorkingDirectory = "";

            //set input file
            if (string.IsNullOrEmpty(executerStartInfo.InputStream) == false)
            {
                options += string.Format(" -i \"{0}\"", Path.Combine(executerStartInfo.WorkingDirectory, executerStartInfo.InputStream));
            }

            //set output file
            string temporaryOutputFile = null;
            string temporaryDirectory = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
            if (string.IsNullOrEmpty(executerStartInfo.OutputStream) == false)
            {
                options += string.Format(" -o \"{0}\"", Path.Combine(executerStartInfo.WorkingDirectory, executerStartInfo.OutputStream));
            }
            else
            {
                temporaryOutputFile = Path.Combine(temporaryDirectory, Path.GetRandomFileName());
                Directory.CreateDirectory(temporaryDirectory);
                options += string.Format(" -o \"{0}\"", temporaryOutputFile);
            }

            //set error file
            string temporaryErrorFile = null;
            if (string.IsNullOrEmpty(executerStartInfo.ErrorStream) == false)
            {
                options += string.Format(" -e \"{0}\"", Path.Combine(executerStartInfo.WorkingDirectory, executerStartInfo.ErrorStream));
            }
            else
            {
                temporaryErrorFile = Path.Combine(temporaryDirectory, Path.GetRandomFileName());
                Directory.CreateDirectory(temporaryDirectory);
                options += string.Format(" -e \"{0}\"", temporaryErrorFile);
            }

            //set time limit
            if (executerStartInfo.TimeLimit > 0)
            {
                options += string.Format(" -t {0}ms", executerStartInfo.TimeLimit);
            }

            //set memory limit
            if (executerStartInfo.MemoryLimit > 0)
            {
                options += string.Format(" -m {0}K", executerStartInfo.MemoryLimit / 1024);
            }

            //set working directory
            if (string.IsNullOrEmpty(executerStartInfo.WorkingDirectory) == false)
            {
                options += " -d " + executerStartInfo.WorkingDirectory;
            }

            //result of runexe in XML format
            options += " -xml";

            var startInfo = new ProcessStartInfo
                                {
                                    UseShellExecute = false,
                                    ErrorDialog = false,
                                    CreateNoWindow = true,
                                    FileName = _pathToRunExe,
                                    RedirectStandardOutput = true,
                                    Arguments = string.Format("{0} {1}", options, executerStartInfo.Command),
                                };

            Console.WriteLine(string.Format("Run \"{0} {1}\".", startInfo.FileName,
                                            startInfo.Arguments));

            _process = new Process { StartInfo = startInfo };

            Conclusion conclusion = new Conclusion();

            try
            {
                _process.Start();

                var stdoutReader = _process.StandardOutput;

                if (executerStartInfo.TimeLimit != 0)
                {
                    // implementation of TimeLimit: wait for process
                    // only some time, than kill it
                    var milliseconds = (int)executerStartInfo.TimeLimit * 2;
                    _process.WaitForExit(milliseconds);

                    // kill the process after waiting
                    if (!_process.HasExited)
                    {
                        try
                        {
                            _process.Kill();
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // after kill return time limit
                        //return this.SetResult(Verdict.TL, "Time limit occured");

                        conclusion.ExecutionVerdict = ExecutionVerdict.TimeLimitExceeded;

                        if (string.IsNullOrEmpty(temporaryOutputFile)==false)
                        {
                            File.Delete(temporaryOutputFile);
                        }
                        if (string.IsNullOrEmpty(temporaryErrorFile) == false)
                        {
                            File.Delete(temporaryErrorFile);
                        }

                        return conclusion;
                    }
                }

                string xml = stdoutReader.ReadToEnd();
                //Console.WriteLine(xml);
                InvocationResult invocationResult = InvocationResult.DeserializeFromXml(xml);

                switch (invocationResult.InvocationVerdict)
                {
                    case "SUCCESS":
                        conclusion.ExecutionVerdict = ExecutionVerdict.Success;
                        conclusion.UsedMemory = invocationResult.ConsumedMemory;
                        conclusion.UsedTime = invocationResult.ProcessorKernelModeTime +
                                              invocationResult.ProcessorUserModeTime;
                        break;
                    case "IDLENESS_LIMIT_EXCEEDED":
                    case "TIME_LIMIT_EXCEEDED":
                        conclusion.ExecutionVerdict = ExecutionVerdict.TimeLimitExceeded;
                        break;
                    case "MEMORY_LIMIT_EXCEEDED":
                        conclusion.ExecutionVerdict = ExecutionVerdict.MemoryLimitExceeded;
                        break;
                    default:
                        throw new InvalidOperationException(string.Format("InvocationVerdict \"{0}\" from runexe does not understand.", invocationResult.InvocationVerdict));
                }

                conclusion.ReturnCode = invocationResult.ExitCode;
                if (invocationResult.ExitCode != 0)
                    conclusion.ExecutionVerdict = ExecutionVerdict.RuntimeError;
            }
            catch (Exception exception)
            {

                throw;
            }

            if (string.IsNullOrEmpty(temporaryOutputFile) == false && File.Exists(temporaryOutputFile))
            {
                File.Delete(temporaryOutputFile);
            }
            if (string.IsNullOrEmpty(temporaryErrorFile) == false && File.Exists(temporaryErrorFile))
            {
                File.Delete(temporaryErrorFile);
            }

            return conclusion;
        }
Example #32
0
 void Awake() {
     Instance = this;
 }