Exemplo n.º 1
0
def index():
    party = Party(name='Dungeons and Databases')
    characters = [
        2342595, 2266180, 2790689, 5304380, 6448988, 2278224, 4657425, 2271732
    ]
    members = []
    for character in characters:
        try:
            data = get_character_health(character_id=character)
            members.append(
                Character(character, data['name'], 0, 0, data['current_hp'],
                          data['health_status']))
            cache.set(character, data, timeout=100 * 60)
        except ThrottlingException as e:
            data = cache.get(character)
            if data is None:
                flash(
                    "D&D Beyond throttled us and charcter_id {} was not already cached."
                    .format(character), 'danger')
            else:
                members.append(
                    Character(character, data['name'], 0, 0,
                              data['current_hp'], data['health_status']))
                flash(
                    "ThrottlingException from D&D Beyond, retrieving {} from cache"
                    .format(data['name']), 'warning')
    for char in sorted(members, key=lambda x: x.name):
        party.add(char)
    return render_template('main.html', entries=party)
Exemplo n.º 2
0
def fill_party_table():
    """
    Fill party table with information from party.json
    :return:
    """
    party_ind = Party(name='Independent',
                      leader='None',
                      hq='None',
                      description='None',
                      abbrev='IND')
    party_npa = Party(name='No Party Affiliation',
                      leader='None',
                      hq='None',
                      description='None',
                      abbrev='NPA')
    database.session.add(party_ind)
    database.session.add(party_npa)
    for key in PARTY_JSON.keys():
        temp_party = Party(name=PARTY_JSON[key]['name'],
                           leader=PARTY_JSON[key]['leader'],
                           hq=PARTY_JSON[key]['hq_address'],
                           description=PARTY_JSON[key]['description'],
                           abbrev=key)
        database.session.add(temp_party)
    database.session.commit()
Exemplo n.º 3
0
def lookup_parties_by_id():
    log("Getting all parties")
    fs = Party.all().fetch(100)
    parties_by_id = {}
    c = 0
    while fs:
        log("  getting batch from " + str(c))
        for f in fs:
            c = c + 1
            parties_by_id[str(f.key())] = f
        fs = Party.all().filter('__key__ >', fs[-1].key()).fetch(100)
    return parties_by_id
Exemplo n.º 4
0
	def dispatch_request(self, party_id):
		Usr = users.get_current_user()
		if Usr.email() == '*****@*****.**' or Usr.email() == '*****@*****.**':
			party = Party.get_by_id(party_id)
			form = PartyForm(obj=party)
			form.street.data = party.address.street
			form.suite.data = party.address.suite
			form.city.data = party.address.city
			form.state.data = party.address.state
			form.zip.data = party.address.zip
			if request.method == "POST" and form.validate_on_submit():
				party.name = form.data.get('name')
				party.address.street = form.data.get('street')
				party.address.suite = form.data.get('suite')
				party.address.city = form.data.get('city')
				party.address.state = form.data.get('state')
				party.address.zip = form.data.get('zip')
				party.email = form.data.get('email')
				party.phone = form.data.get('phone')
				party.code = form.data.get('code')
				party.put()
				flash(u'Party %s successfully saved.' % party_id, 'success')
				return redirect(url_for('admin'))
			return render_template('edit_party.html', party=party, form=form)
		else:
			flash(u'Sorry, no admission!')
			return redirect(url_for('index'))
