Task<StacManResponse<Answer>> IQuestionMethods.GetAnswers(string site, IEnumerable<int> ids, string filter = null, int? page = null, int? pagesize = null, DateTime? fromdate = null, DateTime? todate = null, Answers.Sort? sort = null, DateTime? mindate = null, DateTime? maxdate = null, int? min = null, int? max = null, Order? order = null)
        {
            var filterObj = ValidateAndGetFilter(filter);

            ValidateString(site, "site");
            ValidateEnumerable(ids, "ids");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder(String.Format("/questions/{0}/answers", String.Join(";", ids)), useHttps: false);

            ub.AddParameter("site", site);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, filterObj, "/questions/{ids}/answers");
        }
Ejemplo n.º 2
0
 public static Answers KamalsAnswers()
 {
     Answers answers = new Answers();
     answers.AddAnswer(KamalsGoodAnswer(UserMother.Kamal));
     answers.AddAnswer(KamalsBadAnswer(UserMother.Kamal));
     return answers;
 }
        Task<StacManResponse<Answer>> IAnswerMethods.GetAll(string site, string filter = null, int? page = null, int? pagesize = null, DateTime? fromdate = null, DateTime? todate = null, Answers.Sort? sort = null, DateTime? mindate = null, DateTime? maxdate = null, int? min = null, int? max = null, Order? order = null)
        {
            var filterObj = ValidateAndGetFilter(filter);

            ValidateString(site, "site");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder("/answers", useHttps: false);

            ub.AddParameter("site", site);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, filterObj, "/answers");
        }
Ejemplo n.º 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        _session = SamplePortal.Factory.GetWorkSession(this.Session);
        if (_session == null)
            Response.Redirect("Default.aspx");
        _ansPath = _session.AnswerCollection.FilePath;
        _ansFilename = Path.GetFileName(_ansPath);
        if (!IsPostBack) // first arrival on this page
        {
            // Set the max length on the title and description fields. These were previously set in the ASPX page,
            // but ASP.NET drops them for multi-line fields when rendering the page.
            // So we set them manually here using values configurable in the web.config.
            txtTitle.Attributes.Add("maxlength", Settings.MaxTitleLength.ToString());
            txtDescription.Attributes.Add("maxlength", Settings.MaxDescriptionLength.ToString());

            ViewState["answers"] = HotDocs.Sdk.Server.InterviewResponse.GetAnswers(Request.Form); // get the answers from the browser

            if (_session.AnswerCollection.FilePath.Length > 0)
            {
                using (Answers answers = new Answers())
                {
                    DataView ansData = answers.SelectFile(_ansFilename);
                    // pre-populate answer set title and description
                    txtTitle.Text = ansData[0]["Title"].ToString();
                    txtDescription.Text = ansData[0]["Description"].ToString();
                }
            }
        }
    }
Ejemplo n.º 5
0
 public Question(int id = 0, string text = null, Domain domain = 0, int difficulty = 0, Answers answers = null)
 {
     this.id = id;
     this.text = text;
     this.domain = domain;
     this.answers = answers;
     this.difficulty = difficulty;
 }
Ejemplo n.º 6
0
 protected void ansGrid_DeleteCommand(object source, DataGridCommandEventArgs e)
 {
     string answerFileName = e.Item.Cells[2].Text;
     using (Answers answers = new Answers())
     {
         answers.DeleteAnswerFile(answerFileName);
     }
     System.IO.File.Delete(System.IO.Path.Combine(Settings.AnswerPath, answerFileName));
     BindData(null);
 }
Ejemplo n.º 7
0
            private void AddOfficeFields(IDictionary electionsRecord, string electionKey)
            {
                var reportData =
                    Elections.GetElectionReportData(electionKey)
                    .Rows.OfType <DataRow>()
                    .Where(r => !IsNullOrWhiteSpace(r.PoliticianKey()))
                    .ToList();
                var reportGroups =
                    reportData
                    .OrderBy(r => r.AlternateOfficeLevel())
                    .ThenBy(r => r.OfficeLevel())
                    .ThenBy(r => r.DistrictCode())
                    .ThenBy(r => r.OfficeOrderWithinLevel())
                    .ThenBy(r => r.OfficeLine1())
                    .ThenBy(r => r.OrderOnBallot())
                    .GroupBy(r => r.OfficeKey());
                List <DataRow> issues = null;

                if (_Bio || _Reasons || _Issues)
                {
                    var politicians =
                        reportData.Select(r => r.PoliticianKey())
                        .Union(
                            reportData.Where(r => !IsNullOrWhiteSpace(r.RunningMateKey()))
                            .Select(r => r.RunningMateKey()))
                        .Distinct();
                    issues =
                        Answers.GetActiveDataByPoliticianKeys(politicians)
                        .Rows.OfType <DataRow>()
                        .ToList();
                }
                var officesArray = new ArrayList();

                electionsRecord.Add("offices", officesArray);
                foreach (var officeGroup in reportGroups)
                {
                    var officeRow    = officeGroup.First();
                    var officeRecord = new Hashtable();
                    officesArray.Add(officeRecord);
                    AddField(officeRecord, "officeKey", officeRow.OfficeKey());
                    AddField(officeRecord, "officeLine1", officeRow.OfficeLine1());
                    AddField(officeRecord, "officeLine2", officeRow.OfficeLine2());
                    AddField(officeRecord, "isRunningMateOffice", officeRow.IsRunningMateOffice());
                    if (_Candidates)
                    {
                        var candidatesArray = new ArrayList();
                        officeRecord.Add("candidates", candidatesArray);
                        AddCandidateFields(candidatesArray, officeGroup, issues);
                    }
                }
            }
