Пример #1
0
def merge_quotes(quotes):
    first = quotes[0]
    last = quotes[-1]

    pre_close = first.pre_close
    open = first.open
    high = max(q.high for q in quotes)
    low = min(q.low for q in quotes)
    close = last.close
    volume = sum(q.volume for q in quotes)
    amount = sum(q.amount for q in quotes)
    change = last.close - first.pre_close
    percent = change_percent(close, pre_close)

    merged = Quote(
        code=first.code,
        datetime=first.datetime,
        period='TBD',
        open=open,
        close=close,
        low=low,
        high=high,
        pre_close=pre_close,
        change=change,
        percent=percent,
        volume=volume,
        amount=amount
    )

    if last.turnover:
        estimate_shares = int(last.volume / last.turnover * 100)
        merged.turnover = round(float(volume) / estimate_shares * 100, 3)

    return merged
Пример #2
0
def quotes():
    form = QuoteAddForm()
    form.collections.choices = [(collection.name, collection.name)
                                for collection in Collection.select().where(
                                    Collection.user == current_user.get_id())]
    if form.validate_on_submit():
        with db.atomic() as txn:
            quote = Quote.create(
                content=form.content.data,
                author=form.author.data,
                user=current_user.get_id(),
            )
            for collection_name in form.collections.data:
                collection = Collection.get(
                    Collection.name == collection_name,
                    Collection.user == current_user.get_id(),
                )
                QuoteCollection.create(
                    quote=quote,
                    collection=collection,
                )
        return redirect(url_for('quotes'))
    else:
        quotes = Quote.select().where(Quote.user == current_user.get_id())
        return render_template('quotes.html', form=form, quotes=quotes)
Пример #3
0
def remove():
    quote_id = request.form['quote_id']
    next_ = request.form['next']

    Quote.get(Quote.id == quote_id).delete_instance()

    return redirect(next_)
Пример #4
0
def merge_quotes(quotes):
    first = quotes[0]
    last = quotes[-1]

    pre_close = first.pre_close
    open = first.open
    high = max(q.high for q in quotes)
    low = min(q.low for q in quotes)
    close = last.close
    volume = sum(q.volume for q in quotes)
    amount = sum(q.amount for q in quotes)
    change = last.close - first.pre_close
    percent = change_percent(close, pre_close)

    merged = Quote(code=first.code,
                   datetime=first.datetime,
                   period='TBD',
                   open=open,
                   close=close,
                   low=low,
                   high=high,
                   pre_close=pre_close,
                   change=change,
                   percent=percent,
                   volume=volume,
                   amount=amount)

    if last.turnover:
        estimate_shares = int(last.volume / last.turnover * 100)
        merged.turnover = round(float(volume) / estimate_shares * 100, 3)

    return merged
Пример #5
0
 def post(self, request, *args, **kwargs):
   accountinfoform = AccountInfoForm(request.POST, instance = get_object_or_404(AccountInfo, pk=kwargs['pk']))
   riskdataform = RiskDataForm(request.POST)
   classcodeform = ClassCodeSelectForm(request.POST, instance = get_object_or_404(ClassCode, pk=request.POST['class_code']))
   
   if accountinfoform.is_valid() and riskdataform.is_valid() and classcodeform.is_valid():
     accountinfo = accountinfoform.save()
     classcode_to_query = classcodeform.cleaned_data['class_code']
     classcode = ClassCode.objects.get(class_code = classcode_to_query)
     riskdata = riskdataform.save()
     quote = Quote(account_info = accountinfoform.instance, risk_data = riskdata, class_code = classcode)
           ##Add the 9 agreements to the quote object
     agreementtypes = AgreementType.objects.all()
     quote.save()
     for agreement in agreementtypes:
       quote.agreements.add(InsuringAgreement(agreement_type = agreement), bulk=False)      
     return redirect(quote)
   
   else:
     accountinfo = get_object_or_404(AccountInfo, pk=kwargs['pk'])
     accountinfoform = AccountInfoForm(instance=accountinfo)
     riskdataform = RiskDataForm(request.POST)
     classcodeform = ClassCodeSelectForm(request.POST)
     context = {'accountinfoform' : accountinfoform, 'riskdataform' : riskdataform, 'classcodeform' : classcodeform}
     return render(request, 'djangoinsurancerater/quote.html', context)