Exemplo n.º 5
0
    def get_results(self):
        #r = requests.get(self.href)
        #data = r.text
        #reader = csv.DictReader(data.splitlines(), delimiter='\t')

        data = open('local_elections/WA/test_data/MediaResults.txt', 'r')
        reader = csv.DictReader(data, delimiter='\t')

        reader.next()  # Skip header now
        for row in reader:
            raw_candidate_name = row['BallotName']
            candidate_name_split = raw_candidate_name.split()
            candidate_first_name = candidate_name_split[0]
            candidate_last_name = ' '.join(candidate_name_split[1:])

            raw_candidate_party = row['PartyName']
            party_regex = re.compile("Prefers (\w+) Party")
            party_result = party_regex.findall(raw_candidate_party)
            party_name = ''
            party_abbreviation = ''
            if party_result:
                party_name = party_result[0]
                party_abbreviation = party_name[0].upper()

            p = Party(party_name, party_abbreviation)

            c = Candidate(candidate_first_name, candidate_last_name,
                          row['Votes'])

            r = Race(row['RaceName'], row['RaceJurisdictionTypeName'],
                     row['TotalBallotsCastByRace'])

            race, created = self.get_or_create_race(r)
            race.add_candidate(c)
Exemplo n.º 6
0
	def dispatch_request(self):
		Usr = users.get_current_user()
		if Usr.email() == '*****@*****.**' or Usr.email() == '*****@*****.**':
			parties = Party.query()
			persons = Person.query()			
			return render_template('admin_list.html',parties=parties,persons=persons, Party=Party,Person=Person)
		else:
			flash(u'Sorry, no admission!')
			return redirect(url_for('rsvp'))
Exemplo n.º 7
0
def party_create():
    form = PartyForm()

    if form.validate_on_submit():
        if current_user.get_id() == None:
            return redirect(url_for('.login_route'))
        party = Party(
            party_host = current_user.get_id(),
            party_name = form.partyname.data
        )
        db.session.add(party)
        db.session.commit()
        print "PARTY ADDED: \t SUCCESS!\n"
        return redirect(url_for('.party_route', party_id=party.get_id()))
    else:
        print form
        print form.errors
        return render_template("create_party.html", form=form, errors=form.errors)
    return render_template("create_party.html", form=form)
Exemplo n.º 8
0
def create():
    form = AddForm(request.form)

    if form.validate_on_submit():
        party = Party(name=form.name.data)
        db.session.add(party)
        db.session.commit()
        return redirect(url_for('parties.index'))

    return render_template('parties/create.html', form=form)
Exemplo n.º 9
0
    def test_add_candidate(self):
        """Test the public ``add_candidate'' function provided by the
        Constituency() class.
        """

        con = Constituency("test")
        con2 = Constituency("test2")

        party1 = Party("party1")
        party2 = Party("party2")
        party3 = Party("party3")

        candidate1 = Candidate("candidate1", party1, con)
        candidate2 = Candidate("candidate2", party2, con)
        candidate3 = Candidate("candidate3", party3, con2)
        candidate4 = Candidate("candidate4", party2, con)

        con.add_candidate(candidate1)
        self.assertTrue(candidate1 in con.candidates)
        self.assertEqual(len(con.candidates), 1)

        # attempt to add a candidate twice
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate1)
        self.assertEqual(len(con.candidates), 1)
        self.assertEqual(len(con.parties), 1)

        con.add_candidate(candidate2)
        self.assertTrue(candidate1 in con.candidates)
        self.assertTrue(candidate2 in con.candidates)
        self.assertEqual(len(con.candidates), 2)
        self.assertEqual(len(con.parties), 2)

        # attempt to add a candidate with the wrong constituency
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate3)
        self.assertEqual(len(con.candidates), 2)

        # attempt to add a candidate with the same party
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate4)
        self.assertEqual(len(con.candidates), 2)
Exemplo n.º 10
0
def _create_party(user, party_name=None):
    party = Party()
    party.host_id = user
    party.status = 'P'
    if party_name:
        party.token = party_name
    else:
        party.token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(TOKEN_SIZE))
    party.save()
    return party
