示例#1
0
    def post(self):
        isajax = self.request.get('isajax')
        phone = self.request.get('phone')
        msg = self.request.get('msg')
        contact_name = self.request.get('contact_name')

        user = users.get_current_user()
        email = user.email().lower()
        q = Token.query(Token.email == email)
        token = q.get()
        status = 100
        hist=''
        logging.debug(email + ' ' + phone + ' ' + msg + ' ' + contact_name)
        if token:
            status = 101
            if len(phone) and len(msg):
                status = 200
                hist = History(email=email, msg=msg, phone=phone, contact_name = contact_name)
                hist.put()
                airship.push({
                    "android": {
                         "extra": {"msgid": str(hist.key.id()), "phone": phone, "msg":msg}
                    }
                }, apids=[token.apid])
                id = hist.key.id()
                hist = hist.to_dict()
                hist['created']=hist['created'].isoformat();
                hist['id'] = id
                hist['type'] = 'sms'        
        self.response.out.write(json.dumps({'status':status, 'msg':hist}))
示例#2
0
    def new_game(self, request):
        """Creates a Game.
            Args:
            request: The NEW_GAME_REQUEST objects, which includes two players'
                names
            Returns:
                GameForm with created game
            Raises:
                endpoints.NotFoundException: If the user does not exist.
                endpoints.BadRequestException: If the game is created with one
                user.
        """
        user_x = User.query(User.name == request.user_name_x).get()
        user_o = User.query(User.name == request.user_name_o).get()
        if (not user_o) or (not user_x):
            raise endpoints.NotFoundException(
                    'A User with that name does not exist!')
        try:
            game = Game.new_game(user_x.key, user_o.key)
            history = History(game=game.key)
            history.put()
        except ValueError:
            raise endpoints.BadRequestException('Players should be '
                                                'different!')

        return game.to_form('Good luck playing TicTacToe!')
示例#3
0
def updateRecentHistory():
    url = 'https://api.covidtracking.com/v1/us/current.json'
    data = requests.get(url).json()
    print(data)
    for each in data:
        date = datetime.strptime(each['dateChecked'], r'%Y-%m-%dT%H:%M:%SZ')
        mostRecent = History.query.order_by(-History.ds).first().ds
        if date == mostRecent:
            continue

        confirm = each['positive']
        confirm_add = each['positiveIncrease']
        suspect = each['hospitalizedCurrently']
        suspect_add = each['hospitalizedIncrease']
        dead = each['death']
        dead_add = each['deathIncrease']
        heal = each['recovered']   

        history = History()
        history.ds = date
        history.confirm=confirm
        history.confirm_add=confirm_add
        history.suspect=suspect
        history.suspect_add=suspect_add
        history.heal=heal
        history.dead=dead
        history.dead_add=dead_add

        db.session.add(history)
        db.session.commit()
示例#4
0
def upload(request):
    if request.method == 'POST':
        form = SelfieForm(request.POST, request.FILES)
        if form.is_valid():
            instance = Selfie(photo=request.FILES['photo'])
            instance.user = request.user
            instance.info = form.cleaned_data["info"]
            instance.save()

            hist = History(selfie=instance, date=instance.pub_date, matches=0, score=1500)
            hist.save()

            img = Image.open(instance.photo.file)
            x1 = float(request.POST["x1"])
            x2 = float(request.POST["x2"])
            y1 = float(request.POST["y1"])
            y2 = float(request.POST["y2"])
            img.crop((x1, y1, x2, y2)).resize((640, 640)).save(instance.photo.file.file.name)

            print "new salfie: ", instance, "; anlisys result: ", instance.analyze()
            return HttpResponseRedirect(reverse('selfzone.panel:index'))
        return render(request, 'selfzone/uploadForm.html', {'form': form})
    else:
        form = SelfieForm()
        return render(request, 'selfzone/uploadForm.html', {'form': form})
示例#5
0
文件: api.py 项目: yajurahuja/jukebox
    def addToHistory(self, song_instance, user_list):
        history_instance = History(Song=song_instance)
        history_instance.save()

        if user_list is not None and user_list.count() > 0:
            for user_instance in user_list.all():
                history_instance.User.add(user_instance)
示例#6
0
    def parse_rss(self):
        # self.remove_old_history()
        rss_list = Rss.select()
        rss_card_dict = {}
        post_url_list = [
            rss_history.url for rss_history in History.select().where(
                History.publish_at == datetime.today().strftime("%Y-%m-%d"))
        ]
        for rss in rss_list:
            rss_history_list = []
            card_list = [
                CardItem(title=rss.title, url=rss.url, pic_url=rss.cover)
            ]
            feed = feedparser.parse(rss.feed)
            for entry in feed.entries:
                if entry.link not in post_url_list and self.is_today(entry):
                    card_list.append(
                        CardItem(
                            title=f'{entry.title}',
                            url=entry.link,
                            pic_url=
                            'https://ftp.bmp.ovh/imgs/2020/07/6cdb9f606677c9e3.jpg'
                        ))
                    rss_history_list.append(History(url=entry.link))

            if len(card_list) > 1:
                rss_card_dict[rss.title] = card_list
                with db.atomic():
                    History.bulk_create(rss_history_list, batch_size=10)

        return rss_card_dict
示例#7
0
def updateHistory():
    url = 'https://api.covidtracking.com/v1/us/daily.json'
    data = requests.get(url).json()
    for each in data:
        date = datetime.strptime(each['dateChecked'], r'%Y-%m-%dT%H:%M:%SZ')
        confirm = each['positive']
        confirm_add = each['positiveIncrease']
        suspect = each['hospitalizedCurrently']
        suspect_add = each['hospitalizedIncrease']
        dead = each['death']
        dead_add = each['deathIncrease']
        heal = each['recovered']   

        history = History()
        history.ds = date
        history.confirm=confirm
        history.confirm_add=confirm_add
        history.suspect=suspect
        history.suspect_add=suspect_add
        history.heal=heal
        history.dead=dead
        history.dead_add=dead_add

        db.session.add(history)
        db.session.commit()
