Example #1
0
def command(timebook, config, sheet, **kwargs):
    # get the db
    cfg=parse_config(config)
    db=Database(timebook, cfg)

    switch_to_default=False

    current_sheet = db.get_current_sheet()
    if not sheet or sheet == current_sheet:
        switch_to_default=True
    if not sheet:
        sheet = current_sheet

    try:
        confirm=(input('Delete timesheet "%s"? [y/N]: ' % sheet).strip().lower() == 'y')
    except(KeyboardInterrupt, EOFError):
        confirm=False

    if not confirm:
        print('cancelled')
        return None

    kill(db, sheet)
    if switch_to_default:
        commands.switch.switch(db, 'default')
Example #2
0
def command(timebook, config, switch, out, at, resume, messages, **kwargs):
    # get the db
    cfg = parse_config(config)
    db = Database(timebook, cfg)

    if switch:
        commands.switch.switch(db, switch)
        sheet = switch
    else:
        sheet = db.get_current_sheet()

    timestamp = parse_date_time_or_now(at)

    if out:
        commands.out.out(db, timestamp)

    if db.get_active_info(sheet):
        parser.error("the timesheet is already active")

    message = " ".join(messages)

    most_recent_clockout = db.get_most_recent_clockout(sheet)
    if most_recent_clockout:
        (previous_timestamp, previous_description) = most_recent_clockout
        if timestamp < previous_timestamp:
            parser.error("error: time periods could end up overlapping")
        if resume:
            if message:
                parser.error('"--resume" sets the note, so you cannot also ' "supply the message")
            message = previous_description

    _in(db, sheet, timestamp, message)
def insert_qs():
  Database.db.drop_collection(Database.qs)
  Database.db.drop_collection(Database.db.qs_place)
  # drop index for fast insertion
  Database.qs.drop_indexes()
  Database.qs.ensure_index("_id")
  Database.db.qs_place.drop_indexes()
  Database.db.qs_place.ensure_index("_id")
  
  studies = Database.studies.find()
  print studies.count(), 'studies found in the db'
  for i, study in enumerate(studies):
    study_id = str(study['_id'])
    places_ids = study['places_id']
    # NOTE: places_ids are objectids, we need strings
    places_ids = [str(place) for place in places_ids]
    
    # add a score for each location in the given study
    for place_id in places_ids:
      Database._add_qs_place(place_id, study_id)


    #find all the locations used by this study and update/create qs entries
    locations = Database.locations.find({'place_id' : {'$in' : places_ids}})
    # update/create a qs field for every study, location pair
    print 'processing study', i+1, study['study_name'], 'with', locations.count(), 'locations from', len(places_ids), 'places'
    ninserts = 0
    for loc in locations:
      place_id = str(loc['place_id'])
      location_id = str(loc['_id'])
      result = Database._add_qs(location_id, place_id, study_id)
      ninserts += 1
    print 'finished processing study', study['study_name'], 'ninserts:', ninserts
Example #4
0
    def start(self, all_phrases):

        all_objs = {}
        filename = raw_input("Файл с фразами: ")
        db = Database(filename)
        cursors = db.get(all_phrases)

        for table in cursors:
            for key, value in cursors[table]:
                all_objs[key] = value

        phrases_for_del = []

        # вывод фраз для их отгадывания
        for key in all_objs:
            ec = None
            covered = 1
            if key[0] == ' ':
                answer = key[1:]
            else:
                answer = key

            while ec != answer:
                covered_phrase = self.cover_phrase(key, covered)
                print all_objs[key]
                print "-" + covered_phrase
                ec = raw_input("- ")
                print ""
                covered += 1
                if ec == '--exit':
                    return
                if ec == '--del':
                    phrases_for_del.append(key)
            print '(right): '+key+'\n'
Example #5
0
    def config(self):
        def checkHostName():
           ret = bash("hostname --fqdn")
           if not ret.isSuccess():
               raise CloudInternalException("Cannot get hostname, 'hostname --fqdn failed'")

        if self.syscfg.env.svrMode == "mycloud":
            cfo = configFileOps("/usr/share/cloud/management/conf/environment.properties", self)
            cfo.addEntry("cloud-stack-components-specification", "components-cloudzones.xml")
            cfo.save()

            cfo = configFileOps("/usr/share/cloud/management/conf/db.properties", self)
            dbHost = cfo.getEntry("db.cloud.host")
            dbPort = cfo.getEntry("db.cloud.port")
            dbUser = cfo.getEntry("db.cloud.username")
            dbPass = cfo.getEntry("db.cloud.password")
            if dbPass.strip() == "":
                dbPass = None
            dbName = cfo.getEntry("db.cloud.name")
            db = Database(dbUser, dbPass, dbHost, dbPort, dbName)
            
            try:
                db.testConnection()
            except CloudRuntimeException, e:
                raise e
            except:
def update_pol_stock(conn_str=None):
    db = Database(conn_str)
    beers = db.get_pol_beers()
    shops = [pol['id'] for pol in db.get_pol_shops()]

    stock_by_pol = []
    for beer in beers:
        stocks = check_beer(beer['id'])
        for stock in stocks:
            num = stock['stock']
            updated = stock['updated']
            stock_by_pol.append({
                'shop_id': stock['pol_id'],
                'pol_beer_id': beer['id'],
                'stock': num,
                'updated': updated
            })
        shops_with_beer = [int(stock['pol_id']) for stock in stocks]
        for pol_id in shops:
            if pol_id not in shops_with_beer:
                stock_by_pol.append({
                    'shop_id': pol_id,
                    'pol_beer_id': beer['id'],
                    'stock': 0,
                    'updated': datetime.now()
                })
    save_stock(stock_by_pol, db)
    db.add_log('pol_stock')