Exemplo n.º 11
0
    def test_election(self):
        """Test the public ``add_candidate'' function provided by the
        Election() class.
        """

        el = Election()

        con1 = Constituency("test")
        con2 = Constituency("test2")

        party1 = Party("party1")
        party2 = Party("party2")

        candidate1 = Candidate("candidate1", party1, con1)
        candidate2 = Candidate("candidate2", party2, con1)
        candidate3 = Candidate("candidate3", party2, con2)

        el.add_candidate(candidate1)
        self.assertTrue(candidate1 in el.candidates)
        self.assertTrue(party1 in el.parties)
        self.assertTrue(con1 in el.constituencies)

        with self.assertRaises(AssertionError):
            el.add_candidate(candidate1)

        el.add_candidate(candidate2)
        self.assertTrue(candidate2 in el.candidates)
        self.assertTrue(party1 in el.parties)
        self.assertTrue(con1 in el.constituencies)
        self.assertEqual(len(el.candidates), 2)
        self.assertEqual(len(el.parties), 2)
        self.assertEqual(len(el.constituencies), 1)

        el.add_candidate(candidate3)
        self.assertTrue(candidate3 in el.candidates)
        self.assertTrue(party2 in el.parties)
        self.assertTrue(con2 in el.constituencies)
        self.assertEqual(len(el.candidates), 3)
        self.assertEqual(len(el.parties), 2)
        self.assertEqual(len(el.constituencies), 2)
Exemplo n.º 12
0
    def test_add_winner(self):
        """Test the public ``add_winner'' function provided by the
        Outcome() class.
        """

        con = Constituency("test")
        con2 = Constituency("test2")

        party1 = Party("party1")
        party2 = Party("party2")

        candidate1 = Candidate("candidate1", party1, con)
        candidate2 = Candidate("candidate2", party2, con2)

        outcome = Outcome()

        outcome.add_winner(candidate1)

        self.assertEqual(len(outcome.winners), 1)
        self.assertTrue(candidate1 in outcome.winners)

        # attempt to add the same candidate
        with self.assertRaises(AssertionError):
            outcome.add_winner(candidate1)
Exemplo n.º 13
0
	def dispatch_request(self, party_id):
		Usr = users.get_current_user()
		if Usr.email() == '*****@*****.**' or Usr.email() == '*****@*****.**':
			party = Party.get_by_id(party_id)
			persons = Person.query(Person.party == ("%s" % party.key.id()) )
			if request.method == "POST":
				for ps in persons:
					ps.key.delete()
				party.key.delete()
				flash(u'Party and persons %s successfully deleted.' % party_id, 'success')
				return redirect(url_for('admin'))
			return redirect(url_for('admin'))
		else:
			flash(u'Sorry, no admission!')
			return redirect(url_for('index'))
Exemplo n.º 14
0
	def dispatch_request(self):
		Usr = users.get_current_user()
		if Usr.email() == '*****@*****.**' or Usr.email() == '*****@*****.**':
			parties = Party.query()
			persons = Person.query()
			p = request.args.get('p', '')				
			if not p:
				form = PartyForm()
				if form.validate_on_submit():
					party = Party(name=form.name.data,code=gen_code(),email=form.email.data,
							phone=form.phone.data, address={ 'street':form.street.data, 'zip':form.zip.data,
							'suite': form.suite.data, 'city':form.city.data, 'state':form.state.data, } )
					party.put()
					p = party.key.id()
					#request.post(p=p)
					#return redirect(url_for('index'))
					return render_template('admin.html', pid=p,form=PersonForm(),parties=parties,persons=persons,
							Party=Party,Person=Person)
				return render_template('admin.html',pid=p,form=form,parties=parties,persons=persons,
						Party=Party,Person=Person)
			else:
				form = PersonForm()
				p = int(p)
				if form.validate_on_submit():
					person = Person(title=form.title.data,first=form.first.data,last=form.last.data,
							food=form.food.data, rsvp='a', party=form.party.data)
					person.put()
					ps = person.key.id()
					return redirect(url_for('admin', p=p))
					return render_template('admin.html',pid=p,form=form,parties=parties,
							persons=persons, Party=Party,Person=Person)
				return render_template('admin.html',pid=p,form=form,parties=parties,
							persons=persons, Party=Party,Person=Person)
		else:
			flash(u'Sorry, no admission!')
			return redirect(url_for('rsvp'))