Пример #6
0
def add_quote():
    validation_check = Quote.validate_quote(request.form)
    if "_flashes" in session.keys() or not validation_check:
        flash("Adding quote to database was unsuccessful. Try again")
        return redirect("/dashboard")
    else:
        new_quote = Quote.add_new_quote(request.form)
        return redirect("/dashboard")
Пример #7
0
def quote_add():
    template = env.get_template('quote_add.html')
    all_quotes = Quote.select()
    if request.method == 'POST':
        quote = Quote.create(text=post_get('text'),
                             author=post_get('author'))
        app.flash(u'Цитата додана', 'success')
    return template.render({'quotes': all_quotes})
Пример #8
0
def store_quote(stock, quote_data):
    qoute = Quote(stock=stock, price=quote_data['price'], date=quote_data['date'], recommendation=quote_data['recommendation'])
    qoute.save()
    
    stock.symbol = quote_data['symbol']
    stock.save()
    
    print stock.name
Пример #9
0
def handler_remove_quote(update, context):
    if str(context.args[0]).isdigit():
        chat = update.effective_chat
        quote_id = int(context.args[0])
        Quote.delete().where((Quote.id == quote_id)
                             & (Quote.chat_id == chat.id)).execute()
        update.message.reply_text(f'Quote with id {quote_id} removed.')
    else:
        update.message.reply_text(f'Invalid quote id.')
Пример #10
0
 def create_quote(self, customer_id, bike_id):
     quote = Quote()
     quote.date = date.today()
     
     customer = Customer.objects.get(pk=customer_id)
     bike = Bike.objects.get(pk = bike_id)
     
     quote.customer = customer
     quote.bike = bike
     return quote
Пример #11
0
def handler_get_random_quote(update, context):
    chat = update.effective_chat
    if Quote.select().where(Quote.chat_id == chat.id).count():
        selected_quote = Quote.select().where(
            Quote.chat_id == chat.id).order_by(fn.Random()).limit(1)[0]
        chat.bot.forward_message(chat_id=chat.id,
                                 from_chat_id=-355145151,
                                 message_id=selected_quote.stored_message_id)
        return
    update.message.reply_text('Please add at least one quote first.')
Пример #12
0
def _insert_quote(form):
    quote = form.cleaned_data['quote']
    author = form.cleaned_data['author']
    q = Quote(quote=quote, author=author)
    q.validate_unique()
    for quote in Quote.objects.all():
        if quote.quote == q.quote:
            return 'Quote was already in the database, using known author instead.'
    success = 'Added the quote "%s" to the system.' % str(q)
    q.save()
    return success
Пример #13
0
def store_quote(stock, quote_data):
    qoute = Quote(stock=stock,
                  price=quote_data['price'],
                  date=quote_data['date'],
                  recommendation=quote_data['recommendation'])
    qoute.save()

    stock.symbol = quote_data['symbol']
    stock.save()

    print stock.name
Пример #14
0
def add_quote(id):
    user_id = id
    validation_check = Quote.validate_quote(request.form)
    if not validation_check:
        return redirect('/user_dashboard/' + user_id)
    else:
        add_quote = Quote(author=request.form['author'],
                          quote=request.form['quote'],
                          user_id=user_id)
        db.session.add(add_quote)
        db.session.commit()
    return redirect('/user_dashboard/' + user_id)