示例#8
0
文件: api.py 项目: rejahrehim/jukebox
    def addToHistory(self, song_instance, user_list):
        history_instance = History(
            Song=song_instance
        )
        history_instance.save()

        if user_list is not None and user_list.count() > 0:
            for user_instance in user_list.all():
                history_instance.User.add(user_instance)
示例#9
0
def confirm_order(request):
    cart=get_cart(request)
    history = History(id_user=request.user) 
    history.save() 
    for product in cart.id_products.all():
        product.quantity = product.quantity - 1
        history.id_product.add(product)
        product.save()
    history.save()
    cart.delete()    
    return redirect('home')
示例#10
0
    def add_history(cls, jid, to_jid, content):
        m = cls.get_one(jid)
        m.last_say = now()
        if m.history:
            m.history.append(History(to_jid, content))
        else:
            m.history = [History(to_jid, content)]

        try:
            session.commit()
        except:
            session.rollback()
示例#11
0
    def post(self, request):
        if request.method == "POST":
            if 'search_btn' in request.POST:
                look_for = request.POST.get('look_for', None)
                location = request.POST.get('location', None)
                resp = FoursquareSearchRequest().getVenuesInfo(
                    look_for, location)
                f = self.fill_table(resp)
                if f:
                    a = History(item=look_for,
                                location=location,
                                search_date=timezone.now())
                    a.save()
                    for h in f:
                        b = TableData(venue_name=h['name'],
                                      url=h['url'],
                                      phone_number=h['phoneNumber'],
                                      checkin_count=h['checkinCount'],
                                      history_id=a.pk)
                        b.save()
                self.histories = History.objects.order_by(
                    '-search_date').values_list('id', 'item', 'location')[:20]
                self.response_elements['tableData'] = f
                self.response_elements['histories'] = json.dumps(
                    list(self.histories), cls=DjangoJSONEncoder)
            elif 'get_history_btn' in request.POST:
                h_id = request.POST.get('history_id', None)
                self.histories = History.objects.order_by(
                    '-search_date').values_list('id', 'item', 'location')[:20]
                print self.histories
                a = 0
                for history in self.histories:
                    print h_id, history[0]
                    if int(h_id) == int(history[0]):
                        print "aaaaaa"
                        break
                    a = a + 1

                page_number = (a / 10) + 1
                print page_number

                db_histories = TableData.objects.filter(history_id=h_id)
                f = self.fill_table_db(db_histories)
                self.histories = History.objects.order_by(
                    '-search_date').values_list('id', 'item', 'location')[:20]
                self.response_elements['histories'] = json.dumps(
                    list(self.histories), cls=DjangoJSONEncoder)
                self.response_elements['tableData'] = f
                self.response_elements['page_number'] = page_number
        else:
            print "404"

        return render(request, self.template_name, self.response_elements)
示例#12
0
def movie(movie_id):
    user = ctx.request.user
    movie = Movie.get(movie_id)
    movie = _get_movie_details(movie)
    if movie is None:
        raise notfound()
    movie.html_summary = markdown2.markdown(movie.summary)
    if user:
        history = History.find_first('where user_id=? and movie_id=?', user.id,
                                     movie_id)
        if not history:
            history = History(user_id=user.id, movie_id=movie_id)
            history.insert()
        else:
            history.created_at = time.time()
            history.update()
    reviews = Review.find_by(
        'where movie_id=? order by created_at desc limit 1000', movie_id)
    user_review = ''
    if user:
        user_review = Review.find_first('where user_id=? and movie_id=?',
                                        user.id, movie_id)
    return dict(movie=movie,
                reviews=reviews,
                user=user,
                user_review=user_review)
示例#13
0
    def make_move(self, request):
        """Makes a move. Returns a game state with message"""
        if (request.pos < 0 or request.pos > 8):
            raise endpoints.BadRequestException("only move from 0-8!")


        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game.game_over:
            game.message = 'Game already over!'
            return game.to_form()
        
        if (game.board[request.pos] != "-"):
            raise endpoints.BadRequestException("can not move here!")    


        game.board = game.board[:request.pos] + "X" + game.board[request.pos+1:]
        winner = self.get_winner(game.board, "X")
        player_message = "keep moving."
        if winner != None:
            player_message = "You win!"
        elif game.board.count("-") < 1:
            player_message = "Tie!"
        History(game=game.key, move=request.pos, result=player_message, datetime=datetime.now(), player="X").put()
        if winner != None or game.board.count("-") < 1:
            game.end_game(winner, player_message)
            return game.to_form()
        

        spaces = []
        i = -1
        for state in game.board:
            i += 1
            if (state == "-"):
                spaces.append(i);
        if (len(spaces) > 0):          
            robot_move = random.choice(spaces)      
            game.board = game.board[:robot_move] + "O" + game.board[robot_move+1:]
            winner = self.get_winner(game.board, "O")
            robot_message = "keep moving."  
            if winner != None:
                robot_message = "You lose!"
            History(game=game.key, move=robot_move, result=robot_message, datetime=datetime.now(), player="O").put()
            if winner != None:
                game.end_game(winner, robot_message)
                return game.to_form()
        

        game.message = "Keep moving."
        game.put()                  
        return game.to_form()        