Exemplo n.º 15
0
def task_average_response_by_party(request, party_key_name, refined_issue_key_name):
    party = Party.get_by_key_name(party_key_name)
    refined_issue = RefinedIssue.get_by_key_name(refined_issue_key_name)

    arbp = db.Query(AverageResponseByParty).filter('party =', party).filter('refined_issue =', refined_issue).get()
    if not arbp:
        arbp = AverageResponseByParty(party = party, refined_issue = refined_issue,
                average_agreement = None, processing_running_total = 0, 
                processing_running_count = 0, processing_next_key = None)

    chunk = db.Query(Candidacy).filter('deleted = ', False).filter('survey_filled_in =', True)

    # carry on calculation where we left off
    if arbp.processing_last_candidacy == None:
        assert arbp.processing_running_total == 0
        assert arbp.processing_running_count == 0
    else:
        chunk = chunk.filter('__key__ >', arbp.processing_last_candidacy.key())

    # do 100 candidacies at a time, as too slow otherwise
    chunk.fetch(10) # XXX

    candidacy = None
    for candidacy in chunk:
        survey_response = db.Query(SurveyResponse).filter('candidacy =', candidacy).filter('refined_issue =', refined_issue).get()
        if survey_response:
            arbp.processing_running_total += survey_response.agreement
            arbp.processing_running_count += 1
    arbp.processing_last_candidacy = candidacy

    # if we've finished, work out average
    if candidacy == None:
        arbp.average_agreement = float(arbp.processing_running_total) / float(arbp.processing_running_count)

    arbp.put()

    # calculate next chunk
    if candidacy == None:
        return HttpResponse("Calculation complete for " + party.name + " question: " + refined_issue.question)
    else:
        taskqueue.Queue('average-calc').add(taskqueue.Task(url='/task/average_response_by_party/' + party_key_name + "/" + refined_issue_key_name))
        return HttpResponse("Done " + str(arbp.processing_running_count) + ", queued next chunk for " + party.name + " question: " + question)
Exemplo n.º 16
0
def create_party():
    if not g.user:
        flash('You must log in for that', category='danger')
        return redirect('/login')
    form = PartyForm()
    if form.validate_on_submit():
        p = Party.create(name=form.name.data,
                         address=form.address.data,
                         city=form.city.data,
                         state=form.state.data,
                         zip_code=form.zip_code.data,
                         leader_id=g.user.id)
        if type(p) == str:
            flash(p, category='info')
        else:
            flash('Successfully added party', category='success')
            resturaunts = Resturaunt.get_resturaunts(party_id=p.id)
            if type(resturaunts) == str:
                flash(resturaunts, category='warning')
            return redirect('/')
    return render_template('/parties/create.html', form=form)
Exemplo n.º 17
0
	def dispatch_request(self, cc):
		party = Party.query(Party.code == cc).get()
		if not party:
			return render_template('404.html')
		
		if request.method == "POST":
			p_d = request.args.get('p', '')
			ps = Person.get_by_id(int(p_d))
			r_d = request.args.get('r', '')
			f_d = request.args.get('f', '')
			try:
				if r_d:
					ps.rsvp = r_d
				if f_d:
					ps.food = f_d
				ps.put()
			except CapabilityDisabledError:
				flash(u'App Engine Datastore is currently in read-only mode.', 'info')
				return redirect(url_for('code', cc=cc))
			return redirect(url_for('code',cc=cc))
		else:
			persons = Person.query(Person.party == ("%s" % party.key.id()) )
			return render_template('code.html', party=party, persons=persons)
Exemplo n.º 18
0
import requests

with open('json_data/parties.json',
          'r') as parties_file:  # use local edited version
    parties = json.load(parties_file)

r = requests.get('http://opinionbee.uk/json/types')
types = r.json()

#: :type: dict
leaderdict = types.get("LEAD").get("candidatelist")