Пример #15
0
def add():
    form = QuoteForm(request.form)
    if form.validate():
        q = Quote(text=form.text.data, author=slugify(form.author.data))
        tags = []
        form_tags = [slugify(t.strip()) for t in form.tags.data.split(",")]
        for t in form_tags:
            tag = Tag.query.filter_by(name=t).first()
            if not tag:
                tag = Tag(name=t.strip())
            tags.append(tag)
        q.tags = tags
        db.session.add(q)
        db.session.commit()
    return redirect(url_for("index"))
Пример #16
0
    def test_quote_object_admin_changelist_columns(self):
        self.login()

        foo = Quote(quote="Foo", by="Bar")
        foo.save()

        response = self.client.get(reverse('admin:quotes_quote_changelist'))
        self.assert_changelist_not_admin_form_with_errors(response)
        
        # import pdb; pdb.set_trace()

        changelist = response.context['cl']
        columns = changelist.list_display
        self.assertEqual('quote', columns[1])
        self.assertEqual('by', columns[2])
Пример #17
0
def handler_get_quote(update, context):
    if str(context.args[0]).isdigit():
        chat = update.effective_chat
        quote_id = int(context.args[0])
        if Quote.select().where((Quote.id == quote_id) | (Quote.chat_id == chat.id)).exists():
            quote = Quote.get(
                (Quote.id == quote_id) | (Quote.chat_id == chat.id)
            )
            chat.bot.forward_message(
                chat_id=chat.id,
                from_chat_id=-355145151,
                message_id=quote.stored_message_id
            )
            return
    update.message.reply_text(f'Invalid quote id.')
def submit_quote():
    form = QuoteSubmissionForm()
    if form.validate_on_submit():
        if not app.config['LOCAL']:
            if ip_throttled(Quote, request.remote_addr, max_submissions=10):
                flash("Your IP address has been used to submit several posts recently. "
                        "Please try again in an hour or so."
                )
                return redirect(url_for('submit_quote'))
        new_quote = Quote(
                nym=form.nym.data,
                email=form.email.data,
                quote=form.quote.data,
                quote_type=form.quote_type.data,
                datetime_submitted=datetime.datetime.now(pytz.timezone('US/Eastern')),
                ip_address=request.remote_addr
        )
        app.logger.info("added new quote '%s' from %s" % (
                form.quote.data, form.nym.data
        ))
        db.session.add(new_quote)
        db.session.commit()
        flash("Thanks for your submission!")
        return redirect(url_for('submit_quote'))
    if form.errors:
        errs = ';'.join(str(err) for err in form.errors)
        app.logger.debug(errs)
    return render_template('submit_quote.html', form=form, config=app.config)
Пример #19
0
def occupy_quotes(chars_raw):
    for char in chars_raw:
        char_id = Character.query.filter_by(name=char['name']).first().id
        for quote in char['quotes']:
            new_quote = Quote(quote_caption=quote, author_id=char_id)
            db.session.add(new_quote)
    db.session.commit()
Пример #20
0
 def search(self, d):
     term = self.request.get('term')
     self.success, self.message, quotes = Quote.Search(self.user, term)
     data = {
         'quotes': [q.json() for q in quotes]
     }
     self.set_response(data)
Пример #21
0
 def list(self, d):
     page, max, offset = tools.paging_params(self.request)
     readable_id = self.request.get('readable_id')
     quotes = Quote.Fetch(self.user, readable_id=readable_id, limit=max, offset=offset)
     self.set_response({
         'quotes': [q.json() for q in quotes]
     }, success=True)
Пример #22
0
def create_quote(anime):

    characters_models = []
    characters = anime.get_characters()
    for character in characters:
        quotes_models = []
        quotes = character.get_quotes()
        for quote in quotes:
            print(type(quote.get_tags()))
            quotes_models.append(
                Quote(quote=quote.get_quote(),
                      tags=quote.get_tags(),
                      views=quote.get_views(),
                      likes=quote.get_likes()))

        characters_models.append(
            Character(name=character.get_name(),
                      image=character.get_image(),
                      quotes=quotes_models,
                      views=character.get_views()))

    db.session.add(
        Anime(name=anime.get_name(),
              image=anime.get_image(),
              characters=characters_models,
              views=anime.get_views()))

    print("{} added".format(anime.get_name()))