Example #7
0
def curate_study(place_id):
    study_id = session["currentStudy"]
    place = Database.getPlace(place_id)
    locations = Database.getLocations(place_id, 48)
    return auto_template(
        "study_curate.html", polygon=place["polygon"], locations=locations, place_id=place_id, study_id=study_id
    )
Example #8
0
class LinkGetter(object):

    def __init__(self):
        self.db = Database()
        print "Listening to %s" % ADDRESS
        socketIO = SocketIO(ADDRESS, 443, secure=True)
        socketIO.on('message', self.on_message)
        socketIO.wait()



    def do_the_thing(self, key, message):
        groups = re.finditer(LINKY, message)
        for g in groups:
            try:
                response = requests.get(g.group(0))
                if response.status_code == 200:
                    print "Found a link! %s" % message
                    self.db.insert_link(key, message, g.group(0))
            except:
                print "Bad link"
    def on_message(self, *args):
        try:
            data = args[0]
            message = data['chat']['value']['message']
            key = data['chat']['key']
            print message
            self.do_the_thing(key, message)
        except:
            print "never crash because crashing would be bad"
Example #9
0
class TCPProxy(TCPServer):
    """
    TCPProxy defines the central TCP serving implementation for the Pi Conga
    server. Each time a new connection comes in, this establishes a Participant
    object that wraps that connection.
    """
    last_connection = None
    db = None

    def __init__(self, db_path, *args, **kwargs):
        super(TCPProxy, self).__init__(*args, **kwargs)

        self.db = Database()
        self.db.connect(db_path)

    def handle_stream(self, stream, address):
        """
        When a new incoming connection is found, this function is called. Wrap
        the incoming connection in a Participant, then make it the most recent
        connection. Tell the oldest connection to use the new one as its
        write target.
        """
        r = Participant(stream, self.db)

        if self.last_connection is not None:
            self.last_connection.add_destination(r)

        self.last_connection = r

        r.wait_for_headers()
Example #10
0
    def change_term(self):
        """
        Позволяет изменить значение термина.
        """
        db = Database("terms.db")
        coursers = db.get(["all_terms"])
        all_terms = {}
        for table in coursers:
            for term, definition in coursers[table]:
                all_terms[term] = definition

        ec = None
        while ec != "--exit":
            ec = unicode(raw_input("Термин: "), "utf-8")
            if ec == "--exit":
                break
            elif ec == "":
                pass
            else:
                if ec in all_terms:
                    print "Значение: ", all_terms[ec], "\n"
                    new_definition = raw_input("Новое значение: ")
                    db.delete("all_terms", [ec])
                    db.insert("all_terms", [ec, unicode(new_definition, "utf-8")])
                    db.commit()
                else:
                    print "Термина не существует!\n"
        db.close_db()
Example #11
0
def update_pol_beers(conn_str=None):
    db = Database(conn_str)
    beers_polet, updated = read_pol_beers()

    # ok, unwrap generator
    beers_polet = [b for b in beers_polet]

    breweries_rb = db.get_rb_breweries()
    breweries_pol = get_breweries_polet(beers_polet)

    matched_pol_rb = match_pol_breweries(breweries_pol, breweries_rb)

    matched_beers = []
    for rb_beer_id, pol_breweries in matched_pol_rb.iteritems():
        rb_brewery = find_in_list(breweries_rb, 'id', rb_beer_id)['name']
        rb_beers_for_brewery = db.get_rb_beers_for_brewery(rb_beer_id)
        matched_beers += match_pol_beers(
            rb_brewery,
            rb_beers_for_brewery,
            pol_breweries,
            beers_polet,
            db
        )
    save_pol_beers(matched_beers, db)
    db.add_log('pol_beers', updated)
Example #12
0
def process_request(client,address):
	database = Database()
	
	while True:
		message = client.recv(1025)
		if message == "close":
			client.send(str(("Thanks for using this database!",0))) # second parameter is 0 - indicates that the client should terminate now like a status
			break;
		elif message == "save":
			file_name = '../Sampleinput/input_file.txt'
			db_file = open(file_name)
			mobiles_list = []
			for eachLine in db_file:
				mobiles_list.append(eval(eachLine))
			db_file.close()
			#client.send(str(("Saving data into the database! Please wait...",1)))
			database.populate_db(mobiles_list)
			client.send(str(("Database is saved!!",1)))
		else:
			database.query(message)
			with open("../Answer/results.txt","rb") as fobj:
				line = fobj.read(1024)
				while line:
					client.send(line)
					line = fobj.read(1024)
			print "sending complete"

	client.close()
Example #13
0
def generate_id_textmessage():
    from db import Database
    d = Database()
    i = d.get_highest_device_id(TextMessage)
    if (i == None):
        return SETTINGS.starting_id
    return i+1
Example #14
0
 def add_task(self, id, name, user):
     """Adds a task to Task table. Requires ID, NAME, USER params"""
     db = Database(connect=True)
     #print "INSERT INTO Task VALUES(%s, '%s', '%s');" % (id, name, user)
     q = db.query("insert into Task values(%s, '%s', '%s');" % (id, name, user))
     db.close() 
     return q
Example #15
0
def generate_id_missionimage():
    from db import Database
    d = Database()
    i = d.get_highest_device_id(MissionImage)
    if (i == None):
        return SETTINGS.starting_id
    return i+1
Example #16
0
 def wrapper(*args, **kwargs):
     db = Database()
     try:
         result = callback(db=db, *args, **kwargs)
     finally:
         db.close()
     return result
