Пример #1
0
def new_record():
    new_artist = request.form.get('artist')
    new_title = request.form.get('title')
    # sprawdzanie czy ktoś zostawił puste pole
    if new_artist == '' or new_title == '':
        flash("Wypełnij pola!", 'danger')
        records = Record.query.all()
        return render_template('record-list.html', records=records)

    new_record = Record(title=new_title, artist=new_artist)
    api_check = new_record.get_additional()
    # sprawdzanie czy dany artysta/płyta są w zewnętrznym API
    if 'error' in api_check:
        flash("Nie znaleziono takiej pozycji. Podaj prawidłowe dane!",
              'warning')
        records = Record.query.all()
        return render_template('record-list.html', records=records)

    # sprawdzanie czy juz istnieje w naszej bazie
    record_check = Record.query.filter_by(title=new_title,
                                          artist=new_artist).first()
    if record_check is not None:
        flash("Dana pozycja już istnieje w bazie", 'warning')
        records = Record.query.all()
        return render_template('record-list.html', records=records)

    db.session.add(new_record)
    db.session.commit()
    return redirect('/records/')
Пример #2
0
    def testRecordAPIs(self):
        self.sensor1 = Sensor.Create(self.e, "000-100", self.st.key().id())
        self.sensor1.put()
        now = datetime.now()
        r1_ts = tools.unixtime(now)
        r = Record.Create(tools.unixtime(now), self.sensor1,
                          {'location': '51.5033640,-0.1276250'})
        r2 = Record.Create(
            tools.unixtime(now) + 1000, self.sensor1,
            {'location': '51.5033640,-0.1276250'})
        db.put([r, r2])

        # Test list
        params = self.__commonParams()
        params.update({'sensor_kn': "000-100"})
        result = self.get_json("/api/data", params)
        self.assertTrue(result['success'])
        self.assertEqual(len(result['data']['records']), 2)

        # Test detail
        params = self.__commonParams()
        result = self.get_json("/api/data/%s/%s" % ("000-100", r1_ts), params)
        self.assertTrue(result['success'])
        _r = result['data']['record']
        self.assertEqual(_r['sensor_kn'], "000-100")
        self.assertEqual(_r['ts'], r1_ts)
        self.assertEqual(
            _r['kn'], "%s_%s_%s" %
            (self.e.key().id(), self.sensor1.key().name(), int(r1_ts)))
Пример #3
0
def visit(url, rollno, idx):
    """
    This method visits the given site, fills the form, checks if a valid result is generated, adds the valid result 
    and the valid roll number to the valid dict and valid list respectively.

    :param idx:
    :param url: 
    :param rollno: 
    """
    try:
        # noinspection PyProtectedMember

        header = {
            'User-Agent': str(UA.random),
            "Accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": "www.fbise.edu.pk",
            "Origin": "https://www.fbise.edu.pk",
            "Referer": "https://www.fbise.edu.pk/res-hssc-II.php",
            "Upgrade-Insecure-Requests": "1",
        }
        res = post(url, rollno._asdict(), headers=header)
        if res.status_code != 200:
            Record(rollno=rollno[0], html="NULL", error=True, idx=idx)
        else:
            Record(rollno=rollno[0], html=res.text, error=False, idx=idx)
    except Exception as e:
        logger.error(str(e))
        Record(rollno=rollno[0], html="NULL", error=True, idx=idx)
Пример #4
0
 def update_room_data(self):
     url = self.api_url(self.room_designs)
     r = self.call(url)
     root = ElementTree.fromstring(r.text)
     for c in root[0][0]:
         record_id = c.get('RoomDesignId')
         Record.update_data('room', record_id, c)
Пример #5
0
    def save(self, record=None):
        if record:
            links = []
            if self.validated_data['gwc']:
                gwc_endpoints = [endpoint.strip() for endpoint in self.validated_data['gwc_endpoint'].split("^") if endpoint.strip()]
                for endpoint in gwc_endpoints:
                    links.append(
                        record.generate_ows_link(endpoint, 'GWC', self.validated_data['wms_version'])
                    )
            elif self.validated_data['wms']:
                links.append(
                    record.generate_ows_link(self.validated_data['wms_endpoint'], 'WMS', self.validated_data['wms_version'])
                )
            if self.validated_data['wfs']:
                links.append(
                    record.generate_ows_link(self.validated_data['wfs_endpoint'], 'WFS', self.validated_data['wfs_version'])
                )
            if record.service_type == "WMS":
                record.service_type_version = self.validated_data['wms_version']
            elif record.service_type == "WFS":
                record.service_type_version = self.validated_data['wfs_version']
            else:
                record.service_type_version = ""

            style_links = record.style_links
            resources = links + style_links

            Record.update_links(resources, record)
