def dummy(count): words = [ 'why','do','federer','nadal','elena','deepak','rudra','go','live','love','startup','india', 'near', 'far', 'about','give', 'take', 'bird', 'lion', 'window','door', 'try', 'yoda', 'prestige', 'star', 'sun', 'father', 'mother' ] ans = [ 'maybe', 'yes', 'no', 'never', 'do', 'lie', 'cheat', 'steal', 'run', 'whatever', 'see', 'eat', 'why', 'not' ] topics = Topic.objects.all() for i in xrange(count): q = Question() q.question_text = ' '.join(random.sample(words, random.randint(8,15))) q.topic = topics[random.randint(0,len(topics)-1)] q.user = random.sample(User.objects.all(), 1)[0] q.save() choice_count = random.randint(2,6) for j in xrange(choice_count): ch = Choice() ch.choice_text = ' '.join(random.sample(ans, random.randint(2,4))) ch.question = q ch.save()
def show_post_detail(post_id): """show the details of the post (post description, choices available), users' votes on it and comments; User can also vote on the questions""" post = Post.get_post_by_id(post_id) choices = Choice.get_choices_by_post_id(post_id) viewer_id = session.get('loggedin', None) if_voted = None if viewer_id: if_voted = post.check_choice_on_post_by_user_id(viewer_id) vote_dict, total_votes, chart_dict = post.count_votes() bar_chart_gender = post.bar_chart_gender() geochart = post.count_votes_by_location() bar_chart_age = post.count_votes_by_age() comments = Comment.get_comments_by_post_id(post_id) tag_names = [tag.tag_name for tag in Tag.get_tags_by_post_id(post_id)] post_ids = session.get("post_ids", None) state = post.state # this gives a choice_id or Null, for displaying the decision the author has made decision = None if state: decision = Choice.get_choice_by_id(state) if if_voted: return render_template('post_details.html', post=post, choices=choices, vote_dict=vote_dict, comments=comments, total_votes=total_votes, tag_names=tag_names, post_ids=post_ids, chart_dict=chart_dict, decision=decision, bar_chart_gender=bar_chart_gender, geochart=geochart, bar_chart_age=bar_chart_age) else: return render_template('post_details.html', post=post, choices=choices, comments=comments, post_ids=post_ids, tag_names=tag_names, total_votes=total_votes)
def post(self, request): data = request.POST question_id = data.get('question') try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist as e: return HttpResponseNotFound(e) return_data = { 'question': question_id, 'question_type': question.type, 'question_text': question.question_text } ch = [] if question: for possible_answer in data.getlist('possible_answer'): if possible_answer: choice = Choice(question=question, value=possible_answer) choice.save() ch.append({ 'value': choice.value, 'id': choice.id, }) return_data['choices'] = ch else: return JsonResponse({'error': 'error'}, safe=False, status=400) if request.is_ajax(): return JsonResponse(return_data, safe=False) else: return HttpResponse('')
def create_a_poll(request,survey_id): # create a poll in a survey # get questions from input # redirect to craetPollPage logging.debug(request.POST) question = request.POST['Question0'] choice_list = request.POST.getlist('Field1') s = get_object_or_404(Survey,pk = survey_id) # check if user correct if not s.author == request.user.username: return p = Poll(survey=s, question = question) p.save() # get choice from form input logging.debug(choice_list) for c in choice_list: if c: logging.debug(c) choice = Choice(poll= p, choice = c, votes=0) choice.save() return HttpResponseRedirect('createPollPage')
def choice_add(request): question = Question.objects.get(id=request.session['current_question']) newChoice = Choice() newChoice.choice_text = request.POST["choice_text"] question.choice_set.add(newChoice) newChoice.save() question.save() return redirect('admin-choice-add-view')
def pregame(): """Let the user choose one out of two random categories.""" # "GET" method if request.method == "GET": # if table is empty, insert values if Categories.query.get(1) is None: # generate two different random categories firstcat = randomcategory() secondcat = randomcategory() while firstcat == secondcat: secondcat = randomcategory() # update database with new categories randomcats = Categories(firstcat, secondcat) db.session.add(randomcats) db.session.commit() # update the table otherwise else: # generate two different random categories Categories.query.get(1).firstcat = randomcategory() Categories.query.get(1).secondcat = randomcategory() while Categories.query.get(1).firstcat == Categories.query.get(1).secondcat: Categories.query.get(1).secondcat = randomcategory() db.session.commit() # query for categories cats = Categories.query.get(1) return render_template("pregame.html", cats=cats) # "POST" method else: # if the first category was chosen if request.form.get("cat") == "1": if Choice.query.get(1) is None: keuze = Choice(Categories.query.get(1).firstcat) db.session.add(keuze) db.session.commit() Choice.query.get(1).choice = Categories.query.get(1).firstcat db.session.commit() return redirect(url_for("question")) # if the second category was chosen if request.form.get("cat") == "2": if Choice.query.get(1) is None: keuze = Choice(Categories.query.get(1).secondcat) db.session.add(keuze) db.session.commit() Choice.query.get(1).choice = Categories.query.get(1).secondcat db.session.commit() return redirect(url_for("question"))
def __row_to_contest(self, row): contest = Contest() contest.title = row[self.__csv_format['QUESTION_COL_INDEX']] for index in self.__csv_format['OPTIONS_COL_INDEXES']: option = Choice() option.title = row[index] contest.options.append(option) if index == self.__csv_format['RESPONSE_COL_INDEX']: contest.response_index = len(contest.options) - 1 if contest.response_index is None: raise Exception('Response index must be in the options list') return contest
def add(request): if not request.user.id: return redirect('/accounts/login?flag=1') if request.POST: poll = Poll(question=request.POST.get('question')) poll.save() for ch in request.POST.getlist('choice'): choice = Choice(poll=poll, choice=ch) choice.save() poll_list = Poll.objects.all() return render_to_response('index.html',dict(poll_list=poll_list, msg_success='Successfully submitted poll and choices')) else: return render(request,'add.html',{})
def create_choice(data: dict) -> str: if not 'description' in data: return Response.wrong_format( json.dumps({'message': 'description missing'})) if not 'election_round_id' in data: return Response.wrong_format( json.dumps({'message': 'electionid missing'})) if 'picture' in data: if data['picture'].endswith('=='): picture = data['picture'] else: return Response.wrong_format({"message": "picture is not Base64"}) else: picture = '' choice = Choice(description=data['description'], counter=0, picture=picture, election_round_id=data['election_round_id']) session.add(choice) try: session.commit() except: return Response.database_error() return Response.ok( json.dumps({ 'id': choice.id, 'description': choice.description }))
async def on_post(self, req, resp): """ postの場合は受け取ったデータをQuestionテーブルに追加する。 """ data = await req.media() error_messages = list() """ エラー処理 """ if data.get('question_text') is None: error_messages.append('質問内容が入力されていません。') if data.get('date') is None or data.get('time') is None: error_messages.append('公開日時が入力されていません。') # 配列として受け取ったフォームはget_list()で取得する choices = data.get_list('choices[]') votes = data.get_list('votes[]') if len(choices) == 0 or len(votes) == 0 or len(choices) != len(votes): error_messages.append('選択肢内容に入力されていない項目があります。') if len(choices) < 1: error_messages.append('選択肢は2つ以上必要です。') # 何かしらエラーがあればリダイレクト if len(error_messages) != 0: resp.content = api.template('add_question.html', error_messages=error_messages, date=datetime.now()) return """ テーブルにQuestionを追加 """ # 公開日時をセパレートしてint型のリストに変換 date = [int(d) for d in data.get('date').split('-')] time = [int(t) for t in data.get('time').split(':')] # question作成 question = Question( data.get('question_text'), datetime(date[0], date[1], date[2], time[0], time[1], time[2])) # question追加 db.session.add(question) db.session.commit() """ テーブルにChoicesを追加 """ # まず外部キーとなるQuestion.idを取得 foreign_key = question.id q_choices = list() for i, choice in enumerate(choices): # choice作成 q_choices.append(Choice(foreign_key, choice, int(votes[i]))) # choice追加 db.session.add_all(q_choices) db.session.commit() db.session.close() api.redirect(resp, '/admin_top')
async def process_start_command(message: types.Message): user_id = message.from_user.id mention = message.from_user.get_mention() try: reg = User(id=user_id, name=mention, presence=False) choice_init = Choice(id=user_id, Name=mention) await reg.save() await choice_init.save() finally: return await message.reply(MESSAGES["start_message"])
def parse_choice(self, metadata, stack): from .ContextParser import ContextParser match = regex_choice.match(metadata.line) if match: description = match["choice"] choice = Choice(description, metadata) self.choice = choice self.menu.add_choice(choice) parser = ContextParser(self, metadata) stack.push(parser) return True return False
def update_decision(post_id): post = Post.get_post_by_id(post_id) choice_id = request.form.get("choice_id") print choice_id, "this is choice_id" print type(choice_id), "this is the data type" post.update_decision(int(choice_id)) if choice_id != "0": choice = Choice.get_choice_by_id(choice_id) decision_text = "The user has decided to go with: " + choice.choice_text decision_file = choice.file_name else: decision_text = "The author has made the decision but he/she likes to keep it secret" decision_file = "" return jsonify(decision_text=decision_text, decision_file=decision_file)
def all(self): if request.method == 'GET': surveys = Survey.all() return jsonify([s.to_dict() for s in surveys]) elif request.method == 'POST': data = request.get_json() survey = Survey(name = data['name']) questions = [] for q in data['questions']: question = Question(text = q['text']) question.choices = [Choice(text = c) for c in q['choices']] questions.append(question) survey.questions = questions survey.save() return jsonify(survey.to_dict()), 201
def create_a_poll(request, survey_id): # create a poll in a survey # get questions from input # redirect to craetPollPage logging.debug(request.POST) question = request.POST['Question0'] choice_list = request.POST.getlist('Field1') s = get_object_or_404(Survey, pk=survey_id) # check if user correct if not s.author == request.user.username: return p = Poll(survey=s, question=question) p.save() # get choice from form input logging.debug(choice_list) for c in choice_list: if c: logging.debug(c) choice = Choice(poll=p, choice=c, votes=0) choice.save() return HttpResponseRedirect('createPollPage')
def post(self, id): user = users.get_current_user() if not user: #don't want someone who is not authenticated to be able to vote self.redirect(users.create_login_url(self.request.uri)) return issue = Issue.get_by_id(int(id)) #vote = issue.vote_for_member() new_choice = Choice.get_by_id(int(self.request.get('choice'))) was_updated = issue.register_vote(new_choice) if was_updated: self.redirect('/?success=updated') else: self.redirect('/?success=vote')
def post(self,id): user = users.get_current_user() if not user: #don't want someone who is not authenticated to be able to vote self.redirect(users.create_login_url(self.request.uri)) return issue = Issue.get_by_id(int(id)) #vote = issue.vote_for_member() new_choice = Choice.get_by_id(int(self.request.get('choice'))) was_updated = issue.register_vote(new_choice) if was_updated: self.redirect('/?success=updated') else: self.redirect('/?success=vote')
def api_poll_create(request): api_result = {"api": "poll_create", "status": "success"} try: token = request.POST["token"] user = get_user_from_token(token) if not user: api_result["status"] = "failure" api_result["error"] = "user not found" else: question = request.POST["question"] choice_text = request.POST["choices"] group_id = request.POST["group_id"] if group_id == "0": group = None else: group = Group.objects.get(pk=group_id) choices = set(choice_text.split("##")) if "" in choices: choices.remove("") try: topic = Topic.objects.get(name=request.POST["topic"]) except: topic = Topic.objects.get(name="others") if len(question) == 0 or len(choices) < 2: raise ValueError("invalid poll arguments") q = Question() q.question_text = question.strip() q.user = user q.topic_id = topic.id q.group = group # q.pub_date = datetime.now(pytz.timezone("Asia/Calcutta")) q.save() for choice in choices: c = Choice() c.choice_text = choice c.question = q c.votes = 0 c.save() print c.id print q.id api_result["question_id"] = q.id except Exception as e: api_result["status"] = "failure" api_result["error"] = e.message return JsonResponse(api_result)
def post(self,urlcode): user = users.get_current_user() if user: logout_url = users.create_logout_url('/') else: self.redirect(users.create_login_url(self.request.uri)) issue = Issue.get_issue_by_urlcode(urlcode) #vote = issue.vote_for_member() new_choice = Choice.get_by_id(int(self.request.get('choice'))) was_updated = issue.register_vote(new_choice) if was_updated: self.redirect('/?success=updated') else: self.redirect('/?success=vote')
def post(self,urlcode): user = users.get_current_user() if user: logout_url = users.create_logout_url('/') else: self.redirect(users.create_login_url(self.request.uri)) issue = Issue.get_issue_by_urlcode(urlcode) #vote = issue.vote_for_member() new_choice = Choice.get_by_id(int(self.request.get('choice'))) was_updated = issue.register_vote(new_choice) self.response.out.write(template.render('templates/issue.html', locals())) if was_updated: self.redirect('/redirect/%s?success=updated' % issue.urlcode) else: self.redirect('/redirect/%s?success=voted' % issue.urlcode)
def create(request): topics = Topic.objects.all() context = {} context["topics"] = topics if request.method == "POST": print "inside" print request.POST try: question = request.POST["question"] print "question", question choices = set(request.POST["choices"].split("##")) if "" in choices: choices.remove("") print "choices", choices topic_id = request.POST["topic_id"] print "topic_id", topic_id if len(question) == 0 or len(choices) < 2: raise ValueError("invalid poll arguments") q = Question() q.question_text = question.strip() q.user = request.user q.topic_id = topic_id # q.pub_date = datetime.now(pytz.timezone("Asia/Calcutta")) q.save() for choice in choices: c = Choice() c.choice_text = choice c.question = q c.votes = 0 c.save() print c.id print q.id data = {} data["question_id"] = q.id return JsonResponse(data) except Exception as e: print e.errno print e.strerror context["error"] = "Please enter valid question and at least two choices" return render(request, "polls/v1_create.html", context) else: return render(request, "polls/v1_create.html", context)
async def on_post(self, req, resp): """ postの場合は受け取ったデータをQuestionテーブルに追加する。 """ data = await req.media() error_messages = list() # もし何も入力されていない場合 if data.get('choice_text') is None: error_messages.append('選択肢が入力されていません。') questions = db.session.query(Question.id, Question.question_text) resp.content = api.template('add_choice.html', error_messages=error_messages, questions=questions) return # テーブルに追加 choice = Choice(data.get('question'), data.get('choice_text')) db.session.add(choice) db.session.commit() db.session.close() api.redirect(resp, '/admin_top')
from create_db import engine from models import Pizza, Choice, Base import json import argparse session = sessionmaker() session.configure(bind=engine) s = session() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("filename") args = parser.parse_args() Base.metadata.drop_all(engine) Base.metadata.create_all(engine) with open(args.filename, "r") as file: catalog = json.load(file) for pizza in catalog: new_pizza = Pizza(title=pizza['title'], description=pizza['description']) for choice in pizza['choices']: new_choice = Choice(title=choice['title'], price=int(choice['price'])) new_pizza.choices.append(new_choice) s.add(new_pizza) s.commit()
def test_contains_verylong_text_with_normal_size_text(self): choice = Choice(choice_text = 'Tarantula') self.assertFalse(choice.contains_verylong_text())
async def index(request): ch = Choice(name="linxiao", status=JobStatus.Leave) await ch.save() return json({"message": "前后端可选项同步测试。"})
def test_contains_verylong_text_with_big_size_text(self): text_str = "London" choice = Choice(choice_text = "{:201}".format(text_str)) self.assertTrue(choice.contains_verylong_text())
import json from app import db from models import Pizza, Choice from db.catalog import catalog choice_id = 1 for pizza_id, pizza_data in enumerate(catalog, 1): pizza = Pizza( id=pizza_id, title=pizza_data['title'], description=pizza_data['description']) print(pizza_id, pizza) db.session.add(pizza) for choice_data in pizza_data['choices']: choice_id += 1 choice = Choice( id=choice_id, title=choice_data['title'], price=choice_data['price'], pizza_id=pizza_id) print(choice_id, choice) db.session.add(choice) db.session.commit()
from app import db from models import Pizza, Choice def load_catalog(filename): with open(filename) as file_handler: return json.loads(file_handler.read()) if __name__ == '__main__': catalog_filename = sys.argv[1] if len(sys.argv) > 1 else 'catalog.json' catalog = list() for entry in load_catalog(catalog_filename): pizza = Pizza(title=entry['title'], description=entry['description']) for choice in entry['choices']: pizza.choices.append( Choice(title=choice['title'], price=choice['price'])) catalog.append(pizza) db.session.add_all(catalog) db.session.commit()
def test_contains_nonempty_text_with_valid_text(self): choice = Choice(choice_text = 'San Francisco 49ers') self.assertTrue(choice.contains_nonempty_text())
u = User() u.displayname = "Testkonto 1" u.email = "*****@*****.**" u.password = "******" u.save() p1 = Poll() p1.name = "Testpoll 1" p1.number = "+46766862842" p1.allow_duplicate_answers = True p1.allow_multiple_choices = True p1.owner = u p1.save() c1 = Choice() c1.poll = p1 c1.name = "01" c1.description = "Bidrag nr. 1 - Bä bä vita lamm" c1.save() c2 = Choice() c2.poll = p1 c2.name = "02" c2.description = "Bidrag nr. 2 - Blinka lilla stjärna" c2.save() c3 = Choice() c3.poll = p1 c3.name = "03" c3.description = "Bidrag nr. 3 - Björnen sover"
def dummydata(): ## Person p1 = Person() p1.name = "Anna" p1.password = "******" p1.is_present = True p1.role = 0 p2 = Person() p2.name = "Bob" p2.password = "******" p2.is_present = False p2.role = 1 ## Elec-Rounds elec_round = ElectionRound() elec_round.title = "Braucht Ihr Pause?" elec_round.running = "running" elec_round.max_choices_per_person = 1 ## Choices ch1 = Choice() ch1.picture = "beer.png" ch1.description = "Ja!" ch1.counter = 4 #ch2.elec_round = elec_round ch2 = Choice() ch2.picture = "working.jpg" ch2.description = "Ne, passt..." ch2.counter = 2 ch2.election_round = elec_round # RELATIONSHIP (pls work) # The example Choice belongs to the first Election Round ch1.election_round = elec_round # Anna and Bob both Voted in the first Election Round p1.voted_in_election_round.append(elec_round) p2.voted_in_election_round.append(elec_round) # Anna has Bobs Vote p1.received_proxy_vote.append(p2) session.add(p1) session.add(p2) session.add(elec_round) session.add(ch1) session.add(ch2) session.commit()
p1.role = 0 p2 = Person() p2.name = "Bob" p2.password = "******" p2.is_present = False p2.role = 1 ## Elec-Rounds elec_round = ElectionRound() elec_round.title = "Braucht Ihr Pause?" elec_round.running = "running" elec_round.max_choices_per_person = 1 ## Choices ch1 = Choice() ch1.picture = "beer.png" ch1.description = "Ja!" ch1.counter = 4 #ch2.elec_round = elec_round ch2 = Choice() ch2.picture = "working.jpg" ch2.description = "Ne, passt..." ch2.counter = 2 ch2.election_round = elec_round # RELATIONSHIP (pls work) # The example Choice belongs to the first Election Round ch1.election_round = elec_round
def create_choice(db:Session, qid: int, choice: schema.ChoiceCreate): obj = Choice(**choice.dict(), question_id=qid) db.add(obj) db.commit() return obj
def test_contains_nonempty_text_with_empty_text(self): choice = Choice(choice_text = '') self.assertFalse(choice.contains_nonempty_text())