Ejemplo n.º 8
0
        public ActionResult Post(int questionId, [FromBody] Answers answer)
        {
            MySql.Data.MySqlClient.MySqlConnection connection = null;
            string _connectionString;

            _connectionString = context.connectionString;
            try
            {
                connection = new MySql.Data.MySqlClient.MySqlConnection();
                connection.ConnectionString = _connectionString;
                connection.Open();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (questionId <= 0 || answer.UserId <= 0 || answer.Description.Length == 0 || answer.Author.Length == 0)
            {
                return(BadRequest("Request not valid"));
            }

            String sqlString = String.Format("insert into answers(questionId, userId, description, rating, date, author) values ({0}, {1}, '{2}', '{3}', '{4}', '{5}')",
                                             questionId, answer.UserId, answer.Description.Replace("\'", "\\'"), answer.Rating != null ? answer.Rating : 0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), answer.Author);

            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, connection);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (MySql.Data.MySqlClient.MySqlException sqlEx)
            {
                Console.WriteLine(sqlEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            long id = cmd.LastInsertedId;

            if (id < 0)
            {
                return(BadRequest("Answer not submited"));
            }
            else
            {
                return(Ok(id));
            }
        }
Ejemplo n.º 9
0
        public override void Initialize(string[] answerSet, int answerCount)
        {
            MaxAnswer = answerCount;
            for (int i = 0; i < AnswerButtons.Length; i++)
            {
                int maxNumber = answerSet.Length;
                if (maxNumber % 4 != 0)
                {
                    maxNumber += 2;
                }

                if (i < answerSet.Length)
                {
                    AnswerButtons[i].gameObject.SetActive(true);

                    //최적화 문제 있음
                    AnswerButtons[i].GetComponentInChildren <Text>().text = answerSet[i];
                }
                else
                {
                    if (i < maxNumber)
                    {
                        AnswerButtons[i].gameObject.SetActive(true);
                    }
                    else
                    {
                        AnswerButtons[i].gameObject.SetActive(false);
                    }
                }
            }

            //선택 및 모양 초기화
            Answers.Clear();
            foreach (Button target in AnswerButtons)
            {
                target.colors = new ColorBlock()
                {
                    normalColor      = Color.black,
                    highlightedColor = Color.black,
                    pressedColor     = Color.gray,
                    selectedColor    = Color.black,
                    disabledColor    = Color.gray,
                    colorMultiplier  = 1,
                    fadeDuration     = 0.1f
                };
            }

            CurrentPage = 0;
            IsMoving    = false;
            InitializePagePosition();   //currentPage 값이 이상할 수 있으니 움직임과 상관 없이 위치 결정
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the view model for an answer.
        /// </summary>
        /// <param name="answer">The answer.</param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public AnswersViewModel GetViewModel(Answers answer)
        {
            try {
                AnswersViewModel avm = new AnswersViewModel();
                avm.AnswerId    = answer.AnswerId;
                avm.AnswerType  = answer.AnswerType;
                avm.AnswerValue = answer.AnswerValue;

                return(avm);
            }
            catch (Exception ex) {
                throw new CustomException(ex.Message);
            }
        }
Ejemplo n.º 11
0
        public static bool ExecuteRule(RuleBase rule, Answers answers, Bundle bundle)
        {
            if (rule is IAnswerParameter)
            {
                return(((IAnswerParameter)rule).Execute(answers));
            }

            if (rule is IBundleParameter)
            {
                return(((IBundleParameter)rule).Execute(bundle));
            }

            throw new Exception("Unrecognized rule parameter type.");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Returns the check box status to the event subscribers
        /// once the survey's page get posted
        /// </summary>
        protected override PostedAnswerDataCollection GetPostedAnswerData()
        {
            int answerFileCount = new Answers().GetAnswerFileCount(this.GroupGuid);

            if (this.Mandatory && (answerFileCount == 0))
            {
                this.OnInvalidAnswer(new AnswerItemInvalidEventArgs(string.Format(ResourceManager.GetString("UploadFileRequiredMessage", base.LanguageCode), this.Text)));
            }
            PostedAnswerDataCollection datas = new PostedAnswerDataCollection();

            datas.Add(new PostedAnswerData(this, this.AnswerId, base.SectionContainer.SectionNumber, this.GroupGuid, AnswerTypeMode.ExtendedType | AnswerTypeMode.Upload | AnswerTypeMode.Mandatory));

            return(datas);
        }
Ejemplo n.º 13
0
        public Question ToEntity()
        {
            var result = new Question();

            result.Answers        = Answers.Select(a => a.ToEntity()).ToList();
            result.CanSkip        = CanSkip;
            result.Enquiry        = Enquiry;
            result.Id             = Id;
            result.IsSingleSelect = IsSingleSelect;
            result.IsUserMeta     = IsUserMeta;
            result.QuizId         = QuizId;

            return(result);
        }
        public IActionResult Answer(string text, int Id)
        {
            var repo   = new UserRepository(_connectionString);
            var a      = repo.GetByEmail(User.Identity.Name);
            var answer = new Answers
            {
                QuestionsId = Id,
                UserId      = a.Id,
                Text        = text
            };

            repo.AddAnswer(answer);
            return(Redirect($"/home/home"));
        }
Ejemplo n.º 15
0
        public Question Selection(string answer)
        {
            //if that answer is in the dictionary of answers
            if (Answers.ContainsKey(answer))
            {
                //return the next question
                Question questionToReturn = Answers[answer];

                questionToReturn.SetPrevious(this);
                return(questionToReturn);
            }
            Console.WriteLine("Invalid Selection");
            return(this);
        }
Ejemplo n.º 16
0
        TestAnswerPostModel getEditableAnswer(bool isAuto)
        {
            var answersList = Answers?.Select(
                a => new TestAnswerDetailsPostModel(
                    Answers[0].Id, isAuto ? _emptyEditableAnswer : Answers[0].ContentToAnswer)).ToList();

            if (answersList != null && answersList.Count > 0 &&
                string.IsNullOrWhiteSpace(answersList[0].Content))
            {
                return(null);
            }

            return(composeAnswer(answersList));
        }
Ejemplo n.º 17
0
        public int SameAnswerCount()
        {
            var distinctAnswers      = Answers.Distinct();
            var allAnsweredSameCount = 0;

            foreach (var answer in distinctAnswers)
            {
                if (Answers.Count(x => x == answer) == PeopleCount)
                {
                    allAnsweredSameCount++;
                }
            }
            return(allAnsweredSameCount);
        }
Ejemplo n.º 18
0
        protected void ButtonDeleteQuestion_Click(object sender, EventArgs e)
        {
            try
            {
                // checks
                CheckForDangerousInput();
                var questionKey = TextBox_Delete_QuestionKey.Text.Trim();

                if (!Questions.QuestionKeyExists(questionKey))
                {
                    throw new ApplicationException("The QuestionKey is not valid.");
                }

                var count = Answers.CountByQuestionKey(questionKey);
                if (count > 0)
                {
                    throw new ApplicationException(
                              $"There are {count} answers. These need to be reassigned or" +
                              " deleted before this question can be deleted.");
                }

                // Msg needs to come before question is deleted
                Msg.Text =
                    Ok($"The question ({Questions.GetQuestion(questionKey)})" +
                       " has been deleted.");

                Questions.DeleteByQuestionKey(questionKey);

                RenumberQuestions();

                CreateQuestionsReport();

                // Reset Tables Not Visible
                if (Questions.CountByIssueKey(_IssueKey) == 0)
                {
                    Table_Question_Edit.Visible    = false;
                    Table_Question_Add.Visible     = false;
                    Table_Question.Visible         = false;
                    Table_Delete_Question.Visible  = false;
                    Table_Questions_Report.Visible = false;
                }

                TextBox_Delete_QuestionKey.Text = Empty;
            }
            catch (Exception ex)
            {
                Msg.Text = Fail(ex.Message);
                LogAdminError(ex);
            }
        }
Ejemplo n.º 19
0
        public void Set()
        {
            Dictionary <String, Double> dic = TeacherCheckManagerx.GetFinalScore();

            if (dic == null)
            {
                return;
            }

            Answers.ForEach(s =>
            {
                s.FinalScore = dic[s.AnswerId];
            });
        }
Ejemplo n.º 20
0
        /// <summary>
        /// from json object, gets all neighborhoods without blanks or duplicates
        /// </summary>
        /// <param name="myAnswers">json data converted in objects</param>
        /// <returns>list of neighborhoods no duplicates no blanks</returns>
        static List <string> AllInOneQuery(Answers myAnswers)
        {
            var noBlanksOrDuplicates = (from result in myAnswers.Features
                                        where       result.Properties.Neigborhood != ""
                                        select result.Properties.Neigborhood)
                                       .GroupBy(x => x).Select(x => x.First()).ToList <string>();

            foreach (var item in noBlanksOrDuplicates)
            {
                Console.WriteLine(item);
            }

            return(noBlanksOrDuplicates);
        }
Ejemplo n.º 21
0
        public void DeleteAnswer()
        {
            if (SelectedAnswer != null)
            {
                Answer answer = SelectedAnswer.ToPoco();

                AnswerRepository.Delete(answer.AnswerID);

                SelectedQuestion.Answers.Remove(answer);
                Answers.Remove(SelectedAnswer);
                AnswerRepository.Save();
                RaisePropertyChanged("Answers");
            }
        }
        public static int UpdateAnswer(Answers answer)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["DealQuestionAnswerDBCS"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                string     query = "update Answers set Answer=@ans where Id=@id";
                SqlCommand cmd   = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@ans", answer.Answer);
                cmd.Parameters.AddWithValue("@id", answer.Id);
                con.Open();
                return(cmd.ExecuteNonQuery());
            }
        }
Ejemplo n.º 23
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Answers answers = db.Answers.Find(id);

            if (answers == null || answers.UserID != User.Identity.GetUserId() || !User.IsInRole("Administrator"))
            {
                return(HttpNotFound());
            }
            return(View(answers));
        }
Ejemplo n.º 24
0
        public async Task <bool> DeleteAnswers(Guid id)
        {
            Answers answers = await db.answers.FindAsync(id);

            try {
                db.answers.Remove(answers);
                await db.SaveChangesAsync();

                return(true);
            }
            catch (SqlException ex) {
                throw ex;
            }
        }
Ejemplo n.º 25
0
 static void Main(string[] args)
 {
     Console.WriteLine("数字を入力してくれ");
     try
     {
         string  input   = Console.ReadLine();
         Answers answers = new Answers();
         answers.OutputEvenOrOdd(int.Parse(input));
     }
     catch
     {
         Console.WriteLine("数字を入力しろと言ったはずだが???");
     }
 }
Ejemplo n.º 26
0
        private void AnswerUser(string Message, int ImageId, int UserId)
        {
            EGalleryEntities db     = new EGalleryEntities();
            Users            user   = db.Users.Find(UserId);
            Answers          answer = new Answers()
            {
                UserId    = user.Id,
                PictureId = ImageId,
                Text      = user.Nick + ", your image: " + Message + "."
            };

            db.Answers.Add(answer);
            db.SaveChanges();
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Открывает диалог выбора файлов с ответами к тестам
 /// </summary>
 private void AddAnswer_Click(object sender, RoutedEventArgs e)
 {
     OpenFile("Text documents (.txt)|*.txt", (name) =>
     {
         Answers.Add(name);
         var fileName = System.IO.Path.GetFileNameWithoutExtension(name);
         AnswerList.Items.Add(new ListBoxItem
         {
             Height  = 20,
             Content = $"{Answers.Count}: {fileName}"
         });
         testCount.Text = $"{Tests.Count} : {Answers.Count}";
     });
 }
Ejemplo n.º 28
0
        public void AddChild(SurveyObjectBase item)
        {
            var child = item as Answer;

            if (item != null)
            {
                Answers.Add((Answer)item);
                item.Parent = this;
            }
            else
            {
                throw new Exception($"Item with type {item.GetType().Name} cannot be child of type Question");
            }
        }
Ejemplo n.º 29
0
        public ActionResult DeleteConfirmed(int id)
        {
            QAnswers[] qAnswers = db.QAnswers.Where(x => x.AId == id).ToArray();
            foreach (QAnswers qA in qAnswers)
            {
                db.QAnswers.Remove(qA);
                db.SaveChanges();
            }
            Answers answers = db.Answers.Find(id);

            db.Answers.Remove(answers);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 30
0
        // GET: Answer/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Answers answer = db.Answers.Find(id);

            if (answer == null)
            {
                return(HttpNotFound());
            }
            return(View(answer));
        }
Ejemplo n.º 31
0
 public ActionResult EditAnswer(Answers answer)
 {
     if (ModelState.IsValid)
     {
         AnswersRepository.SaveAnswer(answer);
         TempData["message"] = string.Format("Изменения в ответе были сохранены");
         return(RedirectToAction("Index"));
     }
     else
     {
         // Что-то не так со значениями данных
         return(View(answer));
     }
 }
Ejemplo n.º 32
0
 private void addAnswers(List <Answer> allAnswers)
 {
     foreach (Answer a in allAnswers)
     {
         AnswerView av = new AnswerView();
         av.AnsweredById   = a.AnsweredBy.Id;
         av.AnsweredByName = a.AnsweredBy.FirstName + " " + a.AnsweredBy.LastName;
         av.AnswerId       = a.AnswerId;
         av.AnswerText     = a.AnswerText;
         av.AnsweredDate   = a.CreatedAt;
         av.Votes          = a.Votes;
         Answers.Add(av);
     }
 }
        // GET: Answers/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Answers answers = await db.Answers.FindAsync(id);

            if (answers == null)
            {
                return(HttpNotFound());
            }
            return(View(answers));
        }
Ejemplo n.º 34
0
        private async Task ReceiveAnswer(CommandEventArgs e, Answers userAnswer)
        {
            var response = userAnswer == Answers.Betray
                ? ":no_entry: `You betrayed nadeko` - you monster."
                : ":ok: `You cooperated with nadeko.` ";
            var currentAnswer = NextAnswer;
            var nadekoResponse = currentAnswer == Answers.Betray
                ? ":no_entry: `aww Nadeko betrayed you` - she is so cute"
                : ":ok: `Nadeko cooperated.`";
            NextAnswer = userAnswer;
            if (userAnswer == Answers.Betray && currentAnswer == Answers.Betray)
            {
                NadekoPoints--;
                UserPoints--;
            }
            else if (userAnswer == Answers.Cooperate && currentAnswer == Answers.Cooperate)
            {
                NadekoPoints += 2;
                UserPoints += 2;
            }
            else if (userAnswer == Answers.Betray && currentAnswer == Answers.Cooperate)
            {
                NadekoPoints -= 3;
                UserPoints += 3;
            }
            else if (userAnswer == Answers.Cooperate && currentAnswer == Answers.Betray)
            {
                NadekoPoints += 3;
                UserPoints -= 3;
            }

            await e.Channel.SendMessage($"**ROUND {++round}**\n" +
                                        $"{response}\n" +
                                        $"{nadekoResponse}\n" +
                                        $"--------------------------------\n" +
                                        $"Nadeko has {NadekoPoints} points." +
                                        $"You have {UserPoints} points." +
                                        $"--------------------------------\n")
                                            .ConfigureAwait(false);
            if (round < 10) return;
            if (nadekoPoints == userPoints)
                await e.Channel.SendMessage("Its a draw").ConfigureAwait(false);
            else if (nadekoPoints > userPoints)
                await e.Channel.SendMessage("Nadeko won.").ConfigureAwait(false);
            else
                await e.Channel.SendMessage("You won.").ConfigureAwait(false);
            nadekoPoints = 0;
            userPoints = 0;
            round = 0;
        }
Ejemplo n.º 35
0
        public async Task <IHttpActionResult> DeleteAnswers(int id)
        {
            Answers answers = await db.Answers.FindAsync(id);

            if (answers == null)
            {
                return(NotFound());
            }

            db.Answers.Remove(answers);
            await db.SaveChangesAsync();

            return(Ok(answers));
        }
Ejemplo n.º 36
0
        public override void CreateAnswers(StreamReader reader)
        {
            FrequencyQueriesAnswer ans = new FrequencyQueriesAnswer()
            {
                answer = new List <int>()
            };

            while (!reader.EndOfStream)
            {
                ans.answer.Add(Convert.ToInt32(reader.ReadLine()));
            }

            Answers.Add(ans);
        }
Ejemplo n.º 37
0
        public void SaveResultToFile(Student student, TestUnit testUnit, Answers answers, long time, int mark)
        {
            string fileText = $"Выполнил студент {student.FIO} из группы {student.Group}\r\n";
            var    i        = 1;

            foreach (var task in testUnit.Tasks)
            {
                fileText += $"{i}. {task.TaskDescription} - {answers.AnswersList[i-1].ChosenAnswer}\r\n";
                i++;
            }
            fileText += $"Оценка - {mark}";
            Directory.CreateDirectory("./StudentsTests");
            File.WriteAllText($"./StudentsTests/{DateTime.Now.ToString().Replace(":", "-")} {student.FIO}.txt", fileText);
        }
Ejemplo n.º 38
0
    public void BtnClicked(Answers ans)
    {
        if (ans == null)
        {
            HideStoryTeller();
        }

        if (storyTextObj != null)
        {
            storyTextObj.text = storyTextObj.text + "\n" + ans.text;
            GoStoryBottom();
            if ((ans.nextEventName == null) || (ans.nextEventName == ""))
            {
                SetEndBtn();
            }
        }
    }
Ejemplo n.º 39
0
    private Answers GetAnswer(Questions question)
    {
        string selectedAnswer = GetAnswer();

        Answers answer = new Answers();
        answer.QuestionID = question.QuestionID;
        answer.UserID = SessionCache.CurrentUser.Author_ID;
        answer.Answer = selectedAnswer;
        answer.TimeStamp = DateTime.Now;

        //===========================================
        answer.Time = GetTime();  //Need to change with the actual time//int.Parse(txtTime.Text);
        //=============================================
        answer.Correct = selectedAnswer == question.CorrectAnswer ? 1 : 0;
        answer.CorrectAnswer = question.CorrectAnswer;

        return answer;
    }
        Task<StacManResponse<Answer>> IAnswerMethods.GetByIds(string site, IEnumerable<int> ids, string filter, int? page, int? pagesize, DateTime? fromdate, DateTime? todate, Answers.Sort? sort, DateTime? mindate, DateTime? maxdate, int? min, int? max, Order? order)
        {
            ValidateString(site, "site");
            ValidateEnumerable(ids, "ids");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder(Version, String.Format("/answers/{0}", String.Join(";", ids)), useHttps: false);

            ub.AddParameter("site", site);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, HttpMethod.GET, "/answers/{ids}");
        }
