示例#1
0
def tally():
    votes = Vote()
    data = votes.tally()
    response = app.response_class(response=json.dumps(data),
                                  status=200,
                                  mimetype='application/json')
    return response
示例#2
0
 def __init__(self):
     Vote.__init__(self)
     self.statue = Statue()
     self.player_map = {}
     self.role_map = {}
     self.faction_map = {}
     self.roles = []
     self.night = True
     self.day = 0
     self.days = [None]
     self.nights = [None]
     self.duels = 2
     self.searches = 2
     self.bandit_night = 3
     self.bandit_morning = True
     self.rioters = set()
     self.new_night()
     self.stats = {
         "Miasto": 0,
         "Bandyci": 0,
         "Janosik": 0,
         "Lucky_Luke": 0,
         "Lusterko": 0,
         "Ufoki": 0,
         "Indianie": 0,
         "Inkwizycja": 0,
         "Bogowie": 0,
         "Murzyni": 0
     }
示例#3
0
    def get(self):
        cookie = self.request.get('cookie')

        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'

        if not cookie:
            error = json_error('vote', 'failure', 'cookie')
            self.response.write(json.dumps(error))

        else:
            id = self.request.get('id')
        
            if not id:
                error = json_error('vote', 'failure', 'no id')
                self.response.write(json.dumps(error))
   
            else:
                session = Session.query(Session.cookie == cookie).get()

                if not session:
                    error = json_error('vote', 'failure', 'session')
                    self.response.write(error)
                else:
                    key = ndb.Key(urlsafe=id)
                    submission = key.get()

                    if not submission:
                        error = json_error('vote', 'failure', 'no  submission')
                        self.response.write(error)
                    else:
                        value = self.request.get('value')
                        if not value:
                            error = json_error('vote', 'failure', 'value')
                            self.response.write(error)
                        else:
                            value = int(value)
                            if value < -1 or value > 1:
                                error = json_error('vote', 'failure', 'value')
                                self.response.write(error)
                            else:
                                last_vote = Vote.query(ndb.AND(Vote.user == session.user, Vote.sub_id == id)).get()
                                if not last_vote:
                                    vote_val = 0     
                                else:
                                    vote_val = last_vote.value
                                    last_vote.key.delete()

                                vote_val = value - vote_val;
                                old_score = submission.rating
                                new_score = old_score + vote_val

                                submission.rating = new_score;
                                submission.put()

                                vote = Vote(sub_id = id, value = value, user = session.user)
                                vote.put()

                                response = vote_result('ok')
                                self.response.write(response)
示例#4
0
def vote():
    data = request.json
    x = {'submission': 'successful'}
    response = app.response_class(response=json.dumps(data),
                                  status=200,
                                  mimetype='application/json')
    vote = Vote()
    vote.cast(data['session'], data['email'], data['framework'])
    return response
示例#5
0
 def vote(self, pli_id, direc):
     if not "voted_arr" in session: session["voted_arr"] = []
     voted = session["voted_arr"]
     if User.is_admin() or not pli_id in voted:
         v = Vote(playlist_item_id=pli_id, user_id=User.current_id(), direction=direc)
         v.save()
         voted.append(pli_id)
         session["voted_arr"] = voted  
         self.update_subscribers()
         return common.buildDialogResponse("Thanks for the input!", 200)
     else:
         return common.buildDialogResponse("Nice try sucka! You already voted", 409)
示例#6
0
def getVote():
    connection = mysql.connector.connect(user=os.getenv("DB_USER"),
                                         password=os.getenv("DB_PASS"),
                                         host=os.getenv("DB_HOST"),
                                         database=os.getenv("DB_NAME"))
    cursor = connection.cursor()
    vote = Vote(connection, cursor)
    voteKey = request.form.get('vote')
    response = make_response(str(vote.retrieveVote(voteKey))[2:-1])
    response.headers.add('Access-Control-Allow-Origin', '*')
    connection.close()
    return response