Пример #6
0
def rest(request):
	admins_email = ['*****@*****.**']
	content_to_sender = u"Dear %s,\n\nWe have received your application.Please do NOT reply this email directly.\n\nThanks,\nTech Team"
	content_to_admin = u"Received an application from %s %s at %s"
	receive_time_str = strftime("%H:%M:%S %Y-%m-%d", localtime())
	if request.META.has_key('CONTENT_TYPE'):
		info = request.META['CONTENT_TYPE'] 
		if info == 'application/json' and request.method == 'POST':
			data = json.loads(request.body) 
			form = RecordForm(data)

			if form.is_valid():
				r = Record(email = form.cleaned_data['email'],
							first_name = form.cleaned_data['first_name'],
							last_name = form.cleaned_data['last_name'],
							contact_number = form.cleaned_data['contact_number'],
							title = form.cleaned_data['title'],
							content = form.cleaned_data['content'],
							link = form.cleaned_data['link'])
				r.save()

				send_mail(u'Thanks for your application',
							content_to_sender % data['last_name'],
							'*****@*****.**',
							[data['email']])
				send_mail(u'Application Received from %s' % data['email'],
							content_to_admin % (data['last_name'],data['first_name'],receive_time_str),
							'*****@*****.**',
							admins_email)
				return HttpResponse('save successful')
		return HttpResponse('data invalid')	
	else:
		return HttpResponse('Please verify Header info')
Пример #7
0
 def return_records(self):  # pylint: disable=R0201
     """Returns all records in the database."""
     logger.info("Return records")
     if not self.request.params:
         logger.info("Returns all records")
         records = DBSession.query(Record).order_by(
             Record.timestamp.desc()).all()
     else:
         logger.info("Searching records by params")
         for key in self.request.params.keys():
             logger.info("Invalid Query")
             if key not in Record.search_queries:
                 return Response(status=400)
         logger.info("Processing date queries")
         start_date = self.request.params.get("start_date", Record.min_date)
         start_date = Record.get_timestamp(start_date)
         end_date = self.request.params.get("end_date", Record.max_date)
         end_date = Record.get_timestamp(end_date)
         records = (DBSession.query(Record).filter(
             Record.timestamp.between(start_date, end_date)).order_by(
                 Record.timestamp.desc()).all())
     if records:
         records_json = []
         for record in records:
             records_json.append(record.to_dict())
         return records_json
     return Response(status=204)
Пример #8
0
def record_view(request, game_id):
    logger.debug('enter record view')
    if request.method == 'POST':
        logger.debug('submit record post form')
        logger.debug(game_id)
        logger.debug(request.POST)
        record = Record(round=0,
                        score1=request.POST['score1'],
                        score2=request.POST['score2'],
                        score3=request.POST['score3'],
                        score4=request.POST['score4'])

        record.save()
        logger.debug('save record success')
        game = Game.objects.get(id=game_id)
        game.score1 += int(request.POST['score1'])
        game.score2 += int(request.POST['score2'])
        game.score3 += int(request.POST['score3'])
        game.score4 += int(request.POST['score4'])
        logger.debug(game)
        game.save()
        logger.debug('save game success')
    games = Game.objects.order_by('-start_dt')
    return render(request, 'record/record.html', {
        'games': games,
        'game_id': game_id
    })
Пример #9
0
def new_record(id):
    user = User.query.get_or_404(id)
    record = Record(user=user)
    record.import_data(request.json)
    db.session.add(record)
    db.session.commit()
    return jsonify({}), 201, {'Location': record.get_url()}
Пример #10
0
    def save(self, record=None):
        if record:
            links = []
            if self.validated_data['gwc']:
                links.append(
                    json.loads(
                        Record.generate_ows_link(
                            self.validated_data['gwc_endpoint'], 'WMS', None,
                            record)))
            if self.validated_data['wms']:
                links.append(
                    json.loads(
                        Record.generate_ows_link(
                            self.validated_data['wms_endpoint'], 'WMS',
                            self.validated_data['wms_version'], record)))
            if self.validated_data['wfs']:
                links.append(
                    json.loads(
                        Record.generate_ows_link(
                            self.validated_data['wfs_endpoint'], 'WFS',
                            self.validated_data['wfs_version'], record)))

            if record.service_type == "WMS":
                record.service_type_version = self.validated_data[
                    'wms_version']
            elif record.service_type == "WFS":
                record.service_type_version = self.validated_data[
                    'wfs_version']
            else:
                record.service_type_version = ""

            style_resources = record.style_resources
            resources = links + style_resources

            Record.update_links(resources, record)
Пример #11
0
def main():
    template_root = join(dirname(realpath(__file__)), 'templates')

    DB_CONNECTION.connect()

    DB_CONNECTION.create_tables((Record, ), safe=True)

    Record.delete().execute()
    Record.insert_many(({} for _ in range(500))).execute()

    DB_CONNECTION.close()

    DB_CONNECTION.set_allow_sync(False)

    try:
        application = Application()
        jinja2_setup(application, loader=FileSystemLoader(template_root))

        application.router.add_get('/', raw_response_handle)
        application.router.add_get('/template', html_response_handle)
        application.router.add_get('/database', database_response_handle)
        application.router.add_get('/service', service_response_handle)

        run_app(application)
    except Exception as exception:
        # TODO: error notification logic
        raise exception
    finally:
        DB_CONNECTION.close()
Пример #12
0
 def update_collection_data(self):
     url = self.api_url(self.collections)
     r = self.call(url)
     root = ElementTree.fromstring(r.text)
     for c in root[0][0]:
         record_id = c.get('CollectionDesignId')
         Record.update_data('collection', record_id, c)