Ejemplo n.º 41
0
 public void ImportAnswer(Post parent, Answers a)
 {
     Post post = postRepository.FindOne(new { type = PostType.answer, sitename = currentSite, siteid = a.answer_id });
     if (post == null)
     {
         post = new Post();
     }
     post.body = a.body;
     post.community = parent.community;
     post.lastactivity = a.last_activity_date.FromUnixTime();
     post.lastedit = a.last_edit_date > a.creation_date ? a.last_edit_date.FromUnixTime() : a.creation_date.FromUnixTime();
     post.parent = parent;
     post.score = a.score;
     post.siteid = a.answer_id;
     post.sitename = currentSite;
     string strip = Regex.Replace(a.body, "<.*?>", string.Empty);
     strip = strip.Replace("\r", "").Replace("\n", "");
     string[] elementWords = strip.Split(new char[] { ' ' });
     int i = 0;
     StringBuilder sb = new StringBuilder();
     while (i < elementWords.Length)
     {
         if (i != 0)
         {
             sb.Append(" ");
         }
         if (sb.Length + elementWords[i].Length < 250)
         {
             sb.Append(elementWords[i]);
         }
         else
         {
             sb.Append("...");
             break;
         }
         i++;
     }
     post.summary = sb.ToString();
     post.tags.Clear();
     foreach (Tag t in parent.tags)
     {
         post.tags.Add(t);
     }
     post.type = PostType.answer;
     post.user = userimport.Import(userRepository, currentSite, a.owner);
     postRepository.SaveOrUpdate(post);
     foreach (Comments c in a.comments)
     {
         ImportComment(post, c);
     }
 }