示例#7
0
async def vote_mute_user(ctx, user: discord.Member):
    # check if there is already a vote in progress
    global vote
    if vote.active:
        response = f"Sorry {ctx.message.author.mention}, a vote is already in progress."
    else:
        voters = get_voters(ctx.guild)
        vote = Vote(voters, user)
        vote.activate()  # start vote
        response = f"{ctx.message.author.nick} has started a vote to server mute {user.display_name}. The current " \
                   f"voters are:\n"

        response += "\n".join(v.display_name for v in voters)
    await ctx.send(response)
示例#8
0
    async def recieve_block(self, request):
        """Verifing and adding to the blockchain, which mined by other client. """
        """ If client not set up."""
        if self.client.public_key == None:
            response = {'message': 'No client setup.'}
            return web.json_response(data=response, status=400)

        result = await request.json()
        if not result:
            response = {'message': 'No data found.'}
            return web.json_response(data=response, status=400)
        block = Block(result['index'], result['preveous_hash'], [
            Vote(vt['candidate'], vt['id'], vt['node'], vt['signature'])
            for vt in result['votes']
        ], result['proof'], result['timestamp'])

        block = self.blockchain.mine_by_other_client(block)
        if block is False:
            response = {'message': 'Corrapted block.'}
            return web.json_response(data=response, status=400)
        elif not block is None:
            response = {
                'message': 'Add the Block done.',
                'block': Block.to_order_dict(block)
            }
            return web.json_response(data=response, status=201)
        else:
            response = {
                'message': 'Adding the block failed. No client set up.'
            }
            return web.json_response(data=response, status=500)
示例#9
0
def postVote():
    connection = mysql.connector.connect(user=os.getenv("DB_USER"),
                                         password=os.getenv("DB_PASS"),
                                         host=os.getenv("DB_HOST"),
                                         database=os.getenv("DB_NAME"))
    cursor = connection.cursor()
    vote = Vote(connection, cursor)
    voterKey = request.form.get('voter')
    electionKey = request.form.get('election')
    candidateKey = request.form.get('candidate')
    response = make_response(
        str(vote.generateVote(electionKey, voterKey, candidateKey)))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    connection.close()
    return response
示例#10
0
def vote(poll_code):
    # 1. get poll
    poll = Poll.objects(
        code=poll_code).first()  # .first la lay phan tu dau tien

    if request.method == 'GET':
        # 2. render poll detail + input
        return render_template("vote.html", p=poll)
        # 3. handle form request (POST)
    elif request.method == 'POST':
        form = request.form
        name = form['voter']
        choice = form['choice']
        #vote = form['vote']
        # 4. Save
        new_vote = Vote(name=name, choice=choice, poll=poll)
        new_vote.save()
        return "Voted"
示例#11
0
def main():
    if len(sys.argv) < 2:
        print('Usage: {} file'.format(sys.argv[0]))
        sys.exit(1)

    client = DBClient('votes', 'example')
    client.drop()

    file = open(sys.argv[1])
    for line in file.readlines():
        fields = [f.strip() for f in line.strip().split(',')]
        if not fields[-1]:
            continue
        vote = Vote(fields[0], fields[1], fields[2], fields[3], fields[4], '',
                    '')
        pprint(vote.to_dictionary())
        client.insert_one(vote.to_dictionary())

    print(client.count())
示例#12
0
 def getVotes(soup: BeautifulSoup, url: str) -> Vote:
     newSoup: BeautifulSoup = soup
     process: str = ""
     for tr in soup.find_all("tr"):
         th = (tr.find("th")).get_text()
         if "Skjal" in th:
             a = tr.find('a', href=True)
             newSoup = makeRequest(a['data-url'])
         elif "Atkvøða greidd í" in th:
             process = (tr.find("td")).get_text()
     return Vote.createVoteObj(newSoup, process)