for party in parties:
    code = party
    details = parties.get(party)  # Get inner dict

    name = details.get("name")
    colour = details.get("colour")
    text_colour = details.get("textcolor")
    url = details.get("url")
    candidate = leaderdict.get(code)

    party_model = Party(name=name,
                        code=code,
                        colour=colour,
                        text_colour=text_colour,
                        url=url,
                        candidate=candidate)
    db.session.add(party_model)
db.session.commit()
Exemplo n.º 19
0
def load_from_ynmp(ynmp, frozen_seats):
    # Put parties in datastore - don't worry about deleted ones, they just
    # won't be referenced by other tables.
    parties_by_key = {}
    for party_id, party_data in ynmp["Party"].iteritems():
        key_name = party_id
        party = Party(ynmp_id=int(party_id),
                      name=party_data["name"],
                      code=party_data["code"],
                      image_id=int_or_null(party_data["image_id"]),
                      created=convdate(party_data["created"]),
                      updated=convdate(party_data["updated"]),
                      key_name=key_name)
        log("  Storing party " + party.name)
        parties_by_key[key_name] = party
    log("Putting all parties")
    put_in_batches(parties_by_key.values())

    # Put candidates in datastore - don't worry about deleted ones, they
    # just won't be referenced by a candidacy
    candidates_by_key = {}
    for candidate_id, candidate_data in ynmp["Candidate"].iteritems():
        if "status" not in candidate_data:
            raise Exception("No status entry for " + str(candidate_data))
        key_name = candidate_id
        candidate = Candidate(ynmp_id=int(candidate_id),
                              name=candidate_data["name"],
                              code=candidate_data["code"],
                              status=candidate_data["status"],
                              email=candidate_data["email"],
                              address=candidate_data["address"],
                              party=parties_by_key[candidate_data["party_id"]],
                              image_id=int_or_null(candidate_data["image_id"]),
                              created=convdate(candidate_data["created"]),
                              updated=convdate(candidate_data["updated"]),
                              key_name=key_name)
        log("  Storing candidate " + candidate.name)
        candidates_by_key[key_name] = candidate
    log("Putting all candidates")
    put_in_batches(candidates_by_key.values())

    # Put seats in datastore - don't worry about deleted ones, they
    # just won't be referenced by a candidacy
    seats_by_key = {}
    for seat_id, seat_data in ynmp["Seat"].iteritems():
        key_name = seat_id
        seat = Seat(ynmp_id=int(seat_id),
                    name=seat_data["name"],
                    code=seat_data["code"],
                    created=convdate(seat_data["created"]),
                    updated=convdate(seat_data["updated"]),
                    key_name=key_name)
        if key_name in frozen_seats:
            seat.frozen_local_issues = True
        log("  Storing seat " + seat.name)
        seats_by_key[key_name] = seat
        seats_by_name[seat.name] = seat
    log("Putting all seats")
    put_in_batches(seats_by_key.values())

    # Get list of existing candiacies in remote datastore
    # in batches due to 100 entity at a time limit, as per http://code.google.com/appengine/articles/remote_api.html
    log("Getting list of Candidacies")
    candidacies = Candidacy.all().filter("deleted =", False).fetch(100)
    to_be_marked_deleted = {}
    while candidacies:
        for candidacy in candidacies:
            key_name = candidacy.key().name()
            log("Marking before have candidacy key " + key_name)
            to_be_marked_deleted[key_name] = candidacy
        candidacies = Candidacy.all().filter("deleted =", False).filter(
            '__key__ >', candidacies[-1].key()).fetch(100)

    # Loop through new dump of candidacies from YourNextMP, adding new ones
    candidacies_by_key = {}
    for candidacy_id, candidacy_data in ynmp["Candidacy"].iteritems():
        candidate = candidates_by_key[candidacy_data["candidate_id"]]
        assert candidate.status in [
            'standing', 'standing_down', 'not-standing'
        ]
        if candidate.status == 'standing_down' or candidate.status == 'not-standing':
            continue

        key_name = candidacy_data["seat_id"] + "-" + candidacy_data[
            "candidate_id"]

        # find existing entry if there is one, or else make new one
        if key_name in to_be_marked_deleted:
            candidacy = to_be_marked_deleted[key_name]
        else:
            candidacy = Candidacy(key_name=key_name)

        # fill in values
        candidacy.ynmp_id = int(candidacy_id)
        candidacy.seat = seats_by_key[candidacy_data["seat_id"]]
        candidacy.candidate = candidate
        candidacy.created = convdate(candidacy_data["created"])
        candidacy.updated = convdate(candidacy_data["updated"])
        candidacy.deleted = False
        # make sure it has a survey token
        if not candidacy.survey_token:
            log("Generating survey token for " + candidacy.seat.name + " " +
                candidacy.candidate.name)
            candidacy.generate_survey_token(
            )  # this does save too, since it logs
        if candidacy.survey_invite_posted == None:
            candidacy.survey_invite_posted = False
        log("Storing candidacy " + candidacy.seat.name + " " +
            candidacy.candidate.name)
        candidacies_by_key[key_name] = candidacy

        # record we still have this candidacy
        if key_name in to_be_marked_deleted:
            del to_be_marked_deleted[key_name]
    log("Putting all candidacies")
    put_in_batches(candidacies_by_key.values())

    # See which candidacies are left, i.e. are deleted
    for key_name, candidacy in to_be_marked_deleted.iteritems():
        log("Marking deleted " + candidacy.seat.name + " " +
            candidacy.candidate.name)
        candidacy.deleted = True
    log("Putting marked deleted candidacies")
    put_in_batches(to_be_marked_deleted.values())

    ######################################################################
    # Load from DemocracyClub

    fs = Seat.all().filter("frozen_local_issues =", True).fetch(100)
    while fs:
        for f in fs:
            log("  Seat is frozen to local issues changes: " + f.name)
            frozen_seats[f.key().name()] = f
        fs = Seat.all().filter("frozen_local_issues =",
                               True).filter('__key__ >',
                                            fs[-1].key()).fetch(100)