Ejemplo n.º 42
0
    private AnswerTotal ModifyAnswerTotal(Answers answer, AnswerTotal answerTotal)
    {
        if(answer.Answer == "A")
        {
            answerTotal.A++;
        }
        if (answer.Answer == "BA")
        {
            answerTotal.B++;
        }
        if (answer.Answer == "C")
        {
            answerTotal.C++;
        }
        if (answer.Answer == "D")
        {
            answerTotal.D++;
        }

        answerTotal.Total++;

        return answerTotal;
            //UPDATE tbl_AnswerTotal SET [" & varAnswer & "] = [" & varAnswer & "] +1, [Total] = [Total] + 1 WHERE [QuestionID]=" & varID & ";"
    }
Ejemplo n.º 43
0
        public object Any(Answers request)
        {
            TableRepository tableRepository = new TableRepository();
            CloudTable questionTable = tableRepository.GetTable(Tables.Questions);

            Guid questionId = Guid.Parse(request.Id);

            TableQuery<QuestionEntry> questionQuery = questionTable.CreateQuery<QuestionEntry>();

            QuestionEntry questionEntry = (from k in questionQuery
                                           where k.RowKey == questionId.ToString()
                                           select k).SingleOrDefault();

            if (questionEntry == null)
                throw HttpError.NotFound("Such question do not exist");

            questionEntry.Views++;
            tableRepository.InsertOrMerge(questionEntry, Tables.Questions);

            CloudTable answerTable = tableRepository.GetTable(Tables.Answers);
            TableQuery<AnswerEntry> answerQuery = answerTable.CreateQuery<AnswerEntry>();

            AnswerEntry[] answerEntries = (from k in answerQuery
                                           where k.PartitionKey == questionId.ToString()
                                           select k).ToArray();

            UserQuestionEntry userQuestionEntry = UserSession.IsAuthenticated
                                            ? tableRepository.Get<UserQuestionEntry>(Tables.UserQuestion, questionId, UserSession.GetUserId())
                                            : null;

            HashSet<string> votesUp = new HashSet<string>(userQuestionEntry?.VotesUp?.Split('|') ?? new string[] { });
            HashSet<string> votesDown = new HashSet<string>(userQuestionEntry?.VotesDown?.Split('|') ?? new string[] { });

            Func<Guid, VoteKind> getVoteKind = ownerId =>
                                         {
                                             if (votesUp.Contains(ownerId.ToString()))
                                                 return VoteKind.Up;

                                             if (votesDown.Contains(ownerId.ToString()))
                                                 return VoteKind.Down;

                                             return VoteKind.None;
                                         };

            AnswersResponse answersResponse = new AnswersResponse
            {
                Id = questionEntry.GetId(),
                Creation = questionEntry.Creation,
                Owner = CreateUserCard(tableRepository, questionEntry.GetOwnerId()),
                Detail = questionEntry.Detail,
                Tags = questionEntry.Tags.SplitAndTrimOn(new char[] { ',' }),
                Title = questionEntry.Title,
                Views = questionEntry.Views,
                Votes = questionEntry.Votes,
                SelectedAnswer = questionEntry.SelectedAnswer,
                Answers = answerEntries.Select(k => new AnswerResult
                {
                    Owner = CreateUserCard(tableRepository, k.GetAnswerOwnerId()),
                    Creation = k.Creation,
                    Content = k.Content,
                    Votes = k.Votes,
                    VoteKind = getVoteKind(k.GetAnswerOwnerId())
                }).ToArray()
            };

            // quest user vote for this question
            answersResponse.VoteKind = getVoteKind(questionId);
            answersResponse.Love = userQuestionEntry?.Love ?? false;

            return answersResponse;
        }