示例#13
0
    async def add_vote(self, request):
        """If the client machine not create a keys."""
        if self.client.public_key == None:
            response = {'message': 'No client set up.'}
            return web.json_response(data=response, status=400)
        """If user are not login."""
        if self.user.user is None:
            response = {'message': 'User are not Login.'}
            return web.json_response(data=response, status=400)
        """If the request has not data."""
        values = await request.json()
        if not values:
            response = {'message': 'No data found.'}
            return web.json_response(data=response, status=400)
        """If the required data has an missing. """
        required_fields = ['candidate', 'id']
        if not all(field in values for field in required_fields):
            response = {'message': 'Required data missing.'}
            return web.json_response(data=response, status=400)

        candidate = values['candidate']
        vote = Vote(candidate)
        vote.signature = self.client.sign_vote(candidate, vote.id)
        vote.node = self.client.public_key

        success = await self.blockchain.add_to_open_votes(vote)
        """if the system add vote successflly."""
        if success:
            response = {
                'message': 'Successfully added vote.',
                'vote': {
                    'candidate': candidate,
                    'id': vote.id,
                    'node': self.client.public_key,
                    'signature': vote.signature
                }
            }
            return web.json_response(data=response, status=201)
        else:
            response = {'message': 'creating a vote failed.'}
            return web.json_response(data=response, status=500)
def load_votes(csv_file=CSVFILE):
    '''Read a csv file - each line is a vote, return a list of votes'''
    myvotes = []
    try:
        #with open(csv_file, 'rb') as f:
        with open(csv_file, 'rU') as f:
            reader = csv.reader(f)
            for row in reader:
                newvote = Vote(row)
                myvotes.append(newvote)
    except Exception, e:
        raise
示例#15
0
def vote():
    with app.app_context():
        db = get_db()
        cur = db.cursor()
        cur.execute('SELECT * FROM crobdidates WHERE writein = ?', (False, ))
        crobdidates = []
        for row in cur.fetchall():
            print(row)
            crobdidates.append(
                Vote(row[0], row[1], row[2], row[3], row[4], row[5]))

        return render_template('vote.html', crobdidates=crobdidates)
    return render_template('home.html')
示例#16
0
    async def add_vote(self, candidate, id, signature=0):
        """ If the public key of client not exist """
        if self.hosting_node == None:
            return False
        vote = Vote(candidate, id, node=self.hosting_node, signature=signature)
        self.__open_votes.append(vote)

        if self.send_vote(vote):
            print('Vote send.')
        else:
            print('Vote send failed.')

        return True
示例#17
0
    def get_vote(self,
                 rm='',
                 hangar_id='',
                 bet='',
                 punkt='',
                 parti='',
                 valkrets='',
                 rost='',
                 antal=500,
                 gruppering=''):

        data = self._get(
            self.url, 'voteringlista', {
                'hangar_id': hangar_id,
                'rm': rm,
                'bet': bet,
                'punkt': punkt,
                'parti': parti,
                'valkrests': valkrets,
                'iid': '',
                'rost': rost,
                'sz': antal,
                'utformat': 'json',
                'gruppering': gruppering,
            })

        vote_list = []
        if data['@antal'] == '0':
            logging.warning(f'No data for.')
        elif data['@antal'] == '1':
            vote_list.append(Vote(data['votering']))
        else:
            for vote_data in data['votering']:
                vote_list.append(Vote(vote_data))

        return vote_list
示例#18
0
    def load_data():
        try:
            with open('db/blockchain.txt', mode = 'r') as f:
                file_contents = f.readlines()
                
                """ Read blockchain form the file"""
                blockchain = json.loads(file_contents[0][:-1])
                updated_blockchain = []
                for block in blockchain:
                    for vt in block['votes']:
                        print(vt)
                    converted_vt = [Vote(vt['candidate'], vt['id']) for vt in block['votes']]

                    updated_block = Block(block['index'], block['preveous_hash'], converted_vt, block['proof'], block['timestamp'])

                    updated_blockchain.append(updated_block)
                
                blockchain = updated_blockchain

                """ Read open votes form the file"""
                open_votes = json.loads(file_contents[1])
                updated_votes = []
                for vt in open_votes:
                    updated_vote = Vote(vt['candidate'], vt['id'])

                    updated_votes.append(updated_vote)
                
                open_votes = updated_votes

                return blockchain, open_votes         
        
        except(IOError, IndexError):
             print('Load data Failed!!!!!!')
             return None, None
        finally:
            print('clean up')