Пример #23
0
def post_new_quote():

    body = request.get_json()

    conditions = {}
    if "conditions" in body:
        conditions = body['conditions']

    ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr)
    ip = ip.partition(',')[0]

    quote = Quote(text=body['text'],
                  conditions=json.dumps(conditions),
                  view_count=1,
                  ip=ip,
                  active=False)
    db.session.add(quote)
    db.session.commit()

    vote = Vote(ip=ip, value=1,
                quote_id=quote.id)  #auto upvote every new quote by 1
    db.session.add(vote)
    db.session.commit()

    return jsonify(quote.serialize)
Пример #24
0
    def _download_quotes(self, ticker, start_date, end_date=date.today()):
        """
        Get quotes from Yahoo Finance
        """
        ticker = ticker.lower()
        if start_date >= end_date:
            return

        data = quotes.get_historical_prices(ticker, start_date, end_date)
        data = data[len(data) - 1:0:-1]

        if len(data):
            log.info('Got data, storing it')
            if ticker.find('^') == 0:
                return [
                    IdxQuote(ticker, val[0], val[1], val[2], val[3], val[4],
                             val[5], val[6]) for val in data if len(val) > 6
                ]
            else:
                return [
                    Quote(ticker, val[0], val[1], val[2], val[3], val[4],
                          val[5], val[6]) for val in data if len(val) > 6
                ]
        else:
            log.warning('! Quotes download failed, no data.')
            return
Пример #25
0
    def test_quote_calls(self):
        # Create
        q = Quote.Create(self.u, 'Overheard', "I think therefore I am")
        q.put()

        self.assertEqual(q.content, "I think therefore I am")
        self.assertEqual(q.source, "Overheard")

        # List
        response = self.get_json("/api/quote", {}, headers=self.api_headers)
        q = response.get('quotes')[0]
        self.assertEqual(q.get('content'), "I think therefore I am")

        # Update
        response = self.post_json("/api/quote", {
            'id': q.get('id'),
            'source': 'Somewhere else'
        },
                                  headers=self.api_headers)
        q = response.get('quote')
        self.assertEqual(q.get('source'), 'Somewhere else')

        # Search
        response = self.get_json("/api/quote/search", {'term': "think"},
                                 headers=self.api_headers)
        quotes = response.get('quotes')
        self.assertEqual(len(quotes), 1)
Пример #26
0
    def random(self):
        with self.open() as connection:
            cursor = connection.cursor()
            query = "SELECT * FROM quotes ORDER BY RANDOM() LIMIT 1"

            entity = cursor.execute(query).fetchone()
            return Quote(entity[1], entity[2], entity[0]) if entity else None
Пример #27
0
def reqQuote():
    try:
        name = 'abc'
        emailID = '*****@*****.**'
        phoneNum = '8845555'
        country = 'aba'
        fromLang = 'eng'
        toLang = 'eng'
        contentType = 0
        contentSize = 0
        query = 'aa'
        
        if 'name' in request.form:
            name = request.form['name']
        
        if 'emailID' in request.form:
            emailID = request.form['emailID']
            
        if 'phoneNum' in request.form:
            phoneNum = request.form['phoneNum']
            
        if 'country' in request.form:
            country = request.form['country']
            
        if 'fromLang' in request.form:
            fromLang = request.form['fromLang']
            
        if 'toLang' in request.form:
            toLang = request.form['toLang']
            
        if 'contentType' in request.form:
            contentType = request.form['contentType']
            
        if 'contentSize' in request.form:
            contentSize = request.form['contentSize']
            
        if 'query' in request.form:
            query = request.form['query']

        quoteObj = Quote(
            name,
            emailID,
            phoneNum,
            country,
            fromLang,
            toLang,
            contentType,
            contentSize,
            query
        )
        db.session.add(quoteObj)
        db.session.commit()
        return {'message' : 'Request Posted Successfully'}, 201
        
    except:
        print (traceback.format_exc())
        sys.stdout.flush()

        return jsonify({'message': 'Unexpected Error occurred when posting request. Please try again'}), 405
