Example #1
0
def display_rt_graph(conn):
    while True:
        try:
            db = dbHandler('sqlite3')
            conn = db.connect()
            #read all the invoice data from the sqlite database
            df = pd.read_sql_query(
                "select InvoiceId,CustomerId,InvoiceDate,Total from invoice;",
                conn,
                parse_dates=['InvoiceDate'],
                index_col='InvoiceDate')
            fig, axes = plt.subplots(
                ncols=2)  #display two graphs to see the differences clearly
            sales = df.resample("M").sum()  #sum of sales for one graph
            sales['Total'].plot(ax=axes[0])
            #unique customers for the other graph
            unique_customers = df['CustomerId'].resample('M').apply(
                lambda x: x.nunique())
            unique_customers.plot(ax=axes[1])
            fig.tight_layout()
            plt.pause(1)
            clear_output(wait=True)

        except Exception as e:
            pass
Example #2
0
def __getPlot(req, plot, filename, title, xSize, ySize):
    filenameWithPath = "/tmp/%s-%sx%s.%s" % (filename.split('.')[0], xSize, ySize, filename.split('.')[1])
    db = dbHandler.dbHandler()
    g = tempPlot.tempPlot()
    if plot == 'day':
        houres = 24
    if plot == 'week':
        houres = 24 * 7
    if plot == 'month':
        houres = 24 * 7 * 30
    if plot == 'year':
        houres = 24 * 365

    # Check for new Data
    if db.hasNewData(filenameWithPath):
        data = db.getData(houres)
        g.plotToFile(data, filenameWithPath, title, int(xSize), int(ySize))
        db.writeRequest(filenameWithPath)

    # Check if file exits:
    if not os.path.exists(filenameWithPath):
        return apache.HTTP_NOT_FOUND

    req.content_type = 'image/png'
    req.sendfile(filenameWithPath)
Example #3
0
 def getTestPlanId(self, name):
     """
     通过测试计划名获取测试计划id
     :param name:
     :return: tpid
     """
     db = dbHandler()
     # sql = 'select * from nodes_hierarchy WHERE name="%s"'% name
     datas = db.getTestPlanId(name)
     db.closeConnection()
     return datas[0][0]
Example #4
0
def main():
    """
    """
    cfg = parseCmdArgs(sys.argv)

    db = dbHandler.dbHandler()
    db.connectDb(cfg['user'], cfg['password'], cfg['db_host'], "openbmp")

    asnList = getASNList(db)
    walkWhois(db,asnList)

    db.close()
Example #5
0
    def getPlanTV(self, tpid):
        """
        获取testversion id
        :param tpid: 测试计划Id,可调用getTestPlanId来获取
        :return: 返回测试计划中包含的用例tvid list
        """

        db = dbHandler()
        datas = db.getTVidByTP(tpid)
        db.closeConnection()
        tcversionids = []
        for i in xrange(len(datas)):
            tcversionids.append(datas[i][2])
        return tcversionids
def main():
    cfg = parseCmdArgs(sys.argv)

    db = dbHandler.dbHandler()
    db.connectDb(cfg['user'], cfg['password'], cfg['db_host'], cfg['db_name'])
    print('connected to db')

    server = cfg['server']
    load_export(db, server);
    print "Loaded rpki roas"

    # Purge old entries that didn't get updated
    db.queryNoResults("DELETE FROM rpki_validator WHERE timestamp < now() - interval '1 hour'")
    print("purged old roas")

    print("Done")
Example #7
0
    def getCaseId(self, tvids):
        """
        获取数据库中的caseId
        :param tvid:
        :return:
        """
        if not tvids:
            return False
        db = dbHandler()
        caseids = []
        for i in xrange(len(tvids)):
            datas = db.getCaseid(tvids[i])
            for j in xrange(len(datas)):
                caseids.append(datas[j][0])

        db.closeConnection()
        return caseids
Example #8
0
    def getExternalId(self, tvids):
        """
        获取测试用例的id
        :param tvids: 传入list[testversion_id, ]
        :return: 返回列表
        """
        if not tvids:
            return False
        db = dbHandler()
        externalids = []
        for i in xrange(len(tvids)):

            datas = db.getTCidByTV(tvids[i])
            for j in xrange(len(datas)):
                externalids.append(datas[j][1])

        db.closeConnection()
        return externalids