Ejemplo n.º 44
0
        public ActionResult AddingTasks(System.Collections.Generic.List<string> Answers, System.Collections.Generic.List<string> Tags, string Category, string Difficulty, string HTML, string Name, int? id)
        {
            ApplicationDbContext DB = new ApplicationDbContext();
            if (Answers != null && Difficulty != null && Category != null && HTML != null)
            {
                if (Answers.Count > 0)
                {
                    if (id == null)
                    {                        
                        UserTask NewTask = new UserTask();
                        NewTask.TaskName = Name;
                        NewTask.TaskDifficulty = Difficulty;
                        NewTask.TaskCategory = Category;
                        NewTask.TaskText = HTML;
                        NewTask.TaskRating = 0;
                        NewTask.SolveCount = 0;
                        NewTask.UserID = DB.Users.First(c => c.UserName == User.Identity.Name).Id;
                        DB.Tasks.Add(NewTask);
                        DB.Entry(NewTask).State = System.Data.Entity.EntityState.Added;
                        int NewTaskID = DB.Tasks.ToList().Last(c => c.UserTaskID > 0).UserTaskID + 1;
                        for (int i = 0; i < Tags.Count; i++)
                        {
                            string CurrentTag = Tags[i];
                            Tags NewTag = new Tags();
                            NewTag.TagText = Tags[i];
                            NewTag.TaskID = NewTaskID;
                            DB.Tags.Add(NewTag);
                        }
                        for (int i = 0; i < Answers.Count; i++)
                        {
                            string CurrentAnswer = Answers[i];

                            Answers NewAnswer = new Answers();
                            NewAnswer.AnswerText = Answers[i];
                            NewAnswer.TaskID = NewTaskID;
                            DB.Answers.Add(NewAnswer);
                            DB.Entry(NewAnswer).State = System.Data.Entity.EntityState.Added;

                        }

                    }
                    else
                    {
                        DB.Tags.RemoveRange(DB.Tags.Where(c => c.TaskID == id));
                        DB.Answers.RemoveRange(DB.Answers.Where(c => c.TaskID == id));
                        for (int i = 0; i < Tags.Count; i++)
                        {
                            string CurrentTag = Tags[i];

                            Tags NewTag = new Tags();
                            NewTag.TagText = Tags[i];
                            NewTag.TaskID = (int)id;
                            DB.Tags.Add(NewTag);
                            DB.Entry(NewTag).State = System.Data.Entity.EntityState.Added;
                        }

                        for (int i = 0; i < Answers.Count; i++)
                        {
                            string CurrentAnswer = Answers[i];

                            Answers NewAnswer = new Answers();
                            NewAnswer.AnswerText = Answers[i];
                            NewAnswer.TaskID = (int)id;
                            DB.Answers.Add(NewAnswer);
                            DB.Entry(NewAnswer).State = System.Data.Entity.EntityState.Added;
                        }
                        DB.Tasks.First(c=>c.UserTaskID == id).TaskName = Name;
                        DB.Tasks.First(c => c.UserTaskID == id).TaskDifficulty = Difficulty;
                        DB.Tasks.First(c => c.UserTaskID == id).TaskCategory = Category;
                        DB.Tasks.First(c => c.UserTaskID == id).TaskText = HTML;                        
                    }
                    DB.SaveChanges();
                }
            }

            return RedirectToAction("Index", "Home");
        }