示例#14
0
 def get(self):
     contact_name = self.request.get('contact_name')    
     phone = self.request.get('phone')
     msg = self.request.get('msg')
     email = self.request.get("email",'').lower()
     hist = History(email=email, msg=msg, phone=phone, contact_name = contact_name, byme=False)
     hist.put()
     id = hist.key.id()
     hist = hist.to_dict()
     hist['created']=hist['created'].isoformat();
     hist['id'] = id
     hist['type'] = 'sms'  
     channel.send_message(email, json.dumps(hist))
     self.response.out.write(json.dumps({}))
示例#15
0
def api():
    if request.method == 'OPTIONS':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'
        return resp
    if request.method == 'POST':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'
        data = request.json  # получаем данные

        # получаем или создаем нового пользователя
        user = get_or_create(db.session,
                             User,
                             ip_adress=str(request.remote_addr),
                             user_agent=str(parse(str(request.user_agent))))

        # вставляем запись истории с данным пользователем
        history = History(date=datetime.datetime.now(),
                          base=float(data[0]),
                          work_days=int(data[1]),
                          pay_days=int(data[2]),
                          coff=int(data[3]),
                          premium=float(data[4]),
                          result=str(data[5]))

        # сохраняем в БД
        user.histories.append(history)
        db.session.add(user)
        db.session.add(history)
        db.session.commit()
        return resp
    if request.method == 'GET':
        resp = Flask.response_class()
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = '*'

        # запрос истории расчетов сортированный по дате
        query = db.session.query(History, User).join(User, History.user_id == User.id)\
            .order_by(History.date.desc()).all()

        # формируем данные для формата JSON
        records = []
        for history, user in query:
            records.append({
                'date': str(history.date),
                'ip': user.ip_adress,
                'user_agent': user.user_agent,
                'base': history.base,
                'work_days': history.work_days,
                'pay_days': history.pay_days,
                'coff': history.coff,
                'premium': history.premium,
                'result': history.result
            })

        # заносим данные в тело ответа
        resp.data = json.dumps(records)
        return resp
示例#16
0
 def save(self, user, topic, reply=None):
     data = self.data
     content = unicode(data.get('content'))
     data.update({
         'user_id': user.id,
         'topic_id': topic.id,
         'content': strip_xss_tags(content)
     })
     if reply:
         category = 'edit'
         pre_content = reply.content
         cur_content = data.get('content')
         changed = 0
         if pre_content != cur_content:
             diff_content = ghdiff.diff(pre_content, cur_content, css=None)
             changed = 1
         if changed == 1:
             reply.content = cur_content
             History(user_id=user.id,
                     content=diff_content,
                     reply_id=reply.id).save()
         else:
             return reply
     else:
         category = 'create'
         reply = Reply(**data)
     return reply.save(category=category)
示例#17
0
def put(table):
    try:
        model = get_model_by_tablename(table)
        data = request.get_json()
        idx = data['index']

        obj = session.query(model).get(idx)  # неизмененное состояние строки

        note = ''
        flag = False
        for k in data.keys():
            if data[k] != obj.__dict__[k] and data[k] != 'None':
                flag = True
                changed_row = '<{}>: "{}" -> "{}".'.format(k, obj.__dict__[k], data[k])
                note += changed_row
        if flag:
            session.query(model).filter_by(index=idx).update(data)
            last_idx = len(session.query(History).all())
            hist = History(index=last_idx, table=table, obj_id=int(idx), note=note)
            session.add(hist)

        res = make_response(jsonify({"message": "OK"}), 200)
        logger.info('Data changed in "{}" table. Object by index: {}'.format(table, idx))
        return res
    except Exception as e:
        logger.error('Error occurred. Details: {}'.format(e))
        abort(500)
示例#18
0
    def _parse_history(self, request_url):
        weatherbitio_reponse = requests.get(request_url)
        weatherbitio_reponse.raise_for_status()
        json = weatherbitio_reponse.json()
        headers = weatherbitio_reponse.headers

        return History(json, weatherbitio_reponse, headers)
示例#19
0
def delete_expired_images():
    """
    Helper method to delete expired images from database and filesystem
    :return:
    """

    print "Deleting expired images"

    # Get expiration day
    days = int(app.config['SOURCE_IMAGE_LIFETIME'])
    expiration = isodate.datetime_isoformat(datetime.now() - timedelta(days=days))

    storage = GoogleCloudStorage()

    # Get expired history
    history_list = History.get_expired(expiration)

    files_to_delete = []
    for history in history_list:

        # Get images to delete
        files = history.source_files
        files_to_delete += files

        # Update mongo
        history.source_files = []
        history.save()

    # Delete all files to delete
    for filename in files_to_delete:
        storage.delete_from_cloud_storage(filename)
示例#20
0
def smoke_on(all_sensors, all_rules):
    smoke = True
    GPIO.output(4, 1)
    for sensor in all_sensors:
        if sensor.name == 'Smoke':
            sensor.open = True
            sensor.save()

    for rule in all_rules:
        if rule.rule_id == 6 and rule.is_enabled:
            msg = 'Smoke alarm was triggered!'
            Push.message(msg, channels=["Notifications"])
            history_item = History(Text=msg)
            history_item.save()
            message = sendgrid.Mail(to='*****@*****.**', subject='Allstate Hub Notification', html='', text=msg, from_email='*****@*****.**')
            status, mersg = sg.send(message)