Example #9
0
def main():
    """
    """
    cfg = parseCmdArgs(sys.argv)

    # Download the RR data files
    download_data_file()

    db = dbHandler.dbHandler()
    db.connectDb(cfg['user'], cfg['password'], cfg['db_host'], cfg['db_name'])

    for source in RR_DB_FTP:
        import_rr_db_file(db, source,
                          "%s/%s" % (TMP_DIR, RR_DB_FTP[source]['filename']))

    rmtree(TMP_DIR)

    db.close()
Example #10
0
                conn,
                parse_dates=['InvoiceDate'],
                index_col='InvoiceDate')
            fig, axes = plt.subplots(
                ncols=2)  #display two graphs to see the differences clearly
            sales = df.resample("M").sum()  #sum of sales for one graph
            sales['Total'].plot(ax=axes[0])
            #unique customers for the other graph
            unique_customers = df['CustomerId'].resample('M').apply(
                lambda x: x.nunique())
            unique_customers.plot(ax=axes[1])
            fig.tight_layout()
            plt.pause(1)
            clear_output(wait=True)

        except Exception as e:
            pass


if __name__ == '__main__':
    try:
        db = dbHandler('sqlite3')
        conn = db.connect()
        display_rt_graph(conn)
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)
Example #11
0
from flask import Flask, render_template, request, jsonify
from planner import Planner
import json
from dbHandler import dbHandler

app = Flask(__name__)

dbCaller = dbHandler()
planner = Planner()

# Should comment out this call to prevent initialization of radar db at ever
# server restart.
#dbCaller.initializeDatabase()


@app.route("/")
def index():
    planner.definePlanningProblem()
    a = planner.getActionNames()
    g = ['Extinguish Fire At Byeng']
    if a == []:
        o = {'1': 'INVALID INITIAL STATE ;Initial State is Invalid'}
    else:
        o = planner.getOrderedObservations()
    return render_template('index.html', plan=o, actions=a, goals=g)


def getPresentPlan(request):
    """
    Example 'plan' : [
    {"name":"address_media firechief","x":0,"y":0,"width":12,"height":1},
    Copyright: (c) 2012 by Anusha Ranganathan.
"""

from __future__ import absolute_import
import pyinotify
from celery import Celery
import os, stat, time

from dbHandler import dbHandler
from diskMonitorConfig import SCAN_LOCATIONS, DATABASE, TABLE
import celeryconfig

celery = Celery()
celery.config_from_object(celeryconfig)
db = dbHandler(database=DATABASE, table=TABLE)


class EventHandler(pyinotify.ProcessEvent):
    def bytes_to_english(self, no_of_bytes):
        # Helper function to convert number of bytes receives from os.stat into human radabale form
        # 1024 per 'level'
        suffixes = ["bytes", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Yb"]
        f_no = float(no_of_bytes)
        level = 0
        while f_no > 1024.0:
            f_no = f_no / 1024.0
            level = level + 1
        if level == 0:
            return "%s %s" % (no_of_bytes, suffixes[level])
        return "%5.1f %s" % (f_no, suffixes[level])
 def __init__(self):
     self.dbCaller = dbHandler()
Example #14
0
 def __init__(self, user_id):
     self.db = dbHandler.dbHandler()
     self.userPreferences = self.db.GetUserPreferences(user_id)
     self.ingredientsGroups = self.db.ingredients
Example #15
0
def get_db():
    "Opens a new database connection if there is none yet for the current application context."
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = dbHandler(database=DATABASE, table=TABLE)
    return top.sqlite_db
Example #16
0
 def __init__(self):
     self.db_handler = dbHandler()
     self.new_db = self.db_handler.new_db
Example #17
0
from flask import Flask, jsonify, request
import subprocess
import sys
import rateCalculation
import dbHandler

app = Flask(__name__)

db = dbHandler.dbHandler()


@app.route('/')
def home():
    pass


#post /user data: {name :}
@app.route('/user', methods=['POST'])
def create_user():
    request_data = request.get_json()
    return db.SaveNewUserPreferences(user_data=request_data)


#get /restaurant/<name> data: {name :}
@app.route('/restaurant/<string:data>')
def get_recommended_dishes(data):
    datar = rateCalculation.main(data)
    return jsonify(datar)


#get /users