def add_vote(option, poll_participant, db_options, multiple_options): """ Add a vote. :param option: the voted option. :param poll_participant: the id of the participant whose vote is to add. :param db_options: the existing options in the db. :param multiple_options: if multiple options are allowed in this poll. """ new_vote = False # If it is a valid option if 0 < option <= len(db_options): if db_options[option - 1].locked: return False # Check the type of participant # int means discord used # string means external participant if type(poll_participant) == str: discord_participant_id = None participant_name = poll_participant vote = config.session.query(models.Vote) \ .filter(models.Vote.option_id == db_options[option - 1].id) \ .filter(models.Vote.participant_name == participant_name).first() else: discord_participant_id = poll_participant participant_name = None vote = config.session.query(models.Vote) \ .filter(models.Vote.option_id == db_options[option - 1].id) \ .filter(models.Vote.discord_participant_id == discord_participant_id).first() # Vote for an option if multiple options are allowed and he is yet to vote this option if multiple_options and vote is None: # Add the new vote vote = models.Vote(db_options[option - 1].id, discord_participant_id, participant_name) config.session.add(vote) new_vote = True # If multiple options are not allowed elif not multiple_options: # The participant didn't vote this option if vote is None: remove_prev_vote(db_options, poll_participant) # Add the new vote vote = models.Vote(db_options[option - 1].id, discord_participant_id, participant_name) config.session.add(vote) new_vote = True return new_vote
def set_encrypted_vote(self, votes_json_string): # Check the proof on the vote pk = self.election.get_pk() election_obj = self.election.toElection() vote_dict = utils.from_json(votes_json_string) enc_vote = electionalgs.EncryptedVote.fromJSONDict(vote_dict, pk) # verify # turned off for now (Ben- 2008-11-28) #if not enc_vote.verify(election_obj): # raise Exception("Vote does not verify") # store this current vote in the voter structure self.vote = votes_json_string self.vote_hash = self.compute_vote_hash() self.cast_id = str(datetime.datetime.utcnow()) + str(self.voter_id) # store the vote v = models.Vote() v.cast_at = datetime.datetime.utcnow() v.vote = votes_json_string v.vote_hash = self.vote_hash v.voter = self v.insert() self.save()
def vove(): form = VoteForm(request.form) if request.method == 'POST' and form.validate(): if voted(form.suggestionid.data,str(session['uuid'])): vote = models.Vote(form.suggestionid.data,str(session['uuid']),form.votestatus.data) vote.status = form.votestatus.data models.db.session.add(vote) models.db.session.commit() flash('Thanks, suggestion down-voted') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) vote = models.Vote(form.suggestionid.data,str(session['uuid']),form.votestatus.data) models.db.session.add(vote) models.db.session.commit() flash('Thanks, suggestion up-voted') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data))
def djpandora_vote(request): """ Receives a vote, returns JSON status Creates a vote object and applies it to a song. If it's a duplicate we check to see if our value reverses our vote, and applies that to the existing vote object. This prevents a user from repeatedly voting on a song. """ song = get_object_or_404(models.Song, id=request.GET.get('song_id')) s = utils.get_pandora_rpc_conn() if request.GET.get('vote') == 'like': vote = 1 s.play_sound('upvote') else: vote = -1 s.play_sound('downvote') instance = models.Vote(user=request.user) post = { u'station': song.station_id, u'value': vote, u'song': song.id } vote_obj, created = models.Vote.objects.get_or_create(user=request.user, station=song.station, song=song ) vote_obj.value = vote vote_obj.save() form = forms.Vote(post, instance=instance) json_status = {'status': 'success'} return HttpResponse(json.dumps(json_status), mimetype='application/json' )
def create_vote_for_user(db: Session, vote: schemas.VoteCreate, user_id: int): db_vote = models.Vote(**vote.dict(), owner_id=user_id) db.add(db_vote) db.commit() db.refresh(db_vote) return db_vote """[اضافه کردن رای معلم به دیتابیس]
def create_vote(db: Session, vote: schemas.VoteCreate): db_vote = models.Vote(**vote.dict()) db_vote.item = db.query( models.Item).filter(models.Item.id == vote.item_id).first() db.add(db_vote) db.commit() db.refresh(db_vote) return db_vote
def tx_vote(tx, cursor): payload = json.loads(tx.payload) voter = models.Account(tx.chain_id, tx.sender, cursor) draft = models.Draft(tx.chain_id, payload['draft_id'], None, cursor) vote = models.Vote(tx.chain_id, draft.draft_id, voter.address, cursor) vote.approve = payload['approve'] vote.save(cursor)
def db_start(): create_engine('sqlite:///tmp/test.db', convert_unicode=True) db.create_all() db.session.commit() user = models.User( password=bcrypt.generate_password_hash('password').decode('utf-8'), email='*****@*****.**', admin=True) user2 = models.User( password=bcrypt.generate_password_hash('password').decode('utf-8'), email='*****@*****.**', admin=True) db.session.add(user) db.session.add(user2) db.session.commit() recipe = models.Recipe(title="Private recipe user1", ingredients="Some ingredients", time_needed=15, steps="some steps", is_public=False, user_id=user.id, average_score=None) recipe2 = models.Recipe(title="Public recipe user1", ingredients="Some ingredients", time_needed=15, steps="some steps", is_public=True, user_id=user.id, average_score=None) recipe3 = models.Recipe(title="Private recipe user2", ingredients="Some ingredients", time_needed=15, steps="some steps", is_public=False, user_id=user2.id, average_score=None) recipe4 = models.Recipe(title="Public recipe user2", ingredients="Some ingredients", time_needed=15, steps="some steps", is_public=True, user_id=user2.id, average_score=None) db.session.add(recipe) db.session.add(recipe2) db.session.add(recipe3) db.session.add(recipe4) db.session.commit() vote1 = models.Vote(value=1, user_id=user.id, recipe_id=recipe.id) db.session.add(vote1) db.session.commit()
def fake_data(): for collection in ['user', 'session', 'vote']: clear_collection(collection) for user_dict in load_users(): models.User(user_dict).save() for session_dict in load_sessions(): models.Session(session_dict).save() for vote_dict in load_votes(): models.Vote(vote_dict).save()
def vote_action(): from flask import request session = request.args.get('session') user = request.args.get('user') error = json.dumps({ "success": False, "text": "Please send a session ID and a user ID." }) if not session or not user: return error u = utils.connect('user').find_one({"_id": user}) if not u: return error s = utils.connect('session').find_one({"_id": session}) if not s: return error votes = [ vote for vote in utils.connect('vote').find({ "user": user, "session": session }) ] # Create a new vote. if len(votes) == 0: models.Vote(user=u['_id'], session=s['_id']).save() sesh = models.Session(s) sesh.update_records() tally() return json.dumps({"success": True, "action": "create vote"}) # Delete existing votes. if len(votes) > 0: utils.connect('vote').remove({"user": user, "session": session}) sesh = models.Session(s) sesh.update_records() tally() return json.dumps({"success": True, "action": "delete vote"}) return error
def post(self): group_id = self.request.get('group_id') topic_id = self.request.get('topic_id') proposal_id = self.request.get('proposal_id') proposal = models.Proposal.get_from_id(long(group_id), long(topic_id), long(proposal_id)) success = True if proposal.topic.get().deadline != None: currentdatetime = datetime.datetime.now() proposal.topic.get( ).expired = proposal.topic.get().deadline < currentdatetime if proposal.topic.get().expired: success = False if success: vote = models.Vote(proposal=proposal.key, parent=proposal.key, creator=self.beevote_user.key) vote.put() time.sleep(0.25) votes = proposal.get_votes() vote_number = len(votes) values = {'success': success, 'vote_number': vote_number} self.response.out.write(json.dumps(values))
async def vote_poll_command(command, db_channel): """ models.Vote a list of options in a poll. :param command: the command used. :param db_channel: the corresponding channel entry in the DB. """ # If the channel does not exist in the DB if db_channel is None: msg = 'There\'s no poll in this channel for you to vote!' await auxiliary.send_temp_message(msg, command.channel) return # Get the list of parameters in the message params = auxiliary.parse_command_parameters(command.content) # Check for external voters if params.__contains__('-e') and len(params) == 5: author_id = params[4] if author_id[0] != '"': author_id = '"%s"' % author_id else: # If the command has an invalid number of parameters if len(params) != 3: msg = 'Invalid parameters in command: **%s**' % command.content await auxiliary.send_temp_message(msg, command.channel) return author_id = command.author.id poll_key = params[1] options = params[2] # Select the current poll poll = config.session.query( models.Poll).filter(models.Poll.poll_key == poll_key).first() # If no poll was found with that id if poll is None: msg = 'There\'s no poll with that id for you to vote.\nYour command: **%s**' % command.content await auxiliary.send_temp_message(msg, command.channel) return # Get all options available in the poll db_options = config.session.query(models.Option).filter(models.Option.poll_id == poll.id) \ .order_by(models.Option.position).all() # If it is an vote for an external user and it is not allowed if author_id is None and not poll.allow_external: msg = 'models.Poll *%s* does not allow for external votes.\n' \ 'If you need this option, ask the poll author to edit it.' % poll_key await auxiliary.send_temp_message(msg, command.channel) return poll_edited = False # Option is a list of numbers try: # Verify if the options are numbers selected_options = [] for o in options.split(','): selected_options.append(int(o)) for option in selected_options: poll_edited |= auxiliary.add_vote(option, author_id, db_options, poll.multiple_options) # Option is not a list of numbers except ValueError: if poll.new_options: if not poll.multiple_options: auxiliary.remove_prev_vote(db_options, author_id) if options[0] == '"' and options[-1] == '"': # Remove quotation marks options = options.replace('"', '') # Add the new option to the poll options = models.Option(poll.id, len(db_options) + 1, options) db_options.append(options) config.session.add(options) config.session.flush() # Check the type of participant # int means discord used # string means external participant if type(author_id) == str: discord_participant_id = None participant_name = author_id else: discord_participant_id = author_id participant_name = None vote = models.Vote(options.id, discord_participant_id, participant_name) config.session.add(vote) poll_edited = True else: msg = 'models.Poll *%s* does not allow for new votes.\n' \ 'If you need this option, ask the poll author to edit it.' % poll_key await auxiliary.send_temp_message(msg, command.channel) return # Edit the message if poll_edited: c = config.client.get_channel(db_channel.discord_id) try: m = await c.fetch_message(poll.discord_message_id) await m.edit(content=auxiliary.create_message(poll, db_options)) except discord.errors.NotFound: config.session.delete(poll) config.session.commit() print('%s voted in %s -> %s!' % (author_id, poll.poll_key, command.content))
def load_data(wipe=False, section=None, Max=None): if not settings.running_on_test_server(): return "Forbidden" result_strings = [] if geo.geoCodeAddress("1 Crouch Hill, London"): # if we can geocode, we will - no fake fakeGeoCoder = None else: # if we cant geocode, use the fake one fakeGeoCoder = fakeGeoCode if section == "addresses": return add_addresses_to_db() else: if wipe: # wipe_table("User") wipe_table("Category") wipe_table("Item") wipe_table("Vote") print "wiped" if not section or section == 'user': for idx, usr in enumerate(Users): if Max: if idx >= Max: break user_name = usr[0] this_user = User.get_by_auth_id(user_name) if not this_user: email = usr[1] name = usr[2] last_name = usr[3] password = usr[4] unique_properties = ['email_address'] this_user = User.create_user(user_name, unique_properties, email_address=email, name=name, password_raw=password, last_name=last_name, verified=False) if not this_user[0]: # user_data is a tuple result_strings.append("ERROR - User: "******"User: "******"User exists: " + usr[0]) a_sample_user = User.get_by_auth_id( Users[0][0]) # used for the owner of the records print "users ok" if not section or section == "category": for idx, cat in enumerate(Categories): if Max: if idx >= Max: break if models.Category.get_by_id(cat): result_strings.append("Category exists: " + cat) else: new_cat = models.Category(id=cat) new_cat.title = cat new_cat.put() result_strings.append("Created: " + cat) print "category ok" if not section or section == "item": home = geo.LatLng(lat=51.57, lng=-0.13) for idx, item in enumerate(items_data_list): if Max: if idx >= Max: break it = models.Item.query(models.Item.place_name == item[0]).get() if it: result_strings.append("Item exists: " + item[0]) it.category = models.Category.get_by_id(item[2]).key it.save() else: new_it = models.Item() new_it.category = models.Category.get_by_id(item[2]).key new_it.place_name = item[0] lat_long = fakeGeoCode( ) if fakeGeoCoder else geo.geoCodeAddress(item[1]) new_it.lat = lat_long['lat'] new_it.lng = lat_long['lng'] new_it.address = item[1] new_it.owner = a_sample_user.key.id() # new_it.descr = "blah" new_it.geo_hash = geohash.encode(new_it.lat, new_it.lng) img = models.DBImage() detail = geo.getPlaceDetailFromGoogle(new_it) remoteURL = detail['photo'] if remoteURL: main_url = remoteURL % 250 data = urllib2.urlopen(main_url) img.picture = db.Blob(data.read()) img.remoteURL = None thumb_url = remoteURL % 65 thumb_data = urllib2.urlopen(thumb_url) img.thumb = db.Blob(thumb_data.read()) img.put() new_it.photo = img.key new_it.telephone = detail['telephone'] new_it.put() result_strings.append('Item: ' + item[0]) print "items" # votes items = models.Item.query() i = 0 for idx, vote_item in enumerate(items): if Max: if idx >= Max: break vote = models.Vote() vote_score = randint(0, 5) if vote_score == 0: vote.stars = 0 vote.untried = True else: vote.stars = vote_score vote.untried = False vote.comment = "blah v" + str(i) vote.voter = a_sample_user.key.integer_id() vote.item = vote_item.key vote.cuisine = vote_item.category vote.put() i += 1 result_strings.append("Votes") print "votes" if not section or section == 'friends': for idx, pair in enumerate(FriendsList): if Max: if idx >= Max: break left = User.get_by_auth_id(pair[0]) right = User.get_by_auth_id(pair[1]) left_prof = left.profile() models.Friends.addFriends(left.get_id(), right.get_id()) result_strings.append("Friends %s - %s" % (pair[0], pair[1])) print "friends" return result_strings