Exemplo n.º 20
0
 def clean_identifiers(self):
     data = self.cleaned_data['identifiers']
     return Party.validate_identifiers(data)
Exemplo n.º 21
0
 def index():
     result_obj = self.serialized_json_api_obj(Party.all())
     return self.json_response(result_obj)
Exemplo n.º 22
0
 def clean_identifiers(self):
     data = self.cleaned_data['identifiers']
     return Party.validate_identifiers(data)
Exemplo n.º 23
0
    def __create_party(self, attributes={}):
        party = Party.first_or_create(short_name=attributes["short_name"])

        if "full_name" in attributes and attributes["full_name"] is not None:
            party.full_name = attributes["full_name"]
            party.save()
def election_from_csv(filename):
    """
    Create an Election object from a csv file of election data.
    """

    election = None

    with open(filename, 'rb') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')

        # create an Election object
        election = Election()

        constituencies = {}
        parties = {}
        candidates = {}

        for row in reader:
            # extract the fields from the CSV data
            constituencyName = row[0]
            candidateName = row[1]
            partyName = row[2]
            voteCount = int(row[3])

            # reconcile the constituency
            if constituencyName not in constituencies:
                con = Constituency(constituencyName)
                constituencies[constituencyName] = con
            else:
                con = constituencies[constituencyName]

            # reconcile the party
            if partyName not in parties:
                par = Party(partyName)
                parties[partyName] = par
            else:
                par = parties[partyName]

            # reconcile the candidate
            if (candidateName, partyName, constituencyName) \
                    not in candidates:
                can = Candidate(candidateName,
                                par,
                                con,
                                voteCount)
                candidates[(candidateName,
                            partyName,
                            constituencyName)] = can
            else:
                raise ValueError(
                    """A candidate with the same details already exists""")

            # add the candidate to the constituency
            con.add_candidate(can)

            # add the candidate to the party
            par.add_candidate(can)

            # add the candidate to the election
            election.add_candidate(can)

    return election