Пример #13
0
def add_record(release):
    from models import Record, Artist, Track
    release_discogs_id = release.id
    try:
        # Check if we already have this album
        existing = Record.objects.get(discogs_id=release_discogs_id)
        return existing
    except Record.DoesNotExist:
        # Process record
        record_title = release.title
        if (len(record_title.split('- '))>1):
            record_title = record_title.split('- ')[1]
        record = Record(discogs_id = release_discogs_id, title = record_title, year = release.year, thumb = release.thumb, notes = release.notes)
        record.save()

        # Process artists
        for release_artist in release.artists:
            artist = Artist(discogs_id=release_artist.id, name=release_artist.name)
            artist.save()
            record.artists.add(artist)

        # Process tracklist
        for release_track in release.tracklist:
            track = Track()
            track.position = release_track.position
            track.title = release_track.title
            track.duration = release_track.duration
            track.save()
            record.tracklist.add(track)

        record.save()
        return record
Пример #14
0
 def update_char_data(self):
     url = self.api_url(self.char_designs)
     r = self.call(url)
     root = ElementTree.fromstring(r.text)
     for c in root[0][0]:
         record_id = c.get('CharacterDesignId')
         Record.update_data('char', record_id, c)
Пример #15
0
def get_doc_list(folder_name):
    corpus = []
    cursor = Record().get_knowledgebases()
    for row in cursor.fetchall():
        line = row[0] + ' ' + row[1]
        corpus.append(line)
    return corpus
Пример #16
0
def thisdiary(friend_diary):
    # friendID,diarychoose=friend_diary
    info = friend_diary.split(",")
    diarychoose = info[1]

    cur_user = info[0]
    form = CommentForm()
    diary_show = Record(cur_user)
    diary = diary_show.display_single(diarychoose)
    diary = diary[0]
    comment_show = Comment()
    comments = comment_show.show_group_dialog(diarychoose)
    if form.validate_on_submit():
        comment = request.form.get('comment', None)
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        record_id = diarychoose
        comment_new = Comment()
        comment_new.create_dialog(record_id, current_user.user_email, time,
                                  comment)
        friend_diary = cur_user + "," + diarychoose
        return redirect(
            request.args.get('next')
            or url_for('thisdiary', friend_diary=friend_diary))
    return render_template('thisdiary.html',
                           title="Sign In",
                           form=form,
                           diary=diary,
                           comments=comments,
                           user_info_global=user_info_global)
Пример #17
0
 def update_item_data(self):
     url = self.api_url(self.item_designs)
     r = self.call(url)
     root = ElementTree.fromstring(r.text)
     for c in root[0][0]:
         record_id = c.get('ItemDesignId')
         Record.update_data('item', record_id, c, ['FairPrice', 'MarketPrice'])
Пример #18
0
    def save(self,record=None):
        if record:
            links = []
            if self.validated_data['gwc']:
                links.append(
                    json.loads(Record.generate_ows_link(self.validated_data['gwc_endpoint'],'WMS',None,record))
                )
            if self.validated_data['wms']:
                links.append(
                    json.loads(Record.generate_ows_link(self.validated_data['wms_endpoint'],'WMS',self.validated_data['wms_version'],record))
                )
            if self.validated_data['wfs']:
                links.append(
                    json.loads(Record.generate_ows_link(self.validated_data['wfs_endpoint'],'WFS',self.validated_data['wfs_version'],record))
                )
                
            if record.service_type == "WMS":
                record.service_type_version = self.validated_data['wms_version']
            elif record.service_type == "WFS":
                record.service_type_version = self.validated_data['wfs_version']
            else:
                record.service_type_version = ""

            style_resources = record.style_resources
            resources = links + style_resources

            Record.update_links(resources,record)
Пример #19
0
def create_records(pin_num):
    with open('fixtures/rel_humidity_data.csv') as csvfile:
        reader = csv.reader(csvfile)
        f = reader.__next__()
        delay = dt.now().timestamp() - int(f[0])

        record = Record(pin_num, int(f[2]), int(f[0]) + delay)
        db_session.add(record)

        for row in reader:
            record = Record(pin_num, int(row[2]), int(row[0]) + delay)
            db_session.add(record)

        db_session.commit()
        db_session.close()

    with open('fixtures/dht11_data.csv') as csvfile:
        reader = csv.reader(csvfile)
        f = reader.__next__()
        delay = dt.now().timestamp() - int(f[0])

        record = DHT11Record(int(f[1]), int(f[2]), int(f[0]) + delay)
        db_session.add(record)

        for row in reader:
            r = DHT11Record(int(row[1]), int(row[2]), int(row[0]) + delay)
            db_session.add(r)

        db_session.commit()
        db_session.close()
Пример #20
0
 def add_diagnosis(self, login_patient, diagnosis):
     new_diagnosis = Record(rec_login=login_patient, rec_diag=diagnosis)
     if login_patient and diagnosis:
         new_diagnosis.save_to_db()
         return 'doctor_space'
     else:
         return "Произошла ошибка!"
Пример #21
0
def gong(request):
    user = "******" % request.POST.get("user_name", "somebody")
    reason = request.POST.get("text", "Gonged stuff!")

    slack_message('slack/gonged.slack', {
        'user': user,
        'reason': reason
    })

    attachments = [
        {
            'author_name': user,
            'title': reason,
            'image_url': 'https://curriculum.code.org/images/gong.gif',
            'color': '#00adbc'
        }
    ]
    payload = {
        "response_type": "in_channel",
        "attachments": attachments,
    }

    record = Record(user=user, reason=reason)
    record.save()

    return Response(payload, content_type='application/json')