示例#21
0
def spell_check_post():
    text = request.form['inputtext']
    text = sanitize(text)
    x = [random.randint(0, 9) for y in range(0, 10)]
    temp = ''.join(map(str, x))
    f = open("./" + temp + ".txt", "w+")
    f.write(text)
    f.close()
    #check words
    cmd = "./a.out " + f.name + " ./wordlist.txt"
    #run file through spell checker c program
    checkedtext = subprocess.check_output(cmd, shell=True)
    #decode to string from bytes
    checkedtext = checkedtext.decode('ascii')
    checkedtext = checkedtext.replace("\n", ",")
    #delete file to prevent resource depletion attacks
    os.remove(f.name)
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    logquery = History(submit_text=text,
                       returned_text=checkedtext,
                       submit_user=current_user.email,
                       timestamp=current_time)
    db.session.add(logquery)
    db.session.commit()
    return render_template('spellcheckpost.html',
                           inputtext=text,
                           outtext=checkedtext)
示例#22
0
	def get_game_history(self, request):
		"""Returns a history of all moves made in game."""
		game = get_by_urlsafe(request.urlsafe_game_key, Game)
		if game:
			history = History.query(ancestor=game.key).order(History.order)
			return HistoryForms(items=[move.to_form() for move in history])
		else:
			raise endpoints.NotFoundException("Game not found!")
示例#23
0
def history():
    gr = {}
    for r in History.all():
        d = r['date'].date()
        if not d in gr:
            gr[d] = []
        gr[d].append(r)
    return render_template('history.html', data=gr)
示例#24
0
文件: api.py 项目: halee9/HangMan
 def get_game_history(self, request):
     """Returns all of the game history"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.NotFoundException(
                 'A Game with that game key does not exist!')
     qry = History.query(History.game == game.key)
     return HistoryForms(items=[history.to_form() for history in qry])
示例#25
0
def crawl_user(account):
    client = weibo.APIClient(app_key=settings.WEIBO_APPKEY, app_secret=settings.WEIBO_APPSECRET)
    client.set_access_token(account.access_token, 0)
    
    if settings.DEBUG:
        COUNT = 21
    else:
        COUNT = settings.WEIBO_API_MAX_COUNT
    id_func = lambda s:s.id 
    
    ##TODO: handle exception
    if not account.latest_status:
        all_statuses = client.statuses.home_timeline.get(count = COUNT).statuses
    else:
        statuses = client.statuses.home_timeline.get(since_id = account.latest_status.id, count = COUNT).statuses
        all_statuses = statuses
        
        while len(statuses) == COUNT:
            last_minid = min(map(id_func, statuses))
            ## The API will return the largest COUNT statuses whose id is larger than since_id
            ## so here is how we iterate to retrieve the entire set
            statuses = client.statuses.home_timeline.get(max_id = last_minid - 1, since_id = account.latest_status.id, count = COUNT).statuses
            all_statuses.extend(statuses)
            
    all_statuses.sort(key=id_func)
    ids = map(id_func, all_statuses)
    assert len(ids) == len(set(ids)) ## Sanity check: no duplicates in the list
    
    saved_statuses = map(store_status, all_statuses)
    for status in saved_statuses:
        ## If we encounter duplicated status, do not create history m2m again
        if not status.weiboaccount_set.exists():
            h = History()
            h.user = account
            h.status = status
            h.save()
    ## Move on if the status is 15 minutes old
    ## This is to deal with API sometimes having missing statuses in between (not even eventually consistent?!) 
    if saved_statuses:
        for i in reversed(range(len(saved_statuses))):
            if older_than(all_statuses[i].created_at, 15): 
                account.latest_status = saved_statuses[i]
                break
    account.save()
    return map(lambda s:s.id, saved_statuses)
示例#26
0
文件: tests.py 项目: AndreiRO/wouso
 def testUpdatePoints(self):
     Coin.add('points')
     Coin.add('gold')
     Formula.add('level-gold', definition='gold=10*{level}', owner=None)
     player = self._get_player()
     player.points = 82
     player.level_no = 1
     player.save()
     update_points(player, None)
     coins = History.user_coins(player.user)
     self.assertIn('gold', coins)
     self.assertEqual(coins['gold'], 20)
     player.points = 10
     player.save()
     update_points(player, None)
     coins = History.user_coins(player.user)
     self.assertIn('gold', coins)
     self.assertEqual(coins['gold'], 0)
示例#27
0
 def testUpdatePoints(self):
     Coin.add('points')
     Coin.add('gold')
     Formula.add('level-gold', expression='gold=10*{level}', owner=None)
     player = self._get_player()
     player.points = 82
     player.level_no = 1
     player.save()
     update_points(player, None)
     coins = History.user_coins(player.user)
     self.assertIn('gold', coins)
     self.assertEqual(coins['gold'], 20)
     player.points = 10
     player.save()
     update_points(player, None)
     coins = History.user_coins(player.user)
     self.assertIn('gold', coins)
     self.assertEqual(coins['gold'], 0)
示例#28
0
 def get_game_history(self, request):
     """Return the game history."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         histories = History.query(History.game==game.key).order(History.datetime)
         # histories = History.query(History.game==game.key)            
         return HistoryForms(items = [history.to_form() for history in histories])
     else:
         raise endpoints.NotFoundException('Game not found!')
示例#29
0
def ajaxHistoryEdit(id=None):
    event = History.query.filter_by(id=id).first()

    if not event:
        event = History(timestamp=datetime.now())
        db.session.add(event)

    if event:
        event.message = request.json['message']
        event.status = request.json['status']
        event.icon = request.json['icon']

        db.session.commit()

    return json.dumps([{
        'exec':
        'document.location.href = \'' + request.referrer + '\''
    }])