示例#19
0
    async def vote(self, ctx: Context, *choices: str, time=20):
        """ Create a vote. (Alt command: v) """
        # Check if voting is possible
        guild = ctx.guild
        if ctx.guild is None:
            await ctx.send("This feature is only supported in guilds")
            return
        vote = self.votes.get(guild)
        if vote:
            await ctx.send("There is already a vote running")
            return

        # Attach a number to each choice
        choice_enum: List[Tuple[int, str]] = list(
            enumerate(
                map(lambda choice: choice.strip(" ,\n").lower(), choices), 1))
        vote = Vote(self.bot, guild, choice_enum)
        self.votes[guild] = vote
        LOGGER.debug("Started voting listener")
        self.bot.add_listener(vote.on_vote, name="on_message")
        choice_text = ("\n".join(
            map(lambda choice: f"{choice[0]}\t\u21D2 \t{choice[1]}",
                choice_enum)) if choice_enum else "Open voting")
        await ctx.send(f"Voting started for {time}s.\n{choice_text}")

        await asyncio.sleep(time)

        self.bot.remove_listener(vote.on_vote, name="on_message")
        LOGGER.debug("Removed voting listener")
        results = vote.format_results()
        hist = vote.termogram()
        if hist is not None:
            await ctx.send(f"Voting finished!\n{hist}")
        else:
            await ctx.send(f"Voting finished!\n{results}")
        del self.votes[guild]
def results_check_page():
	if dbManager.isElectionOver(dbManager, connection):
		if request.method == 'POST':
			result = request.form
			searchQuery = result['search']
			cleanSearchQuery = re.sub(r"\D", "", searchQuery)
			
			data = Vote.getVote(dbManager, connection, cleanSearchQuery)
			if not data:
				return not_found('Your voter ID does not match any voter IDs recorded for this election. Please return to the previous page and make sure your voter ID is entered correctly.')
			
			return render_template('check.html', data=data)
		else:
			return render_template('check.html', data=None)
	else:
		return not_found('The election has not yet concluded, please try again after the election end time.')
示例#21
0
    def get_thread(cls, anchor_uri, user):
        """
        Returns a tree of comments.
        """
        comments = cls._default_manager.filter(anchor_uri=anchor_uri)

        map = {"root": []}
        for comment in comments:
            value = Vote.value_for(comment, user=user)      # TODO: Cache this
            if (value > 0):
                comment.up = True
            if (value < 0):
                comment.down = True
            comment.thread = map.setdefault(comment.id, [])
            map.setdefault(comment.parent_id or "root", []).append(comment)
        return map["root"]
示例#22
0
def count_vote():
    if 'candidate' in request.form and request.form['candidate'] != "-1":
        print('standard candidates selected')
        print(str(request.form['candidate']))
        with app.app_context():
            db = get_db()
            cur = db.cursor()
            c = int(request.form['candidate'])
            cur.execute('SELECT * FROM crobdidates WHERE id = ?', (c, ))
            result = cur.fetchone()
            print(str(result))
            newvotes = int(result[5]) + 1
            cur.execute('UPDATE crobdidates SET votes = ? WHERE id = ?',
                        (newvotes, int(request.form['candidate'])))
            db.commit()

    elif 'writein' in request.form and request.form['writein']:
        print('writein candidate selected!')
        print(request.form['writein'])
        with app.app_context():
            db = get_db()
            cur = db.cursor()
            cur.execute('SELECT * FROM crobdidates WHERE prez = ?',
                        (request.form['writein'], ))
            result = cur.fetchone()
            if not result:
                cur.execute(
                    'INSERT INTO crobdidates (prez, vprz, slogan, writein, votes) VALUES (?, ?, ?, ?, ?)',
                    (request.form['writein'], "", "", True, 1))
            else:
                cur.execute('UPDATE crobdidates SET votes = ? WHERE id = ?',
                            (int(result[5]) + 1, int(result[0])))
            db.commit()
    data = []
    with app.app_context():
        db = get_db()
        cur = db.cursor()
        cur.execute('SELECT * FROM crobdidates ORDER BY votes DESC')
        for row in cur.fetchall():
            data.append(Vote(row[0], row[1], row[2], row[3], row[4], row[5]))
    # print(str(data))
    graph_file = render_graph(data)
    return render_template('results.html', graph_file=graph_file, data=data)