Пример #22
0
class RecordForm(forms.Form):
    def __init__(self, instance=None, *args, **kwargs):
        if instance is None:
            self.instance = Record()
        else:
            self.instance = instance
            kwargs['initial'] = self.instance.data

        super(RecordForm, self).__init__(*args, **kwargs)

    def save(self, view, commit=True):
        data = {}

        widgets = Widget.objects.filter(
            tab__form=view.appform.form).select_subclasses()
        widgets = {w.name: w for w in widgets}

        for key, value in self.cleaned_data.items():
            if isinstance(widgets[key], RecordsWidget):
                value = [v.pk for v in value]

            #if value and hasattr(value, '__iter__'):
            #    ct = ContentType.objects.get_for_model(value.model)
            #    value = [(ct.natural_key(), v.pk) for v in value]

            data[key] = value

        self.instance.data = data

        if commit:
            self.instance.save()

        return self.instance
Пример #23
0
def delete(instance, obj_id):
    obj = Record().give_child(instance)
    obj = obj.get_by_id_or_new(obj_id)
    obj.delete()
    if not request.is_xhr:
        return redirect('index/'+repr(obj))
    else:
        return "it ok"
Пример #24
0
    def __init__(self, instance=None, *args, **kwargs):
        if instance is None:
            self.instance = Record()
        else:
            self.instance = instance
            kwargs['initial'] = self.instance.data

        super(RecordForm, self).__init__(*args, **kwargs)
Пример #25
0
def record_user(request,user):
	user = User.objects.get(id=user)
	summary = Record.summary_by_user(user)
	records = Record.list_by_user(user)

	context = {'records':records,
		'summary':summary,}
	
	return render_to_response('user.html', context,context_instance=RequestContext(request))
Пример #26
0
 def get_user_rankings(self, request):
     """Get user rankings"""
     if isinstance(request.number_of_results, int):
         _number_of_results = request.number_of_results
         records = Record.query().order(Record.wins).fetch(limit=_number_of_results)
         return RecordForms(items=[record.to_form() for record in records])
     else:
         records = Record.query().order(Record.wins)
         return RecordForms(items=[record.to_form() for record in records])
Пример #27
0
 def update_data(self, uri, attr, record_name):
     """Update data and save records
     """
     url = self.api_url(uri)
     r = self.call(url)
     root = ElementTree.fromstring(r.text)
     for c in root[0][0]:
         record_id = c.get(attr)
         Record.update_data(record_name, record_id, c)
Пример #28
0
 def __get_record(self, session_id, event_list):
     record = None
     for event in event_list:
         if event['event_type'] == '@@mgStartMixRecord':
             if record:
                 logging.error(u'分析方法错误,%s有多个mgStartMixRecord事件' % session_id)
             else:
                 record = Record(session_id, hex(int(event['call_id'])), hex(int(event['res_id'])), event['@timestamp'], event['save_path'], event['result'])
     if not record:
         return None
     for event in event_list:
         if event['event_type'] == 'MediaID':
             record.media_id = event['media_id']
             record.record_type = event['record_type']
             if event['tac'] == '0':
                 record.end_time = event['@timestamp']
             elif event['tac'] == '1':
                 record.start_time = event['@timestamp']
             else:
                 logging.error(u'%s无法识别的录音tac' % (session_id, event['tac']))
         else:
             pass
     if not record:
         pass
     elif record.result == 'GATEWAY_SUCCESS':
         if record.end_time:
             record.result = 'RECORD_SUCCESS'
         else:
             record.result = 'NOT_RECORD_END'
     else:
         record.end_time =record.start_time
     return record
Пример #29
0
    def testExpressionParsing(self):
        from models import Record
        r = Record()
        x = 5
        y = -2
        z = 3.5
        r.setColumnValue("x", x)
        r.setColumnValue("y", y)
        r.setColumnValue("z", z)
        volley = [
            ["1 + 1", (1 + 1) ],
            ["1 + 1 + 5", (1 + 1 + 5) ],
            ["2 * 8 + 3", (2*8) + 3 ],
            ["4 + 5 * 2", 4 + (5*2)],
            ["2^3", (pow(2,3)) ],
            ["(8/2)*3 + 9", ((8/2)*3 + 9) ],
            ["[x]^2", (pow(x,2))],
            ["SQRT([x]^2 + [y]^2)", ( math.sqrt(pow(x,2)+pow(y,2)) )],
            ["5 > 2", True],
            ["5 > 6", False],
            ["(3*5) < 20", True],
            ["[x] > 100", False],
            ["(3*5) < 20 AND [x] > 100", False],
            ["(3*5) < 20 AND [x] > 0 AND [x] > 1", True],
            ["1==1 OR 1==3 AND 2==0", True],
            ["(1==1 OR 1==3) AND 2==2", True],
            ["(1==2 AND 1==3) OR 2==2", True],
            ["(1==1 OR 1==1) AND 1==0", False],
            ["1==1 OR 1==1 AND 1==0", True], # And first
            ["1==1 OR (1==1 AND 1==0)", True],
            ["1 == 2 OR [x] > 100 OR [x] > 1", True],
            ["1==2 OR 1==1 OR 1==4 OR 1==5", True],
            ["SQRT([x]^2 + [y]^2)", ( math.sqrt(pow(x,2)+pow(y,2)) )],
            ["SQRT([x]^2 + [y]^2 + 8^2)", ( math.sqrt(pow(x,2)+pow(y,2)+pow(8,2))) ],
            ["SQRT([x]^2 + [y]^2 + [z]^2)", ( math.sqrt(pow(x,2)+pow(y,2)+pow(z,2))) ]
        ]

        for v in volley:
            expr = v[0]
            target = v[1]
            tick = datetime.now()
            ep = ExpressionParser(expr, verbose=True)
            result = ep.run(r)
            tock = datetime.now()
            diff = tock - tick
            ms = diff.microseconds/1000
            logmessage = "%s took %d ms" % (expr, ms)
            if ms > 100:
                logmessage += " <<<<<<<<<<<<<<<<<<<<<<<<<<< SLOW OP!"
            print logmessage
            self.assertEqual(result, target)