Ejemplo n.º 45
0
        private void button2_Click(object sender, EventArgs e)
        {
            String file = openFileDialog1.FileName;
            String text = richTextBox1.Text;
            String domainname = null;
            bool isGraphic = checkBox1.Checked;
            Domain domain = 0;
            Answers answers = new Answers();
            answers[1] = textBox1.Text;
            answers[2] = textBox2.Text;
            answers[3] = textBox3.Text;
            answers[4] = textBox4.Text;

            switch (comboBox1.SelectedIndex)
            {
                case 0: answers.CorrectAnswer = textBox1.Text;
                    break;
                case 1: answers.CorrectAnswer = textBox2.Text;
                    break;
                case 2: answers.CorrectAnswer = textBox3.Text;
                    break;
                case 3: answers.CorrectAnswer = textBox4.Text;
                    break;
                default:
                    answers.CorrectAnswer = textBox1.Text;
                    break;
            }

            foreach (Control c in this.Controls)
                if (c is RadioButton) if (((RadioButton)c).Checked == true) domainname = ((RadioButton)c).Text;

            switch (domainname)
            {
                case "hidro":
                    domain = Domain.Hidrografie;
                    break;
                case "rel":
                    domain = Domain.Relief;
                    break;
                case "res":
                    domain = Domain.Resurse;
                    break;
                case "admin":
                    domain = Domain.Administrativ;
                    break;
                default:
                    domain = Domain.None;
                    break;
            }

            Question question = new Question(0, text, domain, 0, answers);
            if (!String.IsNullOrEmpty(richTextBox1.Text) &&
                !String.IsNullOrEmpty(textBox1.Text) &&
                !String.IsNullOrEmpty(textBox2.Text) &&
                !String.IsNullOrEmpty(textBox3.Text) &&
                !String.IsNullOrEmpty(textBox4.Text))
            {
                if (isGraphic)
                    DatabaseAbstractionLayer.DAL.UploadQuestion(question, isGraphic, file);
                else DatabaseAbstractionLayer.DAL.UploadQuestion(question);
                MessageBox.Show("Intrebare adaugata!");
                this.Close();
            }
            else MessageBox.Show("Toate campurile trebuie completate!");
        }