Пример #28
0
def quote_delete(quote_id):
    try:
        quote = Quote.get(Quote.quote_id == quote_id)
        quote.delete_instance()
        app.flash(u'Цитата видалена', 'success')
        redirect('/quote/add')
    except DoesNotExist:
        abort(404)
Пример #29
0
    def get(self):
        quotes = Quote.all()
        quotes_list = []
        if not quotes.count():
            quote = Quote(content=u"Приветик Кош!")
            db.put(quote)
            quotes = Quote.all()

        for q in quotes:
            quotes_list.append(q)

        quote = choice(quotes_list)

        template_values = {"quote": quote.content}

        path = os.path.join(os.path.dirname(__file__), "templates/index.html")
        self.response.out.write(template.render(path, template_values))
Пример #30
0
    def get(self):
        quotes = Quote.all()
        quotes_list = []
        if not quotes.count():
            quote = Quote(content=u"Приветик Кош!")
            db.put(quote)
            quotes = Quote.all()

        for q in quotes:
            quotes_list.append(q)

        quote = choice(quotes_list)

        template_values = {'quote': quote.content}

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))
Пример #31
0
    def search(self, clause):
        with self.open() as connection:
            cursor = connection.cursor()
            query = "SELECT * FROM quotes WHERE {} ORDER BY RANDOM() LIMIT 1".format(
                clause)

            entity = cursor.execute(query).fetchone()
            return Quote(entity[1], entity[2], entity[0]) if entity else None
Пример #32
0
def add_fam_like(content,author, poet):
    """Add a like to quote from the api - they do not have ids from the api so they must be stored in the database"""

    quote = Quote.handle_api_quote(content=content, author=author)

    like = Like(poet_id=poet.id, quote_id=quote.id, is_user_quote=False)
    db.session.add(like)
    db.session.commit()
Пример #33
0
    def execute(self, channel, parameters):
        if len(parameters) == 0:
            channel.send_message("Usage: !addquote [message]")
            return

        result = self._quote_repository.add(Quote(" ".join(parameters), 0))

        channel.send_message("Bleep bloop! Quote number {} added.".format(result))
Пример #34
0
def edit():
    quote_id = request.form['quote_id']
    content = request.form['content']
    next_ = request.form['next']

    quote = Quote.get(id=quote_id)
    quote.content = content
    quote.save()

    return redirect(next_)
Пример #35
0
 def get_random_quote(self):
   quotes = Quote.all()
   quotes_dict = {}
   i = 0
   for q in quotes:
     quotes_dict[i] = q.quote
     i += 1
   if len(quotes_dict) > 0:
     return quotes_dict[random.randint(0, i - 1)]
   return ''
Пример #36
0
def quote_json(quote_id):
    try:
        quote = Quote.get(Quote.id == quote_id)
    except Quote.DoesNotExist:
        return jsonify({'message': 'Quote not found.'}), 404, cors_header
    return jsonify(model_to_dict(
        quote,
        recurse=False,
        exclude=[Quote.user],
    )), cors_header
Пример #37
0
 def random_batch(self, d):
     '''
     Return a random batch, optionally filtered
     '''
     BATCH_SIZE = 50
     sample_keys = Quote.Fetch(self.user, limit=500, keys_only=True)
     if len(sample_keys) > BATCH_SIZE:
         sample_keys = random.sample(sample_keys, BATCH_SIZE)
     quotes = ndb.get_multi(sample_keys)
     self.set_response({'quotes': [q.json() for q in quotes]}, success=True)