Пример #30
0
def get_upcoming(channel_slug):
    channel = Channel.query.filter_by(slug=channel_slug).first()
    if not channel:
        return jsonify({"error": "404 - Not found"})
    q = Record.query.filter_by(channel_id=channel.id, executed=True).order_by(
        Record.id.desc()).limit(20)
    results = Record.query.filter_by(executed=False,
                                     channel_id=channel.id).all()
    if not results:
        if len(channel.favorites) != 0:
            rand = random.randrange(0, len(channel.favorites))
            random_rec = channel.favorites[rand]
            if random_rec:
                entry = Record(channel.id, random_rec.id)
                channel.update_id += 1
                db.session.add(entry)
                db.session.commit()
                results = [entry]
        else:
            random_rec_q = Record.query.filter_by(channel_id=channel.id)
            rand = random.randrange(0, random_rec_q.count())
            random_rec = random_rec_q.all()[rand]
            if random_rec:
                entry = Record(channel.id, random_rec.video.id)
                channel.update_id += 1
                db.session.add(entry)
                db.session.commit()
                results = [entry]
    current = Record.query.filter_by(executed=True,
                                     channel_id=channel.id).order_by(
                                         Record.id.desc()).first()
    data = {
        "upcoming":
        map(
            lambda x: {
                'code': x.video.code,
                'r_id': x.id,
                'title': x.video.title,
                'duration': x.video.duration,
                'id': x.video.id,
                "favorite": x.video in channel.favorites
            }, results),
        "volume":
        channel.volume,
    }
    if current:
        data['current_title'] = current.video.title
    else:
        data['current_title'] = "no playback detected"
    return jsonify(data)
Пример #31
0
async def add(ctx, content: str):
    try:
        content = ctx.message.content
        content = content.lstrip('+add')
        contentArray = content.split('|')
        for s in contentArray:
            s = s.strip()
        
        title = contentArray[0]
        content = contentArray[1]
        tags = contentArray[2]

        rows = [[content], [tags]]
        header = [title]
        info = tabulate(rows, header)

        record = Record(title=title, content=content)

        session.add(record)
        session.commit()

        await bot.say('New Record Added:\n```\n' + info + '```')
    
    except Exception as e:
        await bot.say('Could not complete your command')
        print(e)
Пример #32
0
    def get(self):
        """Handles GET."""

        height = self.request.GET.get('height', 600)
        width = self.request.GET.get('width', 1000)
        num = int(self.request.GET.get('num', 100))
        if num > 1000:
            num = 1000

        records = Record.all().order('-num_iter').order('-date').fetch(num)

        values = [r.estimated_pi for r in records]

        num_rows = len(values)

        rows = []

        for i in range(num_rows):
            rows.append("%i, 0, %i" % (i, i+1))
            rows.append("%i, 1, %f" % (i, values[i]))

        if values:
            pi = sum(values)/num_rows
        else:
            pi = 'unknown'

        self.response.out.write(template.render('chart.html', locals()))
Пример #33
0
    def add_record(self, data):
        sipping_ids = []
        for sipping in data["sipping"]:
            if not self._object_is_empty(sipping):
                sipping_ids.append(self._add_sipping(sipping))

        en_ids = []
        for en in data["EN"]:
            if not self._object_is_empty(en):
                en_ids.append(self._add_en(en))

        record = Record(patient=data["patient"],
                        date_from=data["dateFrom"],
                        date_to=data["dateTo"],
                        stool=data["stool"],
                        vomit=data["vomit"],
                        appetite=data["appetite"],
                        mucositis=data["mucositis"],
                        nausea=data["nausea"],
                        ration=data["ration"],
                        sipping=sipping_ids,
                        EN=en_ids,
                        components=data["components"],
                        interval=data["interval"],
                        needs=data["needs"],
                        doctor=data["doctor"])

        self.session.add(record)
        self.session.commit()
Пример #34
0
def update(POST):
    player_one = Player.objects.get(pk=int(POST['player_one']))
    player_one_score = int(POST['player_one_score'])
    player_two = Player.objects.get(pk=int(POST['player_two']))
    player_two_score = int(POST['player_two_score'])

    record = Record(date=datetime.datetime.now(), player_one_id=player_one.id, player_one_score=player_one_score, player_two_id=player_two.id, player_two_score=player_two_score)
    record.save()

    if player_one.ELO > player_two.ELO:
        expected_one = get_Expected(player_one.ELO, player_two.ELO)
    else:
        expected_one = 1 - get_Expected(player_two.ELO, player_one.ELO)

    update_player(player_one, player_one_score, player_two, player_two_score, expected_one)
    update_player(player_two, player_two_score, player_one, player_one_score, 1-expected_one)