Ejemplo n.º 46
0
        private List<Answers> GetAnswersFromTask(string RawVariants)
        {
            MatchCollection answers = Regex.Matches(RawVariants, @"'(?<aid>\d+)'.*?""(?<atext>.*?)""", RegexOptions.Singleline);

            List<Answers> AnswerList = new List<Answers>();

            foreach (Match item in answers)
            {
                Answers NewAnswer = new Answers();

                NewAnswer.AID = Convert.ToInt32(item.Groups["aid"].Value);
                NewAnswer.AnswerText = item.Groups["atext"].Value.Trim();

                AnswerList.Add(NewAnswer);
            }

            return AnswerList;
        }
Ejemplo n.º 47
0
        public static OneBasedArray<Question> GetQuestions()
        {
            OneBasedArray<Question> questionList = new OneBasedArray<Question>(30);
            int id = 0;
            int difficultyPercent = 0;
            bool isGraphic = false;
            string text = string.Empty;
            Domain domain = Domain.None;
            byte[] imageData;
            Image image = null;

            // Open connection
            if (OpenConnection() == true)
            {
                // Create command and assign the query and connection from the constructor
                try
                {
                        using (var command = new MySqlCommand("GetQuestions", connection) { CommandType = CommandType.StoredProcedure })
                        {
                            command.Parameters.AddWithValue("@user", PersistentData.user);
                            int j = 1;

                            MySqlDataReader myReader = command.ExecuteReader();
                            while (myReader.Read())
                            {
                                id = myReader.GetInt32(0);
                                text = myReader.GetString(1);
                                domain = myReader.GetDomain(2);
                                difficultyPercent = myReader.GetInt32(3);
                                isGraphic = myReader.GetBoolean(4);

                                if (isGraphic)
                                    imageData = (byte[])myReader[5];
                                else imageData = null;
                                image = Utils.Converters.ByteArrayToImage(imageData);
                                Answers answers = new Answers();
                                answers.CorrectAnswer = myReader.GetString(6);

                                int i = 1;
                                while (i <= PersistentData.MAX_ANSWERS)
                                {
                                    answers[i] = myReader.GetString(6 + i);
                                    i++;
                                }

                                if (!isGraphic)
                                    questionList[j] = new Question(id, text, domain, difficultyPercent, answers);
                                else
                                    questionList[j] = new GraphicQuestion(id, text, image, domain, difficultyPercent, answers);
                                j++;
                            }
                        }
                    }
                catch (MySqlException ex)
                {
                    Debug.ExitWithErrorMessage(ex.Message, ex.Number);
                }

                // Close connection
                CloseConnection();
            }
            else Debug.ExitWithErrorMessage("Connection failed to open using DAL method.");
            return questionList;
        }
        Task<StacManResponse<Answer>> IUserMethods.GetMyTopAnswers(string site, string access_token, IEnumerable<string> tags, string filter = null, int? page = null, int? pagesize = null, DateTime? fromdate = null, DateTime? todate = null, Answers.Sort? sort = null, DateTime? mindate = null, DateTime? maxdate = null, int? min = null, int? max = null, Order? order = null)
        {
            var filterObj = ValidateAndGetFilter(filter);

            ValidateString(site, "site");
            ValidateString(access_token, "access_token");
            ValidateEnumerable(tags, "tags");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder(String.Format("/me/tags/{0}/top-answers", String.Join(";", tags)), useHttps: true);

            ub.AddParameter("site", site);
            ub.AddParameter("access_token", access_token);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, filterObj, "/_users/tags/{tags}/top-answers");
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Creates new course and opens it.
        /// </summary>
        public static void CreateNew()
        {
            FFDebug.EnterMethod(Cattegory.Course, State.ToString());

            if ((State & CourseStates.Opened) > 0 && !Close())
            {
                return;
            }

            __FullPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(__FullPath);
            __Manifest = new ManifestType("New Course") { version = CourseUpgradeManager.LastVersion };
            __Manifest.ResolveTree(__Manifest);
            __Organization = __Manifest.organizations.Organizations[0];
            __Manifest.organizations.@default = __Organization.identifier;
            Answers = new Answers();
            Save();
            if (Open(__FullPath))
            {
                State = CourseStates.Opened;
            }

            FFDebug.LeaveMethod(Cattegory.Course, MethodBase.GetCurrentMethod());
        }