示例#30
0
文件: api.py 项目: seyfig/BattleShip
 def get_game_history(self, request):
     """Return game history."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.NotFoundException('Game not found!')
     histories = History.query(ancestor=game.key)
     histories = histories.order(History.turn)
     histories = histories.order(History.player_turn)
     return HistoryForms(items=[history.to_form() for history in histories])
    def cancel_game(self, request):
        """ Cancels a game from it's urlsafe key """
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException("Game not found")

        if not game.game_over and not game.canceled:
            game.canceled = True
            msg = "Game canceled"
            hist = History()
            hist.guess = "-1"
            hist.message = msg
            print hist
            game.history.append(hist)
            game.put()
            return game.to_form(msg)
        else:
            return game.to_form("You cannot cancel a game that is already over")
示例#32
0
文件: offers.py 项目: zjw1234560/PSMS
def createOffer():
    if request.method == "POST":
        data = request.get_json(force=True)
        createdTime = (
            datetime.datetime.now() +
            datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        updateTime = (
            datetime.datetime.now() +
            datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
        email_time = "2016-12-19 " + data["email_time"] + ":00"
        emailTime = float(
            time.mktime(time.strptime(email_time, '%Y-%m-%d %H:%M:%S')))

        offer = Offer(
            int(data["user_id"]), int(data["customer_id"]), data["status"],
            data["contract_type"], data["contract_num"],
            float(data["contract_scale"]), data["os"], data["package_name"],
            data["app_name"], data["app_type"].encode('utf-8'),
            data["preview_link"], data["track_link"], data["material"],
            data["startTime"], data["endTime"], str(data["platform"]),
            str(data["country"]), float(data["price"]),
            float(data["daily_budget"]), data["daily_type"],
            float(data["total_budget"]), data["total_type"],
            data["distribution"], data["authorized"], data["named_rule"],
            data["KPI"].encode('utf-8'), data["settlement"].encode('utf-8'),
            data["period"].encode('utf-8'), data["remark"].encode('utf-8'),
            emailTime, str(data["email_users"]), int(data["email_tempalte"]),
            createdTime, updateTime)
        try:
            db.session.add(offer)
            db.session.commit()
            db.create_all()

            for i in data['country_detail']:
                history = History(offer.id,
                                  int(data["user_id"]),
                                  "default",
                                  createdTime,
                                  status=data["status"],
                                  country=i["country"],
                                  country_price=i["price"],
                                  price=data["price"],
                                  daily_budget=float(data["daily_budget"]),
                                  daily_type=data["daily_type"],
                                  total_budget=float(data["total_budget"]),
                                  total_type=data["total_type"],
                                  KPI=data["KPI"],
                                  contract_type=data["contract_type"],
                                  contract_scale=float(data["contract_scale"]))
                db.session.add(history)
                db.session.commit()
                db.create_all()
            return json.dumps({"code": 200, "message": "success"})
        except Exception as e:
            print e
            return json.dumps({"code": 500, "message": "fail"})
示例#33
0
    def reset_db(self):
        Base.metadata.drop_all(bind=self.db.engine)
        Base.metadata.create_all(bind=self.db.engine)

        for i in xrange(0, 5):
            if len(list(self.db.session.query(History).filter(History.hist_id == i))) == 0:
                h = History(hist_id=i, value=-1, dice="dice" + str(i), name="name" + str(i))
                self.db.session.add(h)

        self.db.session.commit()
示例#34
0
    def test_user_points(self):
        coin = Coin.add('points')
        player = self._get_player()

        scoring.score_simple(player, 'points', 10)

        up = History.user_points(user=player.user)
        self.assertTrue(up.has_key('wouso'))
        self.assertTrue(up['wouso'].has_key(coin.name))
        self.assertEqual(up['wouso'][coin.name], 10)
 def save_history(self, session, obj, action):
     klass = type(obj)
     class_path = "%s.%s" % (klass.__module__, klass.__name__)
     if class_path in self.history_aware_classes:
         data = self.get_changed_data(obj)
         if data or action in ('delete', 'add'):
             transaction = self.get_transaction(session)
             history = History(transaction.id, obj, action, class_path,
                               data)
             session.add(history)
示例#36
0
 def get_game_history(self, request):
     """Return a game's history."""
     game = get_by_urlsafe(request.urlsafe_game_key, TicTac)
     if game:
         histories = History.query(History.game == game.key).\
                             order(History.steps)
         return HistoryForms(
             items=[history.to_form() for history in histories])
     else:
         raise endpoints.NotFoundException('Game not found!')
示例#37
0
 def get_game_history(self, request):
     """Returns a history of all guesses made in game."""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if not game:
         raise endpoints.ConflictException(
             'Cannot find game with key {}'.format(
                 request.urlsafe_game_key))
     else:
         history = History.query(ancestor=game.key).order(History.order)
         return HistoryForms(items=[guess.to_form() for guess in history])
示例#38
0
文件: tests.py 项目: PopAdi/wouso
    def test_user_points(self):
        coin = Coin.add('points')
        player = self._get_player()

        scoring.score_simple(player, 'points', 10)

        up = History.user_points(user=player.user)
        self.assertTrue('wouso' in up)
        self.assertTrue(coin.name in up['wouso'])
        self.assertEqual(up['wouso'][coin.name], 10)
示例#39
0
def price(pairs):
    ticker = krapi.query_public('Ticker', {'pair': pairs})
    prices = {}
    for pair, price in ticker['result'].items():
        maker_price = price['a'][0]
        h = History(pair, maker_price)
        db.session.add(h)
        db.session.commit()
        prices[pair] = maker_price
    return jsonify(pair=pairs, prices=prices)
示例#40
0
文件: app.py 项目: j3andidier/sendsms
        def handle(self, message):
		tel=message.connection.identity
		msg=message.text.lower().split(" ")

		if History.objects.filter(tel_num=tel):				
			"""The phone number is known in our system """
			for q in History.objects.filter(tel_num=tel):	#We pass on each question that we have to ask to the user
				if(q.status==1):
                                        #The question has been asked to the user but the response is not yet registered.So the incoming text message is the response.
					q.reponse=message.text
					q.status=2
					q.save()
				if(q.status==0):
                                        #The question is not yet asked to the user. We have to ask it to him or to her
					q.status=1
					q.save()
					quest=q.question
					message.respond(" %s " %(quest))
					return True
			message.respond("CONGRATULATION! YOU ARE REGISTERED IN OUR SYSTEM !")	#All questions we have prepared to ask to that user for his/her registration have got response
			return True
		elif msg[0]=='joindre':	
			"""The phone number is not known in our system and the user ask for registration"""
			for q in Questions.objects.all():
                                #We put all questions that we will ask to him/her in the table "History"
				h=History(question=q.question,tel_num=tel,status=0)
				h.save()
			if History.objects.filter(tel_num=tel):
                                #The question(s) for registration are available
				message.respond("WELCOME TO RAPIDSMS!")
			else:
				"""The question(s) for registration are not available 
                and the user must try again later to ask for registration 
                """
				message.respond("SORY, TRY AGAIN LATER!")
                        return True
		else:
			"""The phone number is not known in our system and the 
			system must inform to the user the mesage to send if he/she 
			want to be registered """
			message.respond("SORY YOU ARE NOT REGISTERED! TO REGISTER YOURSELF SEND <JOINDRE> !")
			return True
示例#41
0
def smoke_on(all_sensors, all_rules):
    smoke = True
    GPIO.output(4, 1)
    for sensor in all_sensors:
        if sensor.name == 'Smoke':
            sensor.open = True
            sensor.save()

    for rule in all_rules:
        if rule.rule_id == 6 and rule.is_enabled:
            msg = 'Smoke alarm was triggered!'
            Push.message(msg, channels=["Notifications"])
            history_item = History(Text=msg)
            history_item.save()
            message = sendgrid.Mail(to='*****@*****.**',
                                    subject='Allstate Hub Notification',
                                    html='',
                                    text=msg,
                                    from_email='*****@*****.**')
            status, mersg = sg.send(message)
示例#42
0
文件: tests.py 项目: Sendroiu/wouso
    def testUpdatePoints(self):
        IntegerListSetting.get('level_limits').set_value("80 125 180 245 320 450")

        Coin.add('points')
        Coin.add('gold')
        Formula.add('level-gold', expression='gold=10*{level}', owner=None)
        player = self._get_player()
        player.points = 82
        player.level_no = 1
        player.save()
        update_points(player, None)
        coins = History.user_coins(player.user)
        self.assertIn('gold', coins)
        self.assertEqual(coins['gold'], 20)
        player.points = 10
        player.save()
        update_points(player, None)
        coins = History.user_coins(player.user)
        self.assertIn('gold', coins)
        self.assertEqual(coins['gold'], 0)
示例#43
0
def history(id):
    entry = None
    try:
        entry = History.get(id=id)
    except History.DoesNotExist:
        pass
    except ValueError:
        pass
    if entry is None or entry.user.id != current_user.id:
        abort(404)
    return render_template('history.html', entry=entry)
示例#44
0
文件: api.py 项目: bschmoker/highnoon
    def create_game(self, request):
        """create a new game """

        # look up initiating player
        slinger = Player.query(Player.player_id == request.player_id).get()

        if slinger is None:
            raise endpoints.BadRequestException(
                'specified player_id not found')

        # generate new game
        game_id = uniq_id()
        game = Game(game_id=game_id, player_id=slinger.player_id)
        game.put()

        # create game history for this game
        history = History(game=game.key)
        history.put()

        return game.to_message()
示例#45
0
文件: api.py 项目: halee9/HangMan
    def make_guess(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game.game_over:
            return game.to_form('Game already over!')

        guess = request.guess[0].upper()
        """The Guess is only a character"""
        if not guess.isalpha():
            msg = 'Should put an alphabet!'
            return game.to_form(msg)

        """The Guess is already used"""
        if guess in game.matches + game.misses:
            msg = 'Already used!'
            return game.to_form(msg)

        """The Guess is in the taget word"""
        if guess in list(game.target):
            game.matches.append(guess)
            msg = "Wonderful!"
            # Set the Guess is in the output words list"""
            i = 0
            for x in list(game.target):
                if x == guess:
                    game.output_words[i] = x
                i += 1
            if '_' not in game.output_words:
                game.end_game(True)
                return game.to_form(msg + ' You win!')
        else:
        	# The Guess is not in the taget word"""
        	game.misses.append(guess)
        	msg = "You missed!"
        	if len(game.misses) >= 6:
        		game.end_game(False)
        		return game.to_form(msg + ' Game over!')

        game.put()
        History.push(game.key, guess, msg)
        return game.to_form(msg)
示例#46
0
文件: app.py 项目: e0en/wiki
def add_history(article, is_new_page):
    pagename = article.name
    content = article.content
    ip_addr = article.ip_address
    now = datetime.now()
    h = History(name=pagename, content=content, ip_address=ip_addr, time=now)
    if is_new_page:
        h.type = 'new'
        db_session.add(article)
    else:
        h.type = 'mod'
        result_dict = {
            'url_name': article.url_name,
            'content': article.content,
            'html': article.html,
            'time_edit': article.time_edit,
            'is_public': article.is_public,
        }
        db_session.query(Article).filter_by(name=pagename).update(result_dict)
    db_session.add(h)
    db_session.commit()
示例#47
0
文件: tests.py 项目: hcxiong/wouso
    def testUpdatePoints(self):
        IntegerListSetting.get('level_limits').set_value(
            "80 125 180 245 320 450")

        Coin.add('points')
        Coin.add('gold')
        Formula.add('level-gold', expression='gold=10*{level}', owner=None)
        player = self._get_player()
        player.points = 82
        player.level_no = 1
        player.save()
        update_points(player, None)
        coins = History.user_coins(player.user)
        self.assertIn('gold', coins)
        self.assertEqual(coins['gold'], 20)
        player.points = 10
        player.save()
        update_points(player, None)
        coins = History.user_coins(player.user)
        self.assertIn('gold', coins)
        self.assertEqual(coins['gold'], 0)
示例#48
0
def garage_opened(all_sensors, all_rules):
    garage = True
    for sensor in all_sensors:
        if sensor.name == 'Garage':
            sensor.open = True
            sensor.save()

    for rule in all_rules:
        if rule.rule_id == 1 and rule.is_enabled:
            msg = 'You left a window open! Close it to avoid a security risk before leaving.'
            Push.message(msg, channels=["Notifications"])
            history_item = History(Text=msg)
            history_item.save()
            message = sendgrid.Mail(to='*****@*****.**', subject='Allstate Hub Notification', html='', text=msg, from_email='*****@*****.**')
            status, mersg = sg.send(message)
        elif rule.rule_id == 3 and rule.is_enabled:
            # napi = nest.Nest(username, password)
            # for device in napi.devices:
            #     prev_nest_mode_garage = device.mode
            #     device.mode = 'off'
            print 'Nest mode set to off and previous state stored.'
        elif rule.rule_id == 4 and rule.is_enabled:
            msg = 'Make sure the alarm system is enabled!'
            Push.message(msg, channels=["Notifications"])
            history_item = History(Text=msg)
            history_item.save()
            message = sendgrid.Mail(to='*****@*****.**', subject='Allstate Hub Notification', html='', text=msg, from_email='*****@*****.**')
            status, mersg = sg.send(message)
def ping_services():
    for service in Service.query.all():
        response = ping.ping(service.address)
        if response == 0 and service.current_state != ServiceState.unspecified:
            service.previous_state = service.current_state
            service.time_of_last_change_of_state = datetime.datetime.now()
            service.current_state = ServiceState.unspecified
            # history
            history = History(service.address, service.name,
                              ServiceState.unspecified,
                              service.time_of_last_change_of_state,
                              service.organization_id)
            db.session.add(history)
        elif response >= 200 and response < 300 and service.current_state != ServiceState.up:
            service.previous_state = service.current_state
            service.time_of_last_change_of_state = datetime.datetime.now()
            service.current_state = ServiceState.up
            # history
            history = History(service.address, service.name, ServiceState.up,
                              service.time_of_last_change_of_state,
                              service.organization_id)
            db.session.add(history)
            # notifications
            if service.users:
                send_notification("icon_blue", service, "UP")
        elif response >= 400 and response < 600 and service.current_state != ServiceState.down:
            service.previous_state = service.current_state
            service.time_of_last_change_of_state = datetime.datetime.now()
            service.current_state = ServiceState.down
            # history
            history = History(service.address, service.name, ServiceState.down,
                              service.time_of_last_change_of_state,
                              service.organization_id)
            db.session.add(history)
            # notifications
            if service.users:
                send_notification("icon_red", service, "DOWN")

    db.session.commit()
    db.session.close()
    def make_move(self, request):
        """Make a move. Return new game state"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found!')
        if game.game_over:
            return game.to_form('Game already over!')
        if game.gameboard_fliped[request.first_card] or game.gameboard_fliped[
                request.second_card]:
            game.historys.append(
                History(card1=request.first_card,
                        card2=request.second_card,
                        result='Can not choose a fliped card.'))
            return game.to_form('Can not choose a fliped card.')

        game.steps += 1

        if abs(game.gameboard_values[request.first_card] -
               game.gameboard_values[request.second_card]) == CORRECT_PAIR:
            game.pairs += 1
            game.gameboard_fliped[request.first_card] = True
            game.gameboard_fliped[request.second_card] = True

            if game.pairs == NUMBER_OF_PAIRS:
                game.end_game(datetime.datetime.now())
                msg = "You win!"

            else:
                msg = "Correct pairs!"

        else:
            msg = "Incorrect pairs!"

        game.historys.append(
            History(card1=game.gameboard_values[request.first_card],
                    card2=game.gameboard_values[request.second_card],
                    result=msg))
        game.put()
        return game.to_form(msg)
示例#51
0
文件: app.py 项目: e0en/wiki
def delete(pagename):
    article = Article.query.filter(Article.name == pagename).first()
    if article is not None:
        h = History(name=pagename,
                    content=article.content,
                    ip_address=get_user_ip(),
                    time=datetime.now(),
                    type='del')
        db_session.add(h)
        Article.query.filter(Article.name == pagename).delete()
        db_session.commit()

    return redirect(url_for('read', pagename='MainPage'))
示例#52
0
def printsrv():
    if request.method == 'GET':
        return render_template('print.html')
    else:
        content = request.form['content']
        ret, err = check_print(content)
        if ret:
            record = History.create(user=current_user.id, content=content)
            title = str(record.id) + ' - ' + current_user.username
            enscript(title=title, _in=content)
            flash(u"打印请求已成功提交", "success")
        else:
            flash(err, "error")
        return redirect(url_for("printsrv"))
示例#53
0
文件: tests.py 项目: PopAdi/wouso
 def test_update_points_level_upgrade_first_time(self):
     level_up_points = 80
     IntegerListSetting.get('level_limits').set_value(str(level_up_points))
     Coin.add('points')
     Coin.add('gold')
     Formula.add('level-gold', expression='gold=10*{level}', owner=None)
     # Upgrade player's level
     player = self._get_player()
     player.points = level_up_points + 1
     player.level_no = 1
     player.save()
     update_points(player, None)
     coins = History.user_coins(player.user)
     self.assertEqual(coins['gold'], 10 * player.max_level)
示例#54
0
 def get_game_history(self, request):
     """Return a Game history.
         Args:
         request: The GET_GAME_REQUEST objects, which includes
             urlsafe_game_key
         Returns:
             HistoryForm with the history of requested game.
         Raises:
             endpoints.NotFoundException: If the game does not exist.
     """
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game is None:
         raise endpoints.NotFoundException('Game not found!')
     else:
         return History.query(History.game == game.key).get().to_form()
示例#55
0
 def get(self):
     PAGESIZE = 50
     contact_name = self.request.get('contact_name')    
     user = users.get_current_user()
     hist = History.query(History.email == user.email().lower())
     if contact_name:
         hist = hist.filter(History.contact_name == contact_name)
     hist = hist.order(-History.created).fetch(PAGESIZE)
     if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest':
         self.response.headers['Content-Type'] = 'application/json'
         hist = [[e.to_dict(), e.key.id()] for e in hist]
         for e,id in hist:
             e['created']=e['created'].isoformat();
             e['id'] = id
         self.response.out.write(json.dumps({'hist':[e[0] for e in hist]}))
     else:
         template = jinja_environment.get_template('templates/history.html')
         self.response.out.write(template.render({'hist':hist}))
示例#56
0
def move():
    p_entry = History.query.descending('mongo_id').first()
    n_entry = History()
    n_entry = p_entry
    print p_entry.next_location.geocode[0]
    print p_entry.next_location.geocode[1]
    print p_entry.suggested_location.geocode[0]
    print p_entry.suggested_location.geocode[1],
    print p_entry.suggested_location.geocode[0] == p_entry.next_location.geocode[0]
    #if the bot is not moving
    
   
    if p_entry.status is False:
    	print "Fitz Owen is not moving, and.."
    	#if the bot has got a new suggestion, then move move move yo
    	if p_entry.next_location.geocode != p_entry.suggested_location.geocode:
    		print "there is a suggested destination :" + p_entry.suggested_location.name
    		n_entry.status = True
    		n_entry.previous_location = p_entry.next_location
    		n_entry.next_location = p_entry.suggested_location
    		distance = gcd(n_entry.previous_location.geocode[0], n_entry.previous_location.geocode[1], n_entry.next_location.geocode[0], n_entry.next_location.geocode[1])
    		n_entry.distance = distance
    		n_entry.number_of_segments = int(distance / p_entry.speed)
    		if (distance / p_entry.speed) < 1:
    			n_entry.number_of_segments = 1
    		print "Now moving towards" + n_entry.next_location.name +"..."
    	else :
    		print "okay, not moving"
    #if the bot is approaching the destination..
    elif p_entry.status is True:
    	if p_entry.segment is p_entry.number_of_segments:
    		print "got there!"
    		#then stop, and calibrate the location, reset
    		n_entry.status = False
    		n_entry.current_location = p_entry.next_location
    		n_entry.segment = 1
    	#Okay, now let's move..
    	else:
    		print "moving.."
    		lon = (p_entry.next_location.geocode[0] - p_entry.previous_location.geocode[0]) / p_entry.number_of_segments
    		lat = (p_entry.next_location.geocode[1] - p_entry.previous_location.geocode[1]) / p_entry.number_of_segments
    		xy = (p_entry.current_location.geocode[0]+lon,p_entry.current_location.geocode[1]+lat)
    		n_entry.current_location.geocode = xy
    		n_entry.segment = p_entry.segment + 1
    		print n_entry.segment 
    		print n_entry.number_of_segments
    n_entry.current_time = str(datetime.datetime.now())
    n_entry.save()
示例#57
0
def get_history(request):
    history_page_index = request.GET.get('historyPageIndex', '0')
    return JsonResponse({'history': History.export(history_page_index)})
示例#58
0
文件: tests.py 项目: PopAdi/wouso
 def test_user_coins(self):
     Coin.add('points')
     Coin.add('gold')
     player = self._get_player()
     scoring.score_simple(player, 'points', 10)
     self.assertIn('points', History.user_coins(player.user))
示例#59
0
文件: api.py 项目: seyfig/BattleShip
 def _make_move(self, game, user, at_position, p):
     try:
         history = History(parent=game.key)
         history.user = user.key
         history.guess = p.coordinate
         history.turn = game.turn
         if game.player1_turn:
             history.player_turn = 1
         else:
             history.player_turn = 2
         if at_position <= 0:
             message = 'Miss!'
             history.result = 'miss'
             history.put()
             game.set_fired(user, p.d)
             game.put()
         else:
             message = "Hit!"
             history.result = 'hit'
             ships_query = Ship.query(ancestor=game.key)
             filter_query = ndb.query.FilterNode('user', '=', user.key)
             ships_query1 = ships_query.filter(filter_query)
             filter_query = ndb.query.FilterNode('type', '=', at_position)
             ships_query2 = ships_query1.filter(filter_query)
             ship = ships_query2.get()
             if not ship:
                 filter_query = ndb.query.FilterNode(
                     'type', '=', str(at_position))
                 ships_query3 = ships_query1.filter(filter_query)
                 ship = ships_query3.get()
             ship.hits += 1
             game.set_fired(user, p.d)
             if(ship.is_sank()):
                 message += " Ship %s sank" % ShipType(at_position)
                 game.sink_ship(user, at_position)
             history.put()
             ship.put()
             game.put()
     except ValueError as e:
         raise endpoints.BadRequestException(e)
     return game.to_form(message)