Пример #35
0
def index():
    if request.method == 'GET':
        place = request.args.get('place')
        dfro = request.args.get('date_start')
        dend = request.args.get('date_end')
        error = 0
        logging.info(
            'The inputs from the user has been recieved on the server side')
        if place is not None:
            r = result(place)
            if (dfro is not '' and dend is not ''):
                r = result(place, dfro, dend)

            if r != 0:
                context = dict()
                context['city'] = r['city']
                context['temp'] = r['temp']
                context['max_temp'] = r['max_temp']
                context['min_temp'] = r['min_temp']
                context['pressure'] = r['pres']
                context['datetime'] = r['datetime']

                if request.args.get('btnSave') is not None:
                    record = Record(context['city'], context['temp'],
                                    context['max_temp'], context['min_temp'],
                                    context['pressure'], context['datetime'])
                    db.session.add(record)
                    db.session.commit()
                return render_template('/result.html', context=context)
            else:
                error = "Connectivity Issue.. Please check your internet connectivity!!!"

    return render_template('/index.html', error=error)
Пример #36
0
    def testNonSaneFutureRecords(self):
        uri = "/%s/inbox/json/%s" % (self.e.key().id(), TEST_SENSOR_ID)
        lat = 1.3
        lon = 36.9
        MOVE_SIZE = 0.01
        N_POINTS = 10
        DELAY_SECS = 1
        now = datetime.now()

        # Populate dummy data with random moves
        data = []
        for x in range(N_POINTS):
            now += timedelta(seconds=DELAY_SECS)
            lat += (random.random() - 0.5) * MOVE_SIZE
            lon += (random.random() - 0.5) * MOVE_SIZE
            loc = "%s,%s" % (lat, lon)
            data.append({
                'timestamp':
                tools.unixtime(dt=now) +
                1000 * 60 * 60 * 24 * 30,  # Non-sane (1 month in future)
                'location':
                loc
            })
        last_loc = loc
        body = json.dumps(data)
        response = self.post(uri, body)
        self.assertEqual(response.status_int, 200)
        content = json.loads(response.normal_body)
        self.assertTrue(content['success'])
        self.assertEqual(content['data']['count'], N_POINTS)

        # Fetch created records from db
        records = Record.Fetch(self.geosensor1)
        self.assertEqual(len(records), 0)  # No records saved, all non-sane
Пример #37
0
 def __createNewRecords(self,
                        data,
                        first_dt=None,
                        interval_secs=3,
                        sensor=None):
     if not sensor:
         sensor = self.vehicle_1
     now = first_dt if first_dt else datetime.now()
     records = []
     N = len(data.values()[0])
     for i in range(N):
         _r = {}
         for column, vals in data.items():
             _r[column] = vals[i]
         now += timedelta(seconds=interval_secs)
         r = Record.Create(tools.unixtime(now),
                           sensor,
                           _r,
                           allow_future=True)
         records.append(r)
     db.put(records)
     sensor.dt_updated = datetime.now()
     sensor.put()
     logging.debug("Created %d records" % len(records))
     if records:
         return records[-1].dt_recorded  # Datetime of last record created
     else:
         return None
Пример #38
0
def add(channel_slug):
    data = json.loads(request.data.decode())
    id = data["id"]
    errors = []
    if len(id) != 11:
        errors.append("Add a youtube id not a link.")
        return jsonify({"error": errors})

    channel = Channel.query.filter_by(slug=channel_slug).first()
    if not channel:
        return "404 - Not found"

    # see if video exists if it doesnt make a new one
    video = Video.query.filter_by(code=id).first()
    if not video:
        url = 'http://gdata.youtube.com/feeds/api/videos/{}?alt=json&v=2'.format(
            id)
        title_data = json.loads(urllib.urlopen(url).read())
        duration = title_data['entry']['media$group']['media$content'][0][
            'duration']
        title = title_data['entry']['title']['$t']
        video = Video(id, title=title, duration=duration)
        db.session.add(video)
        db.session.commit()
    try:
        record = Record(channel.id, video.id)
        db.session.add(record)
        db.session.commit()
        return jsonify({"succes": True})
    except:
        errors.append("Unable to add item to database.")
        return jsonify({"error": errors})
Пример #39
0
def render_review_page():
  """
  Render the review page.
  """
  title = 'Review'
  pending = Record.get_all_pending_records()
  return render_template('review.html', page_title=title, pending=pending)
Пример #40
0
 def fetch(self) -> Iterable[Record]:
     url = f'https://{self.host}.loverad.io/search.json'
     end = datetime.datetime.now(tz=BERLIN_TIME)
     start = end - HOUR
     params: RequestParams = {
         'station': self.station,
         'start': start.isoformat(),
         'end': end.isoformat(),
     }
     resp = requests.get(url, params=params)
     assert resp.ok
     body = resp.json()
     found = body['result']['found']
     print(f'Found {found} records')
     for record in body['result']['entry']:
         timestamp = record['airtime']
         assert record['song']['found'] == '1', record['song']
         [song] = record['song']['entry']
         song_title = song['title']
         # This is potentially a very bad assumption, that there will be 1
         # artist?
         [artist] = song['artist']['entry']
         artist_name = artist['name']
         yield Record(
             timestamp=datetime.datetime.fromisoformat(timestamp),
             title=song_title,
             artist=artist_name)
Пример #41
0
def instantiate_and_form(request, instance, obj_id=None):
    """
    Abstracts common operations from actions add/<instance>, edit/<instance>.
    Instantiates blank model object obj by it's string name (i. e.
    instance=book will produce obj=Book()). Instantiates corresponding
    WTForm model_form object form. If obj_id provided, tries to populate
    obj with database data.
    Populates form with request.from data (if any). Than tries to modify
    obj with data in form. Returns ready to use obj, form to caller.
    """
    obj = Record().give_child(instance)
    form = obj.give_form()
    obj = obj.get_by_id_or_new(obj_id)
    form = form(request.form, obj=obj)
    obj.populate_with(form)
    return obj, form