Ejemplo n.º 50
0
        Task<StacManResponse<Answer>> IUserMethods.GetMyAnswers(string site, string access_token, string filter, int? page, int? pagesize, DateTime? fromdate, DateTime? todate, Answers.Sort? sort, DateTime? mindate, DateTime? maxdate, int? min, int? max, Order? order)
        {
            ValidateString(site, "site");
            ValidateString(access_token, "access_token");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder(Version, "/me/answers", useHttps: true);

            ub.AddParameter("site", site);
            ub.AddParameter("access_token", access_token);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, HttpMethod.GET, "/_users/answers");
        }
Ejemplo n.º 51
0
        Task<StacManResponse<Answer>> IUserMethods.GetTopAnswers(string site, int id, IEnumerable<string> tags, string filter, int? page, int? pagesize, DateTime? fromdate, DateTime? todate, Answers.Sort? sort, DateTime? mindate, DateTime? maxdate, int? min, int? max, Order? order)
        {
            ValidateString(site, "site");
            ValidateEnumerable(tags, "tags");
            ValidatePaging(page, pagesize);
            ValidateSortMinMax(sort, mindate: mindate, maxdate: maxdate, min: min, max: max);

            var ub = new ApiUrlBuilder(Version, String.Format("/users/{0}/tags/{1}/top-answers", id, String.Join(";", tags.Select(HttpUtility.UrlEncode))), useHttps: false);

            ub.AddParameter("site", site);
            ub.AddParameter("filter", filter);
            ub.AddParameter("page", page);
            ub.AddParameter("pagesize", pagesize);
            ub.AddParameter("fromdate", fromdate);
            ub.AddParameter("todate", todate);
            ub.AddParameter("sort", sort);
            ub.AddParameter("min", mindate);
            ub.AddParameter("max", maxdate);
            ub.AddParameter("min", min);
            ub.AddParameter("max", max);
            ub.AddParameter("order", order);

            return CreateApiTask<Answer>(ub, HttpMethod.GET, "/_users/tags/{tags}/top-answers");
        }
Ejemplo n.º 52
0
 public GraphicQuestion(int id = 0, string text = null, Image image = null, Domain domain = 0, int difficulty = 0, Answers answers = null)
     : base(id,text,domain,difficulty,answers)
 {
     this.image = image;
 }
Ejemplo n.º 53
0
    protected void ansGrid_UpdateCommand(object source, DataGridCommandEventArgs e)
    {
        using (Answers answers = new Answers())
        {
            string fileName = ViewState["editf"].ToString();
            string title = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
            string description = ((TextBox)e.Item.Cells[4].Controls[0]).Text;

            answers.UpdateAnswerFile(fileName, title, description);
        }
        ansGrid.EditItemIndex = -1;
        BindData(null);
    }