示例#23
0
    async def createvote(self, ctx: Context, votename: str):
        if dm.vote_exists(votename):
            await ctx.send("Vote with that name already exists!")
            return
        
        def check(m):
            return m.author.id == ctx.author.id and m.channel == ctx.channel

        await ctx.send("Send line separated choices")
        options: str
        try:
            options = await self.bot.wait_for("message", check=check, timeout=90)  
        except asyncio.TimeoutError:
            ctx.send("Timed out")
            return
        options = options.content.split("\n")
        
        dm.create_vote(Vote(votename, options))
        await ctx.send("Vote created successfully")
示例#24
0
    def read_files(self):
        """
        Reads JSON paths of Reps, Bills, and Votes
        """
        print('Loading sessions.')
        ses_paths = get_jsons(Session.ROOT_DIR)
        self._sessions = [Session(filename=p) for p in tqdm(ses_paths)]

        print('Loading reps.')
        rep_paths = get_jsons(Representative.ROOT_DIR)
        self._reps = [Representative(filename=p) for p in tqdm(rep_paths)]

        print('Loading bills.')
        bill_paths = get_jsons(Bill.ROOT_DIR)
        self._bills = [Bill(filename=p) for p in tqdm(bill_paths)]

        print('Loading votes.')
        vote_paths = get_jsons(Vote.ROOT_DIR)
        self._votes = [Vote(filename=p) for p in tqdm(vote_paths)]
示例#25
0
    async def receive_vote(self, request):
        """ Recieving the vote form another client."""
        """ If client not set up."""
        if self.client.public_key == None:
            response = {'message': 'No client setup.'}
            return web.json_response(data=response, status=400)

        result = await request.json()
        if not result:
            response = {'message': 'No data found.'}
            return web.json_response(data=response, status=400)
        vote = Vote(result['candidate'], result['id'], result['node'],
                    result['signature'])
        if self.client.verify_vote(vote):
            self.blockchain.add_to_open_votes(vote)
            response = {'message': 'Recieved succed.'}
            return web.json_response(data=response, status=200)
        else:
            response = {'message': 'Corrapted vote.'}
            return web.json_response(data=response, status=400)
示例#26
0
 async def replace_chain(self):
     """ Replacing chian, Using longest chain Algorithm."""
     network = self.nodes_url
     max_length = 0
     longest_chain = None
     """ Longest chain """
     for node in network:
         new_chain = []
         response = requests.get(f'http://{node}/chain')
         response = None
         status_code = None
         # response = requests.get(f'http://{node}/chain')
         async with aiohttp.ClientSession() as session:
             async with session.get(f'http://{node}/chain') as resp:
                 status_code = resp.status
                 response = await resp.json()
         if status_code == 200:
             length = response['length']
             chain = response['chain']
             for block in chain:
                 # added_block = Block(block['index'], block['preveous_hash'],[vt.__dict__ for vt in block['votes']], block['proof'], block['timestamp'])
                 added_block = Block(block['index'], block['preveous_hash'],
                                     [
                                         Vote(vt['candidate'], vt['id'],
                                              vt['node'], vt['signature'])
                                         for vt in block['votes']
                                     ], block['proof'], block['timestamp'])
                 new_chain.append(added_block)
             if self.verify_other_chain(new_chain) and length > max_length:
                 longest_chain = new_chain
                 max_length = length
     if longest_chain:
         print(max_length)
         self.__chain = longest_chain
         return True
     return False
示例#27
0
p21 = {1: 80, 2: 20}
p22 = {1: 80, 2: 20}
p23 = {1: 80, 2: 20}
p24 = {1: 90, 2: 10}
p25 = {1: 90, 2: 10}
p26 = {1: 90, 2: 10}
p27 = {1: 90, 2: 10}
p28 = {1: 90, 2: 10}
p29 = {1: 90, 2: 10}
p30 = {1: 90, 2: 10}
p31 = {1: 90, 2: 10}
p32 = {1: 90, 2: 10}
p33 = {1: 90, 2: 10}