Exemplo n.º 25
0
def w_party():
    if not validate_post():
        return '', 403

    party = request.json.get('party')
    if not party:
        return '', 204

    party_obj = Party.query.first() or Party()
    old_party_pids = [party_obj.get_pid(i) for i in range(6)]

    updated_pokemon = []
    updated_dexinfo = []

    with db.session.no_autoflush:
        for i, pokemon in enumerate(party + ([None] * (6 - len(party)))):
            pid = pokemon['header']['pid'] if pokemon else None
            party_obj.set_pid(i, pid)

            if pid:
                updated_current = False

                pokemon_obj = Pokemon.query.filter_by(
                    pid=pid).first() or Pokemon(
                        pid=pid, created_time=datetime.datetime.utcnow())
                old_pokedex_id = pokemon_obj.pokedex_id
                new_pokedex_id = pokemon['block_data']['pokedex_id']

                if old_pokedex_id and new_pokedex_id != old_pokedex_id:
                    old_dex_obj = PokedexInfo.query.filter_by(
                        pokedex_id=old_pokedex_id).first()
                    if old_dex_obj:
                        old_dex_obj.evolves_into_dexid = new_pokedex_id
                        db.session.add(old_dex_obj)
                        updated_dexinfo.append(old_dex_obj)

                if pokemon_obj.pokedex_id != new_pokedex_id:
                    pokemon_obj.pokedex_id = new_pokedex_id
                    updated_current = True

                for attr in ('ability', 'nature', 'held_item'):
                    if getattr(pokemon_obj,
                               '%s_id' % attr) != pokemon['block_data'][attr]:
                        setattr(pokemon_obj, '%s_id' % attr,
                                pokemon['block_data'][attr])
                        updated_current = True

                for attr in ('experience', 'nickname', 'move_1_id',
                             'move_2_id', 'move_3_id', 'move_4_id',
                             'move_1_pp', 'move_2_pp', 'move_3_pp',
                             'move_4_pp'):
                    if getattr(pokemon_obj,
                               attr) != pokemon['block_data'][attr]:
                        setattr(pokemon_obj, attr, pokemon['block_data'][attr])
                        updated_current = True

                for attr in ('level', 'hp', 'hp_max', 'attack', 'defense',
                             'speed', 'sp_attack', 'sp_defense'):
                    if getattr(pokemon_obj,
                               attr) != pokemon['battle_stats'][attr]:
                        setattr(pokemon_obj, attr,
                                pokemon['battle_stats'][attr])
                        updated_current = True

                if updated_current:
                    db.session.add(pokemon_obj)
                    updated_pokemon.append(pokemon_obj)

        new_party_pids = [party_obj.get_pid(i) for i in range(6)]

        party_composition_changed = new_party_pids != old_party_pids
        reserve_composition_changed = set(new_party_pids) != set(
            old_party_pids)

        if party_composition_changed:
            db.session.add(party_obj)

    if party_composition_changed or updated_pokemon or updated_dexinfo:
        db.session.commit()
        for pokemon_obj in updated_pokemon:
            socketio.emit('pokemon_changed', pokemon_obj.serialize())
        for dex_obj in updated_dexinfo:
            socketio.emit('pokedex_changed', dex_obj.serialize())
        if party_composition_changed:
            socketio.emit('party_composition_changed')
        if reserve_composition_changed:
            socketio.emit('reserve_composition_changed')

    forward_post('/w/party')
    return '', 204
Exemplo n.º 26
0
 def show_party(party_id):
     party = Party.find_or_fail(party_id)
     result_obj = self.serialized_json_api_obj(party)
     return self.json_response(result_obj)
Exemplo n.º 27
0
 def index():
     result_obj = self.serialized_json_api_obj(Party.all())
     return self.json_response(result_obj)
Exemplo n.º 28
0
 def show_party(party_id):
     party = Party.find_or_fail(party_id)
     result_obj = self.serialized_json_api_obj(party)
     return self.json_response(result_obj)