Пример #42
0
def post():
    try:
        cdr = xmltodict.parse(request.data)

        if isinstance(cdr['records']['record'], list):
            for record in cdr['records']['record']:
                instance = getattr(cdrs, str(record['@type']))(record)
                Record.create(data=json.dumps(instance.__dict__))
        else:
            instance = getattr(cdrs, str(cdr['records']['record']['@type']))(
                cdr['records']['record'])
            Record.create(data=json.dumps(instance.__dict__))
        return ('', 204)
    except:
        print('Parser failure!')
        return ('', 204)
Пример #43
0
def record_user_road(request,user,road):
	user = User.objects.get(id=user)
	records = Record.objects.filter(user=user,road=road)
	summary = Record.summary_by_user_road(user,road)
	context = {'user':user,
		'records':records,
		'summary':summary,}
	return render_to_response('record-user-road.html', context,context_instance=RequestContext(request))
Пример #44
0
def collection_dump(user, identifier, stream=None, prefix=None):

    # export collection
    collection = filter_by_access(user, Collection).get(id=identifier)

    # export collection items and records
    collectionitems = list(
        CollectionItem.objects
        .select_related('record', 'collection')
        .filter(collection__id=identifier)
    )
    ids = [collectionitem.record_id for collectionitem in collectionitems]
    records = list(Record.filter_by_access(user, *ids).filter(owner=None))
    ids = [record.id for record in records]
    collectionitems = [collectionitem for collectionitem in collectionitems
                       if collectionitem.record_id in ids]

    # export all fieldvalues
    fieldvalues = FieldValue.objects.select_related('record', 'field').filter(
        record__id__in=ids)

    used_fields = set(fieldvalue.field_id for fieldvalue in fieldvalues)

    # export all used fields
    fields = list(Field.objects.filter(id__in=used_fields).distinct())

    # export equivalent fields
    more = True
    while more:
        eq_ids = set(
            id
            for field in fields
            for id in field.equivalent.values_list('id', flat=True)
            if id not in used_fields
        )
        more = len(eq_ids) > 0
        if more:
            eq_fields = Field.objects.filter(id__in=eq_ids)
            fields.extend(eq_fields)
            used_fields = used_fields.union(eq_ids)

    # export all used standards
    standards = MetadataStandard.objects.filter(id__in=set(
        field.standard_id for field in fields if field.standard_id
    ))

    objects = [collection]
    objects.extend(standards)
    objects.extend(fields)
    objects.extend(collectionitem.record for collectionitem in collectionitems)
    objects.extend(collectionitems)
    objects.extend(fieldvalues)

    serializer = RenamingSerializer(prefix)
    kwargs = dict()
    if stream:
        kwargs['stream'] = stream
    return serializer.serialize(objects, use_natural_keys=True, **kwargs)
Пример #45
0
def home(request):
	records = Record.list()
	total_times = int(0)
	for x in records:
		total_times += x['times']
	summary = {'user_num':User.objects.all().count,
	'total_times':total_times}
	context = {'records':records,'summary':summary,}
	return render_to_response('index_list.html', context,context_instance=RequestContext(request))
Пример #46
0
def time_step2(request):
    _ip = request.POST["IP"]
    _time_step2 = request.POST["Time_step2"]

    try:
        record = Record.objects(ip=_ip)
    except DoesNotExist:
        return HttpResponse(status=400)
    record.time_step2 = str(_time_step2)
    record.save()
Пример #47
0
def import_csv(request):
    ret={}
    import csv
    reader = csv.reader(open('programming-sample.tab', 'rb'))
    for index,row in enumerate(reader):
        if index >0:
            m=int(row[1])
            d=int(row[2])
            if m>12:
                my_date= datetime.date(2012,m-12,d)
            else:
                my_date= datetime.date(2011,m,d)
                
            r=Record(body=row[3],title=row[0], date=my_date)
            r.save()
        #~ print 'Month: ' + row[1]
        #~ print 'Day: ' + row[2]
    
    return render_to_response('records/importing.html', ret)
Пример #48
0
def record_preview(request, id):
    record = Record.get_or_404(id, request.user)
    return render_to_response(
        'data_previewrecord.html',
        {
            'record': record,
            'none': None,
        },
        context_instance=RequestContext(request)
    )
Пример #49
0
    def create_user(self, request):
        """Create a User"""
        # Checks if user provided user name exists in database
        if User.query(User.name == request.user_name).get():
            raise endpoints.ConflictException(\
                    'A User with that name already exists!')

        # Creates new player record and user 
        # based on user inputed name and email
        user = User(name=request.user_name, 
                    email=request.email)
        user.put()

        record = Record(user=user.key,
                        wins=0,
                        loses=0)
        record.put()

        return StringMessage(message='User {} created!'.format(request.user_name))
Пример #50
0
def check_ip(request):
    try:
        exp = Exp.objects(onlyKey=1)
    except DoesNotExist:
        exp = Exp()
        exp.save()

    _ip = request.POST["IP"]
    try:
        record = Record.objects(ip=_ip)
    except DoesNotExist:
        exp.count += 1
        exp.save()
        record = Record(ip=_ip, seqNo=exp.count)
        record.save()

    if record.time_end is None:
        return HttpResponse(status=200)
    else:
        return HttpResponse(status=400)