Example #17
0
def get_bottom_n(study_id, n):
    qss = list(Database.qs.find({'study_id': study_id}).sort('trueskill.score', direction=1).limit(n))
    for qs in qss:
        place = Database.getPlace(qs['place_id'])
        qs['place_name'] = place['place_name']
        location = Database.getLocation(qs['location_id'])['loc']
        qs['location'] = location
    return jsonifyResponse(qss)
Example #18
0
 def UpdateUser(self, user_id):
     # db.loans.filter_by(db.loans.book_id==2).update({'book_id':1})
     userlevel = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.filter(Database.user.user_id == user_id).update(
         {"firstname": self._txtFirstname.Text, "lastname": self._txtLastname.Text, "userlevel": userlevel}
     )
     Database.commit()
     # Database.user.filter_by(Database.user.user_id==user_id).update({'lastname':self._txtLastname,'firstname':self._txtFirstname,'userlevel': userlevel})
     self.LoadUserData()
Example #19
0
 def add_task_event(self, id, task_id, user, is_started, start, stop, minutes_sum):
     """Adds a task to Task table. Requires ID, NAME, USER params"""
     db = Database(connect=True)
     values = "('%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (id, task_id, user, 
                                                              is_started, start, 
                                                              stop, minutes_sum)
     q = db.query("insert into TaskEvent values%s;" % (values))
     db.close() 
     return q
Example #20
0
def generate_id_placemark():
    from db import Database
    d = Database()
    i = d.get_highest_device_id(Placemark)
    print "Här är i: "
    print i
    if (i == None):
        return SETTINGS.starting_id
    return i+1
Example #21
0
def crawl(folder = os.curdir): 
    db = Database()

    for root, dirs, files in os.walk(folder): 
        abs_files = [os.path.join(root, file) for file in files]
        img_files = [get_image(file) for file in abs_files]
 
        for image in filter(None, img_files):
            db.add(image)
Example #22
0
    def __init__(self, use_test_db):

        Database.__init__(self, use_test_db)
                
        self.packets = []
        
        logging.basicConfig(level=logging.DEBUG)
        
        self.logger = logging.getLogger("LocalDB")
Example #23
0
def update_ratebeer(conn_str=None):
    db = Database(conn_str)
    breweries, breweries_updated = read_ratebeer_breweries()
    update_rb_breweries(breweries, db)
    db.add_log('ratebeer_breweries', breweries_updated)

    beers, beers_updated = read_ratebeer_beers()
    update_rb_beers(beers, db)
    db.add_log('ratebeer_beers', beers_updated)
Example #24
0
def save_result_to_database(website):
    """
    Saves result to database
    """
    try:
        Database.set_website_status(id=website.id, status='finished', result=website.result_to_json())
        log.info('Result Save successfully :: {0}'.format(website.url))
    except Exception as e:
        log.exception('Error in saving result in database')
Example #25
0
def command(timebook, config, rate, sheet, **kwargs):
    # get the db
    cfg=parse_config(config)
    db=Database(timebook, cfg)

    sheet = sheet or db.get_current_sheet()
    if sheet not in db.get_sheet_names():
        parser.error('%s is not a known timesheet' % sheet)

    money(db, sheet, rate)
Example #26
0
    def compute_pattern(self, username, password, new_pat):
        db = Database()
        if db.exist_user() == False:
            pass # return authentication failed message

        old_pats = db.read_patterns(username)
        if self.compare_patterns(new_pat, old_pats) == True:
            db.add_pattern(username, new_pat)
        else:
            pass # return invalid pattern
Example #27
0
def main():
    studyObj = Database.getRandomStudy()
    if studyObj is None:
        return "I don't have any studies. Go to /study/create and make one."
    votesCount = Database.getVotesCount()
    return auto_template(
        "main.html",
        study_id=studyObj.get("_id"),
        study_prompt=studyObj.get("study_question"),
        votes_contributed=votesCount,
    )
Example #28
0
 def SaveUser(self):
     # db.loans.insert(book_id=book_id, user_name=user.name)
     userlevel_ = str(self._cboUserLevel.Text).split(" ")[0]
     Database.user.insert(
         username=self._txtUsername.Text,
         firstname=self._txtFirstname.Text,
         lastname=self._txtLastname.Text,
         userlevel=userlevel_,
     )
     Database.commit()
     self.LoadUserData()
def sample_exp():
    # step 1: binary classification
    libfm = LibFM()
    db = Database('movielens', 718, 8928, 'ratings.csv', 'movies.attr')
    db.load_data()
    db.make_train_test_matrix()
    db.add_negative_data()
    db.dump_libfm_data('train_step1.libfm', 'test_step1.libfm')
Example #30
0
def requestLog(self, expression):
    #try:
        logID = str(expression[1])
        if game_log.DB is None:
            db = Database()        
        else:
            db = game_log.DB
        self.writeSExpr(['log', logID, db.lookup_game(logID)])
        return True
    #except:
        self.writeSExpr(['request-log-denied', 'Log unavailable'])
        return False
Example #31
0
 def __init__(self):
     self.db = Database()
     self.db.connect()
 def __init__(self):
     self.db = Database()
Example #33
0
def get_insert(dataframe):
    print("Upload data")
    database = Database()
    final = database.insert_data(dataframe)
    return final
Example #34
0
from flask import request, Response
from flask_restplus import Namespace, Resource, fields
from model_tienda import Tienda_Model
from db import Database

api = Namespace('user', description='user related operations')

bd = Database()


class Tienda(Resource):

    #Seleccion de todas las filas
    def get(self):
        res = bd.selectRows("select * from tienda")
        return Response(res, mimetype="application/json", status=200)

    #Añade registro
    @api.expect(Tienda_Model.a_tienda)
    def post(self):

        #Form request
        name = request.form['name']
        direccion = request.form['direccion']
        telefono = request.form['telefono']

        #Json request
        # json_data = request.json
        # name = json_data["name"]
        # direccion = json_data["direccion"]
        # telefono = json_data["telefono"]