Пример #38
0
    def test_quote_readable_matching(self):
        volley = [
            ('1000', "Crony Beliefs", "Kevin Simler", "CRONY BELIEFS (SIMLER)",
             "I contend that the best way to understand all the crazy beliefs out there — aliens, conspiracies, and all the rest — is to analyze them as crony beliefs. Beliefs that have been \"hired\" not for the legitimate purpose of accurately modeling the world, but rather for social and political kickbacks."
             ),
            ('1001', "Thinking in Systems: A Primer", "Donna H. Meadows",
             "THINKING IN SYSTEMS A PRIMER (MEADOWS)", "XXX."),
        ]

        for v in volley:
            source_id, title, author, exp_slug, content = v
            r = Readable.CreateOrUpdate(self.u,
                                        source_id,
                                        title=title,
                                        author=author,
                                        source="test")
            r.put()
            Readable.put_sd_batch([r])

            self.assertEqual(r.slug, exp_slug)

            author_names = author.split(' ')
            source = "%s (%s, %s)" % (title, author_names[-1], author_names[0])
            q = Quote.Create(self.u, source, content)
            q.put()
            self.assertIsNotNone(q.readable)
            self.assertEqual(q.readable, r.key)
            self.assertEqual(q.source_slug(), exp_slug)
            r = Readable.GetByTitleAuthor(self.u, author, title)
            self.assertIsNotNone(r)
            self.assertEqual(r.source_id, source_id)

        # Create another quote with no readable to link to
        q = Quote.Create(self.u, "xxx", "content...")
        q.put()

        self.assertIsNone(q.readable)

        # Fetch quotes for readable
        quotes = Quote.Fetch(self.u, readable_id=r.key.id())
        self.assertEqual(len(quotes), 1)
        self.assertEqual(quotes[0].source, source)
Пример #39
0
def add_new_quote(author_id, quote_caption, user_id):
    new_quote = Quote(quote_caption=quote_caption,
                      author_id=author_id,
                      user_id=user_id)
    if new_quote:
        db.session.add(new_quote)
        db.session.commit()
        flash(message='Quote added successfully! Thanks!', category='success')
        return True
    else:
        return False
Пример #40
0
    def get(self, d):
        hack_id = self.request.get('hack_id')
        res = {}
        if hack_id == 'index_quotes_readables':
            page = self.request.get_range('page')
            PAGE_SIZE = 50
            index_lookup = {}  # index_name -> (index, list of items)
            for q in Quote.query().fetch(limit=PAGE_SIZE, offset=page * PAGE_SIZE):
                sd, index = q.update_sd(index_put=False)
                if index and index.name not in index_lookup:
                    index_lookup[index.name] = (index, [sd])
                else:
                    index_lookup[index.name][1].append(sd)
            for r in Readable.query().fetch(limit=PAGE_SIZE, offset=page * PAGE_SIZE):
                sd, index = r.update_sd(index_put=False)
                if index and index.name not in index_lookup:
                    index_lookup[index.name] = (index, [sd])
                else:
                    index_lookup[index.name][1].append(sd)
            if index_lookup:
                n = 0
                for index_tuple in index_lookup.values():
                    index, items = index_tuple
                    index.put(items)
                    n += len(items)
                res['result'] = "Put %d items in %d indexes" % (n, len(index_tuple))
                res['page'] = page

        elif hack_id == 'normalize_key_props':
            dbp = []
            for hd in HabitDay.query().iter():
                habit_key = hd.habit
                if habit_key.parent() is None:
                    # Need to update
                    hd.habit = ndb.Key('User', hd.key.parent().id(), 'Habit', int(habit_key.id()))
                    dbp.append(hd)
            res['habitdays'] = len(dbp)
            ndb.put_multi(dbp)
            dbp = []
            for jrnl in MiniJournal.query().iter():
                changes = False
                for i, tag_key in enumerate(jrnl.tags):
                    if tag_key.parent() is None:
                        # Need to update
                        jrnl.tags[i] = ndb.Key('User', jrnl.key.parent().id(), 'JournalTag', tag_key.id())
                        changes = True
                if changes:
                    dbp.append(jrnl)
            res['journals'] = len(dbp)
            ndb.put_multi(dbp)

        else:
            res['result'] = 'hack_id not found'
        self.json_out(res)