Пример #51
0
 def get(self, publisher_name, collection_name):
     publisher = Publisher.get_by_urlname(publisher_name)
     collection = Collection.get_by_urlname(collection_name, publisher.key)
     logging.info(str(collection))
     records = Record.all_by_collection(collection.key)
     response = dict(
         publisher=simplejson.loads(publisher.json),
         collection=simplejson.loads(collection.json),
         records=[simplejson.loads(x.record) for x in records])
     self.response.headers["Content-Type"] = "application/json"
     self.response.out.write(simplejson.dumps(response))
Пример #52
0
def approve_requests():
  """
  Approve or reject the requests as specified by request_id.

  1) Approved requests are mapped from a request_id to the approved value of the request.
  2) Rejected requests are identified by a request_id only.
  """
  processed = []
  approved = json.loads((request.form['approved']))
  for request_id in approved:
    value = float(approved[request_id])
    record_id = Record.approve_request(int(request_id), value)
    processed.append(record_id)

  rejected = request.form['rejected'].split(',')
  for request_id in rejected:
    if request_id:
      record_id = Record.reject_request(request_id)
      processed.append(record_id)

  return jsonify(success=processed)
Пример #53
0
def showQuestion(request):
    q=Question.objects.filter(id=request.session['qid'])[0]
    #u=User.objects.filter(id=request.session['uid'])[0]
    #request.session['qid']=q.id
     #记录日志
    record=Record()
    record.uid=request.session['uid']
    record.qid=request.session['qid']
    record.result=True
    record.save()

    request.session['answer']=q.answer
    request.session['explain']=q.qexplain

    # 显示最新的和最热的几条讨论
    discuss_new=Discuss.objects.filter(qid=request.session['qid']).order_by('-date')[0:10]
    discuss_hot=Discuss.objects.filter(qid=request.session['qid']).order_by('-support')[0:10]

    #增加一个随机验证码
    if random.randint(1,80)==2:
        request.session['next_verify']=2
    #不同的题型,出现相应不同的模板
    return render_to_response('question_with_base.html', {'q' : q,\
            'includeQuestion':'question%d.html'%(q.qtype),'user':request.session,\
            'discuss_new':discuss_new,'discuss_hot':discuss_hot} )
Пример #54
0
 def checkAccess(self, record, reader, writer, manager, owner, admin, user=False):
     self.assertEqual(reader, Record.filter_by_access(self.collectionreader, record.id).count() == 1)
     self.assertEqual(writer, Record.filter_by_access(self.collectionwriter, record.id).count() == 1)
     self.assertEqual(manager, Record.filter_by_access(self.collectionmanager, record.id).count() == 1)
     self.assertEqual(owner, Record.filter_by_access(self.owner, record.id).count() == 1)
     self.assertEqual(admin, Record.filter_by_access(self.admin, record.id).count() == 1)
     self.assertEqual(user, Record.filter_by_access(self.user, record.id).count() == 1)
Пример #55
0
def commit_request():
  """
  API endpoint used by the front-end to commit a new merit request in ther records database
  """
  name = request.form['name']
  justification = request.form['justification']
  pledges = request.form['pledges'].split(',')
  suggested_value = request.form['suggestedValue']
  now = datetime.date.today()

  for pledge_id in pledges:
    record_id = Record.add_record(name, now, suggested_value, justification, pledge_id)
  return 'Request Successfully Submited'
Пример #56
0
    def save(self, raw_record):
        record, created = self.__model__.get_or_create(id=raw_record.id)

        last_revision = 0
        if not created:
            last_revision = self.services.last_revisions.record_last_revision(
                record).version + 1

        data = raw_record.model_fields(record=record, version=last_revision)
        new_record_revision = self.services.revisions.create(**data)

        entities = []
        for raw_entity in raw_record.entities:
            raw_entity_model_fields = raw_entity.model_fields(
                revision=new_record_revision)
            entities.append(raw_entity_model_fields)

        if entities:
            with self.services.db.atomic():
                self.services.meta.__model__.insert_many(entities).execute()

        Record.update(frequency=record.frequency + 1).where(
            Record.id == record.id).execute()
Пример #57
0
def get_pledge_report(pledge):
  """
  Render the merit report for the given pledge
  """
  title = pledge
  pledge_info = Pledge.get_pledge_by_name(pledge)

  pledge_id = pledge_info.id
  total = pledge_info.value
  records = Record.get_records_by_pledge(pledge_id)

  approved = [r for r in records if r.approved]
  pending = [r for r in records if not r.reviewed]
  rejected = [r for r in records if r.reviewed and not r.approved]
  return render_template('pledge.html', page_title=title, approved=approved, pending=pending, rejected=rejected, pledge_total=total)
Пример #58
0
def new_user(request):
    _ip = request.POST["IP"]
    _name = request.POST["Name"]
    _gender = request.POST["Gender"]
    _age = request.POST["Age"]
    _occupation = request.POST["Occupation"]
    _email = request.POST["Email"]

    try:
        record = Record.objects(ip=_ip)
    except DoesNotExist:
        return HttpResponse(status=400)
    record.name = str(_name)
    record.gender = str(_gender)
    record.age = int(_age)
    record.occupation = str(_occupation)
    record.email = str(_email)
    record.save()