Exemplo n.º 29
0
def load_results():
    """Match election records to the existing election datasets."""
    logger.info("Matching election results...")

    with open("../wahlergebnisse/wahlergebnisse.json") as f:
        result_data = json.load(f)
    with open("../userdata/substitutions.json") as f:
        substitutions = defaultdict(list)
        substitutions.update(json.load(f))

    for occ in db.session.query(Election).all():
        dt = occ.date.date()
        occ_results = [
            o
            for o in result_data
            if o["territory"].lower().startswith(occ.territory.lower()[:2])
            and dateutil.parser.parse(o["date"]).date() == dt
        ]

        matched_results = set()

        if len(occ_results) == 0:
            logger.error("Didn't find results for {}. Removing from db..".format(occ))
            for th in occ.theses:
                for pos in th.positions:
                    db.session.delete(pos)
                db.session.delete(th)
            db.session.delete(occ)
        else:
            res = occ_results[0]

            if "preliminary" in res and res["preliminary"] == True:
                logger.warning("Marking {} as preliminary".format(occ))
                occ.preliminary = True
                yield occ

            parties = set([p.party for p in occ.theses[0].positions])
            for p in parties:
                options = [p.name.lower()] + list(map(str.lower, substitutions[p.name]))
                matches = [
                    (name, result)
                    for name, result in res["results"].items()
                    if name.lower() in options
                ]

                if len(matches) > 0:
                    for match in matches:
                        if match[0].lower() != p.name.lower():
                            logger.warning(
                                "Assigned WOM text from {} to election result of {} in {}".format(
                                    p, match[0], res["title"]
                                )
                            )
                        matched_results.add(match[0])
                        votes = match[1]["votes"] if "votes" in match[1] else None
                        yield Result(
                            election=occ,
                            party=p,
                            party_repr=match[0],
                            votes=votes,
                            pct=match[1]["pct"],
                            source_url=res["url"],
                            source_name="Tagesschau Wahlarchiv"
                        )
                else:
                    if occ.preliminary:
                        logger.info("{} missing vote count for  {}".format(occ, p))
                    else:
                        logger.error("No vote count for {} in {}".format(p, occ))

            # Add results missing in Wahl-o-Mat
            for p_name, match in res["results"].items():
                if p_name in list(matched_results):
                    continue

                # Try and assign a unified party instance to this election
                # result to merge parties that have changed their name over
                # time

                party = None
                if p_name in party_instances.keys():
                    party = party_instances[p_name]
                else:
                    for (name, subs) in substitutions.items():
                        if p_name in subs:
                            if name in party_instances.keys():
                                party = party_instances[name]
                                logger.info(
                                    "Linked statement {} to election result of '{}' in {}".format(
                                        party, p_name, res["title"]
                                    )
                                )
                            break

                if party is None:
                    party = Party(name=p_name)
                    party_instances[p_name] = party

                yield Result(
                    election=occ,
                    party_repr=p_name,
                    party=party,
                    votes=match["votes"] if "votes" in match else None,
                    pct=match["pct"],
                    source_url=res["url"],
                    source_name="Tagesschau Wahlarchiv",
                    wom=False,
                )
Exemplo n.º 30
0
from models import User, db, Party, Vote, Resturaunt
import random
from app import app

db.drop_all()
db.create_all()

me = User.create(email='*****@*****.**', name='david', password='******')
kynsi = User.create(email='*****@*****.**', name='kynsi', password='******')
chris = User.create(email='*****@*****.**', name='chris', password='******')
tori = User.create(email='*****@*****.**', name='tori', password='******')

valentine = Party.create(address="12248 Hunter's Knoll Dr",
                         city="Burleson",
                         state="Texas",
                         zip_code=76028,
                         leader_id=me.id,
                         name="Valentine's day dinner")

Resturaunt.get_resturaunts(party_id=valentine.id)

valentine.add_member(kynsi.id)

valentine.add_member(chris.id)

valentine.add_member(tori.id)

for member in valentine.members:
    for resturaunt in valentine.resturaunts:
        vote = True if random.randint(0, 1) else False
        new_vote = Vote.vote(member=member,