Пример #41
0
def home():
    if request.method == 'GET':
        quote = query_db()
        if not quote:
            quote = Quote(author='QOTD', insight='POST here to add your quote')
        return render_template('index.html',
                               quote=quote.insight,
                               username=quote.author)
    else:
        try:
            data = request.get_json()
            if data is None or 'author' not in data or 'insight' not in data:
                raise ValueError(
                    'POST application/json data with author and insight')
            quote = add_db(author=data['author'], insight=data['insight'])
        except Exception as e:
            quote = Quote(author='QOTD', insight=str(e))
        return render_template('index.html',
                               quote=quote.insight,
                               username=quote.author)
Пример #42
0
def manual_write():
    all_files = os.listdir(SRT_DIR)
    movie_titles = [{'title':title[:-4]} for title in all_files if title[-3:] == 'srt']

    for movie in movie_titles:
        movie['number'] = len (Quote.query( Quote.movie ==  movie['title']).fetch())
        filepath = SRT_DIR + movie['title'] + '.srt'
        content = open(filepath, 'rb').readlines()
        movie['total'] = len(srt.srt2movie_lines(content))

    return render_template('db_master.html', movies=movie_titles)
Пример #43
0
def homepage():
    try:
        page = int(request.args.get('page'))
    except TypeError:
        page = 0
    quotes, page_count = Quote.paged(page, app.config['PAGE_SIZE'])

    return render_template('homepage.html',
                           quotes=quotes,
                           page=page,
                           page_count=page_count)
Пример #44
0
def pull_last_quote(security, is_index):
    hq = hq_last(security.market, security.code, is_index)

    open = hq.get('open', 0)
    # SUSPEND TODAY
    if open == 0:
        high, low, close, pre_close, volume, amount, change, percent = 0, 0, 0, 0, 0, 0, 0, 0
        return None
    else:
        close = hq.get('close', 0)
        low = hq.get('low', 0)
        high = hq.get('high', 0)
        pre_close = hq.get('pre_close', 0)
        volume = hq.get('volume', 0)
        amount = hq.get('amount', 0)
        change = hq.get('change', 0) or hq.get('close', 0) - hq.get('pre_close', 0)
        percent = hq.get('change_percent') or change_percent(close, pre_close) if pre_close else 0

    quote = Quote(
        code=security.code,
        datetime=date.today(),
        period='d1',
        open=open,
        close=close,
        low=low,
        high=high,
        pre_close=pre_close,
        change=change,
        percent=percent,
        volume=volume,
        amount=amount
    )

    if is_index:
        if security.alias:
            quote.code = security.alias
    else:
        turnover = volume / security.tradable_shares * 100 if security.tradable_shares > 0 else 0
        quote.turnover = round(turnover, 2)

    return quote
Пример #45
0
    def endElement(self, name):
        if name == "page":
            self.title = self.title.strip()
            self.processed += 1
            citations = self.analyse_entry()

            if not citations:
                return

            print self.title

            try:
                uri = u"http://dbpedia.org/resource/" + urlquote(self.title.replace(u" ", u"_"))
                person = profiles.models.Person.objects.get(uri=uri)
            except profiles.models.Person.DoesNotExist:
                try:
                    person = profiles.models.Person.objects.get(name=self.title)
                # except profiles.models.Person.DoesNotExist:
                except Exception:
                    print self.title, "does not exists in the DB"
                    return

            imported = 0

            for q in citations:
                if q["date"]:
                    year = q["date"][0]
                else:
                    year = None

                quote = Quote(author=person, content=q["text"], year=year, source_name=q["description"])
                quote.save()

                # print person.name
                # print q['text']
                # print q['date']
                # print q['description']
                # print ''

            print "imported quotes:", len(citations)