Example #35
0
import glob
import datetime
from flask import Flask, request, session, redirect, url_for, jsonify
from flask_mail import Mail
from werkzeug.utils import find_modules, import_string
from werkzeug.routing import IntegerConverter

from errors import ApiException
from models import Datamapper
from models.base import JsonObjectDataMapper
from db import Database
from config import get_item_data
import filters

datamapper = Datamapper()
db = Database()
mail = Mail()


def create_app(config={}):
    app = Flask(__name__)

    app.config.update(config)
    app.config.from_envvar('FLASKR_SETTINGS', silent=True)
    db.init_app(app)
    datamapper.init_app(app)
    mail.init_app(app)

    register_converters(app)
    register_blueprints(app)
    register_filters(app)
@app.route("/saveprd")
def saveprd():
    pass




@app.route("/addorder")
def addorder():
    pass


@app.route("/delorder")
def delorder():
    pass


@app.route("/saveorder")
def saveorder():
    pass



if __name__ == "__main__":
    db = Database()
    db._connect()
    print("connected")
    db._disconnect()
    print("disconnected")
    app.run(debug=True)
Example #37
0
from tkinter import END, Tk, StringVar, Label, E, Entry, Label, Listbox, Scrollbar, Button, messagebox
from db import Database

db = Database('reports.db')


def populate_list():
    details_list.delete(0, END)
    for row in db.fetch():
        details_list.insert(END, row)


def add_item():
    if class_text.get() == '' or classno_text.get() == '' or date_text.get(
    ) == '' or time_text.get() == '' or details_text.get() == '':
        messagebox.showerror('Required Fields', 'Please include all fields')
        return
    db.insert(class_text.get(), classno_text.get(), date_text.get(),
              time_text.get(), details_text.get())
    details_list.delete(0, END)
    details_list.insert(END,
                        (class_text.get(), classno_text.get(), date_text.get(),
                         time_text.get(), details_text.get()))
    clear_text()
    populate_list()


def select_item(event):
    try:
        global selected_item
        index = details_list.curselection()[0]
from db import Database
db = Database("Store.db")

def remove(num):
    db.remove(num)
    return "removido com sucesso"

Example #39
0
    attach.add_header('Content-Disposition', 'attachment', filename=path)
    msg.attach(attach)
    rep = MIMEText(rep)
    msg.attach(rep)

    smtpObj = smtplib.SMTP('smtp.mail.ru', 587)
    smtpObj.starttls()
    smtpObj.login('EMAIL', 'PASSWORD')
    smtpObj.sendmail("FROM@EMAIL", ["TO@EMAIL"], msg.as_string())
    smtpObj.quit()


if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('./config')
    db = Database('sqlite:////PATH/TO/DB')
    news = db.get_row_for_report()
    rep = ''

    font0 = xlwt.Font()
    font0.name = 'Times New Roman'
    font0.colour_index = 2
    font0.bold = True

    style0 = xlwt.XFStyle()
    style0.font = font0

    style1 = xlwt.XFStyle()

    wb = xlwt.Workbook()
    ws = wb.add_sheet(time.strftime("%d %b %Y", time.localtime()))
Example #40
0
    def get_db_connection(self):

        db = Database()

        return db
Example #41
0
from flask import Blueprint
from flask import Flask, request, jsonify, make_response
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
from db import Database
from auth_service import require_auth_token
import datetime
import jwt
import json


user_service = Blueprint('user', __name__)
db = Database("todoodledb")


@ user_service.route('/user', methods=['POST'])
def create_user():
    request_json = json.loads(request.data)
    hashed_password = generate_password_hash(
        request_json['password'], method='sha256')
    return db.create_user(name=request_json['name'], password=hashed_password)


@ user_service.route('/user/<int:user_id>', methods=['GET'])
def get_single_user_by_id(user_id):
    return db.get_single_user_by_id([user_id])


@ user_service.route('/user/<int:user_id>', methods=['PUT'])
def edit_single_user(user_id):
    request_json = json.loads(request.data)
 def __init__(self, app, jwt):
     self.db = Database()
     self.db.connect()
     self.jwt = jwt
Example #43
0
# def dumps(lst):
#     print("[")
#     for i in lst:
#         print(f"  {str(i[0]), i[1]},")
#     print("]")

# username = '******'
# count = 10 # Creation of query object
# tweetCriteria = got.manager.TweetCriteria().setUsername(username)\
#                                         .setMaxTweets(count)

# print("Ani")
# # Creation of list that contains all tweets
# tweets = got.manager.TweetManager.getTweets(tweetCriteria) # Creating list of chosen tweet data
# print("Vishnu Anand")
# user_tweets = [[tweet.date, tweet.text] for tweet in tweets]

# print(dumps(user_tweets))

import pandas as pd
from db import Database

db = Database("database.db")

db.from_csv("WHOTwitterData.csv")

db.print()

print(*db.search("How to treat corona virus?"), sep=",\n\t")
Example #44
0
from flask import Flask, json, Response, request
from werkzeug.utils import secure_filename
from os import path, getcwd
import time
from db import Database
from face import Face

app = Flask(__name__)

app.config['file_allow'] = ['image/png', 'image/jpeg']
app.config['storage'] = path.join(getcwd(), 'storage')
app.db = Database()
app.face = Face(app)


def success_handle(output, status=200, mimetype='application/json'):
    return Response(output, status=status, mimetype=mimetype)