# Votes
v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 = Vote(2, p1), Vote(2, p2), Vote(
    2, p3), Vote(2, p4), Vote(2,
                              p5), Vote(2, p6), Vote(2, p7), Vote(2, p8), Vote(
                                  2, p9), Vote(2, p10), Vote(2, p11)
v12, v13, v14, v15, v16, v17, v18, v19, v20 = Vote(1, p12), Vote(1, p13), Vote(
    1,
    p14), Vote(1,
               p15), Vote(1,
                          p16), Vote(1,
                                     p17), Vote(1,
                                                p18), Vote(1,
                                                           p19), Vote(1, p20)
v21, v22, v23, v24, v25, v26, v27, v28, v29 = Vote(1, p21), Vote(1, p22), Vote(
    1,
    p23), Vote(1,
               p24), Vote(1,
示例#28
0
def lookup_vote_by_votename(votename: str) -> Vote:
    with DBCursor(database) as c:
        c.execute('SELECT * FROM votes WHERE votename = ?', (votename, ))
        return Vote.from_database(c.fetchone())
示例#29
0
def lookup_votes() -> List[Vote]:
    with DBCursor(database) as c:
        c.execute('SELECT * FROM votes')
        return [Vote.from_database(elem) for elem in c.fetchall()]
示例#30
0
# app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
from vote import Vote

app = Flask(__name__)
CORS(app)

vote = Vote({
    "options": [],
    "voters": [],
    "missing": [],
    "complete": [],
})


@app.route('/getVote/', methods=['GET'])
def getConfigurations():
    return jsonify(vote.toJson())


@app.route('/getVote/', methods=['POST'])
def getConfigurations():
    return jsonify(vote.toJson())


if __name__ == '__main__':
    # Threaded option to enable multiple instances for multiple user access support
    app.run(host="192.168.1.9", threaded=True, port=5050)
示例#31
0
import mlab
from vote import Vote
from poll import Poll

mlab.connect()

# from vote => poll

# vote = Vote.objects().first()
# print(vote.choice)
# print(vte.voter)

# poll = vote.poll
# print(poll.question)
# print(poll.options)
# from poll => vote
poll = Poll.objects(code="QBXXGV").first()
votes = Vote.objects(poll=poll)
for vote in votes:
    print(vote.name)
    print(vote.poll.question)
示例#32
0
 def add_vote(self, name, text, vars):
     self.votes[name] = Vote(name, text, vars)
示例#33
0
 def fix_value(self):
     self.value = Vote.value_for(self)
示例#34
0
    def setUp(self):
        self.client = Redis(decode_responses=True)
        self.client.flushdb()

        self.vote = Vote(self.client, "question::10086")
示例#35
0
 def vote(self, user, value):
     Vote.cast(user, self, value)
     self.fix_value()
示例#36
0
    def get(self):
        cookie = self.request.get('cookie')

        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'

        if not cookie:
            error = json_error('retrieve', 'failure', 'cookie')
            self.response.write(json.dumps(error))

        else:
            flag = self.request.get('flag')
        
            if not flag:
                error = json_error('retrieve', 'failure', 'no flag')
                self.response.write(json.dumps(error))

            else:
                session = Session.query(Session.cookie == cookie).get()

                if not session:
                    error = json_error('retrieve', 'failure', 'session')
                    self.response.write(error)

                else:
                    # flag = 1 means a single request
                    if flag == '1':
                        try:
                            id = self.request.get('id');
                            key = ndb.Key(urlsafe=id)

                            if not id:
                                self.response.write(json.dumps(json_error('single request', 'failure', 'id')))

                            else:
                                submission = key.get()

                                if not submission:
                                    error = json_error('single request', 'failure', 'no corresponding submission')
                                    self.response.write(json.dumps(error))

                                else:
                                    last_vote = Vote.query(ndb.AND(Vote.user == session.user, Vote.sub_id == submission.key.urlsafe())).get()
                                    if not last_vote:
                                        vote_val = 0     
                                    else:
                                        vote_val = last_vote.value
    
                                    string_submission = json_string(submission.key.urlsafe(), submission.name, submission.category, submission.description, submission.location,
                                                                    submission.image, submission.keywords, submission.submitter,
                                                                    submission.tfrom, submission.tto, submission.rating, vote_val)
                                    response = json.dumps(string_submission)
                                    self.response.write(response)

                        except:
                            self.response.write(json.dumps(json_error('single request', 'failure', 'id')))


                    # flag = 2 means that we are requesting submissions to display in what's new
                    elif flag == '2':
                        time_range = 1447786800
                        date = datetime.datetime.fromtimestamp(time_range/1e3)
                        submissions_number = 20

                        submissions = Submission.query(Submission.submitted >= date).fetch(submissions_number)

                        if not submissions:
                            error = json_error('what is new', 'failure', 'nothing in range')
                            self.response.write(json.dumps(error))

                        else:
                            submissions_array = []
                            if(submissions_number <= len(submissions)):
                                for i in range(0, submissions_number):
                                    submission = submissions[i]
                                    # what's new used for around you too. Server return location so that the app
                                    # can use it to display submissions near user on the map
                                    json_submission = json_array_with_location(submission.key.urlsafe(), submission.name,submission.image, submission.rating, submission.location)
                                    submissions_array.append(json_submission)

                            else:
                                for i in range(0, len(submissions)):
                                    submission = submissions[i]
                                    json_submission = json_array_with_location(submission.key.urlsafe(), submission.name, submission.image, submission.rating, submission.location)
                                    submissions_array.append(json_submission)


                            response = json.dumps(submissions_array)
                            self.response.write(response)

                    # flag = 4 means that we are requesting submissions for a specific category
                    elif flag == '4':
                        category = self.request.get('category')
                        submissions_number = 20

                        if not category:
                            error = json_error('retrieve category', 'failure', 'no category')
                            self.response.write(json.dumps(error))

                        else:
                            submissions = Submission.query(Submission.category == category).fetch(submissions_number)

                            if not submissions:
                                error = json_error('retrieve category', 'failure', 'empty category')
                                self.response.write(json.dumps(error))

                            else:
                                submissions_array = []
                                if(submissions_number <= len(submissions)):
                                    for i in range(0, submissions_number):
                                        submission = submissions[i]
                                        json_submission = json_array(submission.key.urlsafe(), submission.name,submission.image, submission.rating)
                                        submissions_array.append(json_submission)

                                else:
                                    for i in range(0, len(submissions)):
                                        submission = submissions[i]
                                        json_submission = json_array(submission.key.urlsafe(), submission.name,submission.image, submission.rating)
                                        submissions_array.append(json_submission)

                                response = json.dumps(submissions_array)
                                self.response.write(response)

                    # every other flag generate an error
                    else:
                        error = json_error('retrieve' ,'failure', 'flag')
                        self.response.write(json.dumps(error))
示例#37
0
	def __init__(self,**kargs):
		Vote.__init__(self,tweets=kargs["tweets"],instances=kargs["instances"],classifiers=kargs["classifiers"],selection=kargs["selection"])
		self.training=False
		self.tmp_keys = self.tweets.keys()[:10]
		self.alpha_result_dict = {}
示例#38
0
# 				print("Adding", str(u_email), "voting for", str(rid), "value", str(vote), "date", str(date))

startDate = datetime.datetime(2015, 3, 1,13,00)
lstUsers = user.loadAll()
# for each theme
for query in queries:
	restaurants = filter_restaurants.construct(ll, query, 'hott')
	if restaurants != None:
		restaurants = restaurants

		# for each user
		for u in lstUsers:
			u_email = u.email

			# calculate the chance to vote for it
			for r in restaurants:
				rid = r["rid"]
				r_name = r["name"]
				# should vote
				if randint(0,3) == 0:
					# generate random vote
					vote = 1
					if randint(0,4) == 0:
						vote = -1
					date = generate_timestamp.random_date(startDate)
					v = Vote(u_email, rid, vote, date)
					v.save()
					print("Adding", str(u_email), "voting for", str(r_name), "value", str(vote), "date", str(date))