Пример #46
0
def tester_toast(title):
    filepath = SRT_DIR + title + '.srt'
    already_in = len (Quote.query( Quote.movie ==  title).fetch())
    lines = srt.srt2movie_lines(open(filepath, 'rb').readlines())
    indices = [i for i in range(already_in, already_in+20)]
    for i in indices:
        new_entry = Quote()
        new_entry.line_number = i
        new_entry.line = lines[i]
        context_indices = [x for x in range(i-3,i+4) if  x >= 0 and x < len(lines)]
        context = "<br> -".join([lines[x] for x in context_indices])
        context = context.replace(new_entry.line, '<b>'+new_entry.line+'</b>')
        new_entry.context = context
        new_entry.movie = title
        new_entry.put()
    return redirect(url_for('manual_write'))
Пример #47
0
def index(request):
    '''
    Processes first page
    '''

    # Check whether the user is having session or not
    username = request.user

    # If its anonymous user.
    if str(username) == "AnonymousUser":
        username = None

    # If user has submitted the quote
    if request.method == "POST":
        # Only authenticated user can post quote. Alert if not logged in
        if username == None:
            messages.error(request, 'You should login to post the Quote')

        else:
            form = forms.QuoteForm(request.POST)
            if form.is_valid():
                # Save the quote into the database
                quote = form.cleaned_data['quote']
                author = form.cleaned_data['quote_author']
                quote_db = Quote(quote_text=quote,
                                 user_who_uploaded=str(username),
                                 submission_date=timezone.now(),
                                 quote_author=author
                                 )
                quote_db.save()

    # Get the quotes from the database
    quote_list = Quote.objects.all()[::-1]
    form = forms.QuoteForm()
    return render(request,"quotes/index.html",
                  {"form":form,"quote_list":quote_list,'username':username,
                   })
Пример #48
0
def post_index():
    all_posts = Post.get_posts().order_by(Post.date_posted.desc()).\
        limit(config.POSTS_PER_PAGE)
    for item in all_posts:
        item.post_text = shorten_text(item.post_text)

    random_banner = Banner.select().\
        where(Banner.disabled == False).order_by(fn.Rand()).first()
    quote = Quote.select().order_by(fn.Rand()).first()
    messages = StreamMessage.select()

    template = env.get_template('post/index.html')
    return template.render(posts=all_posts, banner=random_banner,
                           stream_messages=messages,
                           quote=quote,
                           link_what='pstlink')
Пример #49
0
    def test_current_classmethod(self):
        self.assertIsNone(Quote.latest)
        
        from datetime import datetime, timedelta
        now = datetime.now()
        foo = Quote(quote="Foo", by="Bar", created=now, promoted=now)
        foo.save()
        self.assertEqual(foo, Quote.latest)
        
        one_second = timedelta(seconds=1)
        bonk = Quote(quote="Bonk", by="Bink", created=now,
            promoted=now + one_second)
        bonk.save()
        self.assertEqual(bonk, Quote.latest)

        one_second = timedelta(seconds=1)
        buzz = Quote(quote="Buzz", by="Baz", created=now + one_second,
            promoted=now - one_second)
        bonk.save()
        self.assertEqual(bonk, Quote.latest) # buzz.promoted < bonk.promoted
Пример #50
0
def flush_toast(title):
    already_in = Quote.query(Quote.movie == title).fetch()
    for line in already_in:
        line.key.delete()
    return redirect(url_for('manual_write'))
Пример #51
0
 def QuoteRandom(self, query):
   keys = Quote.query().fetch(keys_only=True)
   key = random.sample(keys, 1)[0]
   return key.get()