def error_handle(error_message, status=500, mimetype='application/json'):
    return Response(json.dumps({"error": {
        "message": error_message
    }}),
                    status=status,
                    mimetype=mimetype)


def get_user_by_id(user_id):
    user = {}
    results = app.db.select(
        'SELECT users.id, users.name, users.created, faces.id, faces.user_id,faces.filename, faces.created FROM users LEFT JOIN faces ON faces.user_id=? WHERE users.id=?',
Example #45
0
 def herokudb(self):
     from db import Database
     mydb = Database()
     return psycopg2.connect(host=mydb.Host, database=mydb.Database, user=mydb.User, password=mydb.Password,
                             sslmode='require')
Example #46
0
class Visual:
    def __init__(self, db_dir, db_name, table, save_dir, save):
        """
        Used to visualise the simulation results from the
        kinematic propagation of a particle moving through
        space.
        Requires a connection to the results database and
        runs through the simulation.
        param db_dir: simulation results database directory
        param db_name: database name -- filename
        param table: database table name == database filename
        param save_dir: directory to save mp4 animation
        param save: bool indicating to save animation mp4
        """
        print('Visualising...', end=' ')
        self.table = table
        self.db = Database(db_dir, db_name, table)
        self.df = self.db.query()

        plt.rcParams['animation.ffmpeg_path'] = '/usr/local/bin/ffmpeg'
        self.anim_filename = '%s%s.mp4' % (save_dir, self.table)
        self.fig = plt.figure(figsize=(15, 8))
        self.fig.subplots_adjust(left=0.05,
                                 bottom=None,
                                 right=0.95,
                                 top=None,
                                 wspace=None,
                                 hspace=0.28)
        gs = gridspec.GridSpec(2, 2)

        # axis 1 - 3d visualisation
        self.ax1 = self.fig.add_subplot(gs[:, 0], projection='3d')
        self.traj, = self.ax1.plot([], [], [], 'bo', markersize=1)
        self.coc, = self.ax1.plot([], [], [], 'mo')

        # list of artists which need to be removed and redrawn each frame
        self.vector_lines = []

        # text animations for points moving through 3d space
        self.pos_text = self.text_artist_3d(' P', 'g')
        self.coc_text = self.text_artist_3d(' C', 'm')
        self.vel_text = self.text_artist_3d(' V', 'r')

        # axis 2 - position and velocity vs time
        self.ax2 = self.fig.add_subplot(gs[0, 1])
        self.ax3 = self.ax2.twinx()
        self.rvt, = self.ax2.plot([], [], 'g-')
        self.vvt, = self.ax3.plot([], [], 'r-')

        self.rmag_text = self.ax2.text(0, 0, '||R||', size=12, color='g')

        # axis 3
        self.ax4 = self.fig.add_subplot(gs[1, 1])
        self.ax5 = self.ax4.twinx()
        self.ant, = self.ax4.plot([], [], 'c-')
        self.att, = self.ax5.plot([], [], 'y-')

        self.n_frames = len(self.df['t'])
        self.anim_counter = 0
        self.n_loops = 3 * self.n_frames

        self.anim = self.animate()
        plt.show()
        if save:
            self.save_animation()
        print('finished')

    def text_artist_3d(self, txt, color, x=0, y=0, z=0):
        """
        create new text artist for the plot
        param txt: text string
        param color: text color
        param x: x coordinate of text
        param y: y coordinate of text
        param z: z coordinate of text
        """
        return self.ax1.text(x, y, z, txt, size=12, color=color)

    @staticmethod
    def vector_arrow_3d(x0, x1, y0, y1, z0, z1, color):
        """
        method to create a new arrow in 3d for vectors
        return Arrow3D: new arrow
        """
        return Arrow3D([x0, x1], [y0, y1], [z0, z1],
                       mutation_scale=10,
                       lw=1,
                       arrowstyle='-|>',
                       color=color)

    def query_db(self):
        """
        query the results db and read into pandas dataframe
        """
        if os.path.isfile(self.db):
            self.db.query()
        else:
            print('Simulation results database does not exist...')

    def config_plots(self):
        """
        Setting the axes properties such as title, limits, labels
        """
        self.set_axes_titles()
        self.set_axes_limits()
        self.ax1.set_position([0, 0, 0.5, 1])
        self.ax1.set_aspect('auto')
        self.ax2.grid()
        self.ax4.grid()

    def set_axes_titles(self):
        """
        put titles on plots
        """
        self.ax1.set_title('Trajectory Visualisation')
        self.ax2.set_title('Position and Velocity Magnitudes vs Time')
        self.ax4.set_title('Normal and Tangential Acceleration vs Time')

    def set_axes_limits(self):
        """
        set the axis limits for each plot, label axes
        """
        # NOTE: Using ax1 limits to draw custom xyz axis
        lim_params = ['r', 'v']
        x_lims = self.get_limits(lim_params, 'x')
        y_lims = self.get_limits(lim_params, 'y')
        z_lims = self.get_limits(lim_params, 'z')
        self.ax1.set_xlim3d(x_lims)
        self.ax1.set_ylim3d(y_lims)
        self.ax1.set_zlim3d(z_lims)
        self.draw_xyz_axis(x_lims, y_lims, z_lims)

        t_lims = self.get_limits(['t'], '')

        self.ax2.set_xlim(t_lims)
        self.ax2.set_ylim(self.get_limits(['r_mag'], ''))
        self.ax2.set_xlabel('t (s)')
        self.ax2.set_ylabel('r_mag (m)', color='g')

        self.ax3.set_ylim(self.get_limits(['v_mag'], ''))
        self.ax3.set_ylabel('v_mag (m/s)', color='r')

        self.ax4.set_xlim(t_lims)
        self.ax4.set_ylim(self.get_limits(['an'], ''))
        self.ax4.set_xlabel('t (s)')
        self.ax4.set_ylabel('an (m/s^2)', color='c')

        self.ax5.set_ylim(self.get_limits(['at'], ''))
        self.ax5.set_ylabel('at (m/s^2)', color='y')

    def draw_xyz_axis(self, x_lims, y_lims, z_lims):
        """
        draw xyz axis on ax1 3d plot
        param x_lims: upper and lower x limits
        param y_lims: upper and lower y limits
        param z_lims: upper and lower z limits
        """
        self.ax1.plot([0, 0], [0, 0], [0, 0], 'ko', label='Origin')
        self.ax1.plot(x_lims, [0, 0], [0, 0], 'k-', lw=1)
        self.ax1.plot([0, 0], y_lims, [0, 0], 'k-', lw=1)
        self.ax1.plot([0, 0], [0, 0], z_lims, 'k-', lw=1)
        self.text_artist_3d('x', 'k', x_lims[1], 0, 0)
        self.text_artist_3d('y', 'k', 0, y_lims[1], 0)
        self.text_artist_3d('z', 'k', 0, 0, z_lims[1])
        self.ax1.set_xlabel('x')
        self.ax1.set_ylabel('y')
        self.ax1.set_zlabel('z')

    def get_limits(self, params, axis):
        """
        get upper and lower limits for parameter
        param axis: get limits for axis, i.e x or y
        param params: list of varaible names
        """
        lower_lim, upper_lim = 0, 0
        for p in params:
            m = max(self.df['%s%s' % (p, axis)])
            if m > upper_lim:
                upper_lim = m
            m = min(self.df['%s%s' % (p, axis)])
            if m < lower_lim:
                lower_lim = m
        return (lower_lim, upper_lim)

    def visualise_data(self, i):
        """
        plot animation function for vector at each time step.
        visualise change in position, velocity, radius of curvature
        param i: time step
        """

        # if self.anim_counter >= self.n_loops:
        #    return

        # ax1

        # position vector
        rx, ry, rz = self.get_vector(['rx', 'ry', 'rz'], i)
        self.traj.set_data(self.df['rx'][:i], self.df['ry'][:i])
        self.traj.set_3d_properties(self.df['rz'][:i])

        # velocity vector
        v = self.get_vector(['vx', 'vy', 'vz'], i)
        vx, vy, vz = rx + v[0], ry + v[1], rz + v[2]

        # radius of curvature - (normalising rc vector)
        rc_mag = self.df['rc_mag'][i]
        rcx, rcy, rcz = self.get_vector(['rcx', 'rcy', 'rcz'], i) / rc_mag
        self.coc.set_data([[0, rcx], [0, rcy]])
        self.coc.set_3d_properties([0, rcz])

        # update label text
        self.pos_text.set_position((rx, ry))
        self.pos_text.set_3d_properties(rz, 'x')
        self.coc_text.set_position((rcx, rcy))
        self.coc_text.set_3d_properties(rcz, 'x')
        self.vel_text.set_position((vx, vy))
        self.vel_text.set_3d_properties(vz, 'x')

        # update vector artists - 3D Arrows for R, V and Rc
        vectors = [
            self.vector_arrow_3d(0, rx, 0, ry, 0, rz, 'g'),
            self.vector_arrow_3d(rx, vx, ry, vy, rz, vz, 'r'),
            self.vector_arrow_3d(rcx, rx, rcy, ry, rcz, rz, 'm')
        ]
        [self.ax1.add_artist(v) for v in vectors]
        if self.vector_lines:
            [vector.remove() for vector in self.vector_lines]
        self.vector_lines = vectors

        # ax2

        t = self.df['t'][:i]

        # magnitude of position vs time
        self.rvt.set_data(t, self.df['r_mag'][:i])
        # magnitude of velocity vs time
        self.vvt.set_data(t, self.df['v_mag'][:i])

        # update r_mag text position
        self.rmag_text.set_position((self.df['t'][i], self.df['r_mag'][i]))

        # ax3

        self.ant.set_data(t, self.df['an'][:i])
        self.att.set_data(t, self.df['at'][:i])

        self.anim_counter += 1

    def get_vector(self, params, i):
        """
        get dataframe values at index for list of parameters
        param params: list of values to retrieve
        param i: index of data
        """
        return [self.df[param][i] for param in params]

    def animate(self):
        """
        animate drawing velocity vector as particle
        moves along trajectory
        return: animation
        """
        return FuncAnimation(self.fig,
                             self.visualise_data,
                             frames=self.n_frames,
                             init_func=self.config_plots(),
                             blit=False,
                             repeat=True,
                             interval=2)

    def save_animation(self):
        """
        save simulation animation
        """
        print('Creating animation movie...')
        FFwriter = animation.FFMpegWriter(fps=30)
        self.anim.save(self.anim_filename, writer=FFwriter)
        print('... movie saved as %s' % self.anim_filename)
Example #47
0
from tkinter import *
from db import Database
from tkinter import messagebox
db = Database('store.db')


def populate_list():
    parts_list.delete(0, END)  # avoid duplicate list, 0: delete everything
    for row in db.fetch():
        print(row)
        parts_list.insert(END, row)


def add_item():
    if part_text.get() == '' or customer_text.get == '' or retailer_text.get() == '' or price_text.get() == '':
        messagebox.showerror('Required_Fields', 'Please include all fields')
    db.insert(part_text.get(), customer_text.get(),
              retailer_text.get(), price_text.get())
    parts_list.delete(0, END)
    parts_list.insert(END, (part_text.get(), customer_text.get(),
                            retailer_text.get(), price_text.get()))
    clear_text()
    populate_list()


def select_item(event):
    try:
        global selected_item
        index = parts_list.curselection()[0]
        selected_item = parts_list.get(index)
Example #48
0
    def __init__(self, db_dir, db_name, table, save_dir, save):
        """
        Used to visualise the simulation results from the
        kinematic propagation of a particle moving through
        space.
        Requires a connection to the results database and
        runs through the simulation.
        param db_dir: simulation results database directory
        param db_name: database name -- filename
        param table: database table name == database filename
        param save_dir: directory to save mp4 animation
        param save: bool indicating to save animation mp4
        """
        print('Visualising...', end=' ')
        self.table = table
        self.db = Database(db_dir, db_name, table)
        self.df = self.db.query()

        plt.rcParams['animation.ffmpeg_path'] = '/usr/local/bin/ffmpeg'
        self.anim_filename = '%s%s.mp4' % (save_dir, self.table)
        self.fig = plt.figure(figsize=(15, 8))
        self.fig.subplots_adjust(left=0.05,
                                 bottom=None,
                                 right=0.95,
                                 top=None,
                                 wspace=None,
                                 hspace=0.28)
        gs = gridspec.GridSpec(2, 2)

        # axis 1 - 3d visualisation
        self.ax1 = self.fig.add_subplot(gs[:, 0], projection='3d')
        self.traj, = self.ax1.plot([], [], [], 'bo', markersize=1)
        self.coc, = self.ax1.plot([], [], [], 'mo')

        # list of artists which need to be removed and redrawn each frame
        self.vector_lines = []

        # text animations for points moving through 3d space
        self.pos_text = self.text_artist_3d(' P', 'g')
        self.coc_text = self.text_artist_3d(' C', 'm')
        self.vel_text = self.text_artist_3d(' V', 'r')

        # axis 2 - position and velocity vs time
        self.ax2 = self.fig.add_subplot(gs[0, 1])
        self.ax3 = self.ax2.twinx()
        self.rvt, = self.ax2.plot([], [], 'g-')
        self.vvt, = self.ax3.plot([], [], 'r-')

        self.rmag_text = self.ax2.text(0, 0, '||R||', size=12, color='g')

        # axis 3
        self.ax4 = self.fig.add_subplot(gs[1, 1])
        self.ax5 = self.ax4.twinx()
        self.ant, = self.ax4.plot([], [], 'c-')
        self.att, = self.ax5.plot([], [], 'y-')

        self.n_frames = len(self.df['t'])
        self.anim_counter = 0
        self.n_loops = 3 * self.n_frames

        self.anim = self.animate()
        plt.show()
        if save:
            self.save_animation()
        print('finished')
def list():

    db = Database()
    cat_list = db.get_all_cat()

    return render_template('list.html', cat_list=cat_list)
 def __init__(self, host='127.0.0.1', port=3306, username='', password='',
              dbname='test', mode=TRANSACTION_MODE.DEFAULT):
     db = MySQLdb.Connect(host=host, port=port, user=username,
                                 passwd=password, db=dbname)
     Database.__init__(self, db)
Example #51
0
 def __init__(self):
     self.sense = SenseHat()
     self.db = Database()
     self.rjson = ReadJson()
Example #52
0
 def get_user_role(self):
     self._logger.info('get_user_role for email: {}'.format(self._email))
     sql = """SELECT advisor FROM user WHERE email=%s"""
     with Database() as _db:
         result = _db.select_with_params(sql, [self._email])
     return result[0][0]
Example #53
0
 def get_table_fields(table, login={}):
     __ = StageTable.get_table_config(table)
     if 'fields' not in __:
         return Database(login=login).list_fields(table)
     return __['fields']
Example #54
0
from admin import Admin
from db import Database

a = Admin('rolf', "1234", 3)

a.save()

print(Database.find(lambda x: x["username"] == 'rolf'))
"""
see admin.py
"""
Example #55
0
class DatabaseExporter:
    def __init__(self, username, filename=None, configLocation=None):
        # Initialize all variables and parameters
        # Must ensure username parameter is safe

        self.csvname = filename
        self.database = Database(
            configLocation) if configLocation else Database()
        self.username = username

        self.sqlMappingOrder, self.sqlMapping = Mapping(
            configLocation=configLocation).getInverseOrderedMap()
        self.defineMaps()

        if isinstance(filename, str) and len(filename) > 0:
            self.csvfile = open(self.csvname, 'w')
        else:
            # if its None or sys.stdout
            self.csvfile = self.csvname

        # connect to the database
        self.database.connect()
        self.table = self.getTableName()

    def defineMaps(self):
        self.columns = len(self.sqlMappingOrder)
        # 1 = GST Type, 2 = Month Map, 3 = TRUE/FALSE
        self.mappableColumns = {
            "GST_type": 1,
            "fin_endMonth": 2,
            "AGM_next": 2,
            "AGM_done": 3,
            "GST_req": 3,
            "GST_endMonth": 2,
            "GST_done": 3,
            "GST_next": 2,
            "audit_req": 3,
            "audit_done": 3,
            "audit_next": 2,
            "IRAS_done": 3,
            "IRAS_next": 2
        }
        self.GSTTypeMap = {-1: "", 1: "1/12", 3: "3/12", 6: "6/12"}
        self.monthMap = {
            -1: "",
            1: "JAN",
            2: "FEB",
            3: "MAR",
            4: "APR",
            5: "MAY",
            6: "JUN",
            7: "JUL",
            8: "AUG",
            9: "SEP",
            10: "OCT",
            11: "NOV",
            12: "DEC"
        }
        self.boolMap = {-1: "", 0: "FALSE", 1: "TRUE"}

        def c_asis(ele):
            return ele

        def c_month(ele):
            return self.monthMap[ele]

        def c_gstType(ele):
            return self.GSTTypeMap[ele]

        def c_boolean(ele):
            return self.boolMap[ele]

        self.mapped = {0: c_asis, 1: c_gstType, 2: c_month, 3: c_boolean}

    def getTableName(self):
        return "table_{}".format(self.username)

    def exportDB(self):
        # check if table exists
        _r = self.database.query(
            "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{}'".
            format(self.table), None, True)

        if len(_r) == 0:
            raise ExporterError(
                "Table does not exist yet. Have you populated the database?")

        _ret = list()

        _companies = self.database.query(
            "SELECT * FROM `{}`".format(self.table), None, True)

        # print headers
        # First write the serial number
        _headers = ['"S/N"']
        for c in self.sqlMappingOrder:
            _headers.append('"{}"'.format(self.sqlMapping[c]))

        _ret.append(",".join(_headers))

        _coyCount = 0
        for coy in _companies:
            _coy = coy[1:]
            _coyCount += 1

            _row = ['"{}"'.format(_coyCount)]

            for i in range(self.columns):
                # 0 = nomap, 1 = GST Type, 2 = Month Map, 3 = TRUE/FALSE
                _maptype = self.mappableColumns.get(self.sqlMappingOrder[i], 0)
                try:
                    _row.append('"{}"'.format(self.mapped[_maptype](_coy[i])))
                except (KeyError, IndexError):
                    raise ExporterError(
                        "Database data incorrect. Please contact administrator."
                    )

            _ret.append(",".join(_row))

        _retJoined = "\n".join(_ret)

        if self.csvfile:
            self.csvfile.write(_retJoined)
            return

        return _retJoined

    def clean(self):
        # Cleanly close the Database
        self.database.exitDB()

        # Close the csvfile if open
        if self.csvfile:
            self.csvfile.close()
Example #56
0
 def get_program_id(self, degree: str) -> str:
     self._logger.info('Get Program ID method for degree: {}'.format(degree))
     sql = "SELECT degree_prog_id FROM degree_prog WHERE program_code=%s"
     with Database() as _db:
         prog_id = _db.select_with_params(sql, [degree, ])
     return prog_id[0][0]
Example #57
0
    def __init__(self, db_path, *args, **kwargs):
        super(TCPProxy, self).__init__(*args, **kwargs)

        self.db = Database()
        self.db.connect(db_path)
Example #58
0

# http://127.0.0.1:5000
api.add_resource(Home, '/')
# Post and add postgres to user and password
# Put and Delete Methods
api.add_resource(UserRegister, "/user")
# Post and add postgres to sensor information
# Put Method
api.add_resource(SensorInformation, "/user/sensor")
#Post and add postrgres to field information
#Delete
api.add_resource(FieldInformation, "/user/field")
# Postgre list all users /get
api.add_resource(Users, "/users")
# Mongodb insert sensor values / post
# Mongodb List all collection values /get
api.add_resource(SensorRegister, "/sensors")
# For collect wemos data from specific id /post
# return specific id's sensor datas /get
api.add_resource(Sensors, "/sensor/<string:sensor_id>")

# If the debug flag is 'True' set the server
# will automatically reload for code changes
# and show a debugger in case an exception happened.
if __name__ == "__main__":
    from db import db, Database
    db.init_app(app)
    Database.initialize()
    app.run(port=5000, debug=True)
Example #59
0
from db import Database
from query import Query
from time import process_time

from random import choice, randint, sample, seed

# Student Id and 4 grades
db = Database()
grades_table = db.create_table('Grades', 5, 0)
query = Query(grades_table)

records = {}

seed(3562901)

for i in range(0, 1000):
    key = 92106429 + randint(0, 9000)
    while key in records:
        key = 92106429 + randint(0, 9000)
    records[key] = [
        key,
        randint(0, 20),
        randint(0, 20),
        randint(0, 20),
        randint(0, 20)
    ]
    query.insert(*records[key])
    print('inserted', records[key])

for key in records:
    record = query.select(key, [1, 1, 1, 1, 1])[0]
Example #60
0
from bot108 import bot
import schedule

import constants
from db import Database

database = Database(constants.bot_database)
#MONDAY
#wake up
def job_tue1(chat_id):
    bot.send_message(chat_id, '🌝Добрейшего утра!) \n'
                                          '\n'
                                          '🤸‍♂Время просыпаться, запускать сознание и тело для новых свершений!\n'
                                          '🕺Сегодня тебя ждет новый день.
 Определи ногу с которой ты встаешь и вперед на утренние процедуры. ')
        # почистить зубы

def job_tue2(chat_id):
    bot.send_message(chat_id,  '🖖Пожалуйста возьми зубную щетку в непривычную для тебя руку. \n'
                                          '🧠Регулярно практикуя это простое действие, сознание учится привыкать к непривычному, это мировосприятие хорошо помогает в изучении новой информации умений. \n'
                                          '\n'
                                          '👉😀Помним для более эффективного результата и мягкого воздействия на десны, чистить зубы от корней к коронкам. Начиная от задних зубов, сначала по верхнему ряду, затем по нижнему. Массаж десен.')
        # waterfasting

def job_tue3(chat_id):
    bot.send_message(chat_id,  '🥛Пьем стакан воды комнатной температуры натощак и за ним сразуже второй.\n')

def job_tue33(chat_id):
    bot.send_message(chat_id,  '🥛➕🥛➕🥛Если захочется есть, пьем еще воду, стараемся позавтракать первый раз в 12.30')

        # warm up + food notice