Exemple #1
0
 def __init__(self, filename=None):
     if filename is None:
         self.filename = ':memory:'
     else:
         self.filename = filename
     self._connection = sqlite3.connect(
         self.filename, detect_types=sqlite3.PARSE_DECLTYPES)
     self._sql = sql.SQL(self._connection)
     self._sql.run("""CREATE TABLE IF NOT EXISTS datoms
                      (entity, attribute, value, time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                      _deleted BOOLEAN DEFAULT FALSE)
                   """)
     self._sql.run("""CREATE INDEX IF NOT EXISTS entity_attribute
                      ON datoms (entity, attribute)""")
     self._sql.run("""CREATE VIEW IF NOT EXISTS current
                      AS SELECT max(_ROWID_)
                         FROM datoms
                         GROUP BY entity, attribute
                   """)
Exemple #2
0
 def __new__(cls, name, bases, attrs):
     if name == 'Model':
         return type.__new__(cls, name, bases, attrs)
     tableName = attrs.get('__table__', None) or name
     logging.info('found model: %s (table: %s)' % (name, tableName))
     mappings = dict()
     fields = []
     primaryKey = None
     for k, v in attrs.items():
         if isinstance(v, Field):
             logging.info('  found mapping: %s ==> %s' % (k, v))
             mappings[k] = v
             if v.primary_key:
                 if primaryKey:
                     raise RuntimeError(
                         'Duplicate primary ket for field: %s' % k)
                 primaryKey = k
             else:
                 fields.append(k)
     if not primaryKey:
         raise RuntimeError('Primary key not found.')
     for k in mappings.keys():
         attrs.pop(k)
     escaped_fields = list(map(lambda f: '`%s`' % f, fields))
     attrs['__mappings__'] = mappings
     attrs['__table__'] = tableName
     attrs['__primary_key__'] = primaryKey
     attrs['__fields__'] = fields
     attrs['__select__'] = 'select `%s`,%s from `%s`' % (
         primaryKey, ', '.join(escaped_fields), tableName)
     attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (
         tableName, ', '.join(escaped_fields), primaryKey, ', '.join(
             ['?' for i in range(len(escaped_fields) + 1)]))
     attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (
         tableName, ', '.join(
             map(lambda f: '`%s`=?' %
                 (mappings.get(f).name or f), fields)), primaryKey)
     attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName,
                                                              primaryKey)
     loop = asyncio.get_event_loop()
     attrs['__sql__'] = sql.SQL(host=HOST, loop=loop, db=DB)
     return type.__new__(cls, name, bases, attrs)
Exemple #3
0
# -*- coding: UTF-8 -*-
import sql
import comments
import news
import news_os
import traceback
import comments_os

mysql = sql.SQL()


def news_start_1000():
    my_news = news.News()
    repos = mysql.get_repo_without_news()
    if len(repos) == 0:
        print 'done'
        exit(0)
    for repo in repos:
        search_news, urls = my_news.get_news(repo[2])
        if search_news:
            mysql.insert_news(repo[0], search_news, urls)
            print '\033[1;31;40m'
            print repo, 'news ,done'
            print '\033[0m'
        else:
            mysql.insert_news(repo[0], [''], [''])
            print repo, 'failed'


def comments_start_1000():
Exemple #4
0
baseurl = os.environ.get("BASEURL")
if baseurl is not None:
    app.wsgi_app = prefix.PrefixMiddleware(app.wsgi_app, prefix=baseurl)

app.secret_key=os.environ.get("SECRET_KEY") or os.urandom(16)
if os.environ.get("ENFORCE_HTTPS") is not None:
    app.config['PREFERRED_URL_SCHEME'] = "https"
    # https://stackoverflow.com/a/32238093
    @app.before_request
    def before_request():
        if not request.is_secure:
            url = request.url.replace('http://', 'https://', 1)
            return redirect(url, code=301)


sqldb = sql.SQL()
auth.initmanager(app, "login", sqldb)
bp = google.Blueprint(sqldb)
google.setupoauth(bp)
sqldb.setgoogle(bp)

app.register_blueprint(bp.bp, url_prefix="/login")

@app.teardown_appcontext
def shutdown_session(exception=None):
    sqldb.db_session.remove()

@app.route("/login/")
def login():
    return redirect(url_for("google.login"))
Exemple #5
0
import sql

stocks_files = ["priority.txt"]#"nasdaq_clean.txt", "nyse_clean.txt"]

stocks = []
bad_stocks = []
bad_stocks.extend(open("bad_stocks.txt", "r", encoding="ascii").read().split("\n")[:-1])
rare_stocks = []
rare_stocks.extend(open("rare_stocks.txt", "r", encoding="ascii").read().split("\n")[:-1])


for stocks_file in stocks_files:
  stocks.extend(open(stocks_file, "r", encoding="ascii").read().split("\n")[:-1])

stocks = [s.replace("\x00","") for s in stocks]
stocks = [s for s in stocks if s not in bad_stocks]

with sql.SQL() as c:
  for stock in stocks:
    rare = 1 if stock in rare_stocks else 0
    c.set("INSERT INTO stocks SET name=\"" + stock + "\"" + ",rare=" + str(rare))
Exemple #6
0
import sql

SQL = sql.SQL(acid, acid_hack, Amazon)

Class Account(object):

    def __init__(self):
        self.username = None
        self.password = None


    def Register():
        email = str(input('Insert Email'))
        if "@" in str(email);
        password = str(input('Insert Password'))

        if SQL.check_login(email, password) = True;
        #user logged in
        else:
        SQL.register(email, password)
        print("account is now registered")
        #user logged in
        return email, password
    
Exemple #7
0
from logbot_data import token, owner_id
import sql

# noinspection SpellCheckingInspection
CLIENT = discord.Client( )
init( )
EXITING = False
SQL = sqlite3.connect( "logbot.db" )
CURSOR = SQL.cursor( )

RET = ""
LEFT = ""

LOGS_PATH = f'{os.getcwd()}\\Discord Logs'
SETTINGS_PATH = f"{LOGS_PATH}\\SETTINGS"
DB = sql.SQL( )
_SQL = sqlite3.connect( f"{SETTINGS_PATH}\\logbot.db" )
_CURSOR = SQL.cursor( )

def log_error ( error_text: str ):
	"""
	Logs the bot's errors.
	:param error_text:
	"""
	file = f"{os.getcwd()}\\error_log.txt"
	prev_text = ""
	try:
		reader = open( file, 'r' )
		prev_text = reader.read( )
		reader.close( )
		del reader
Exemple #8
0
    return variables


def MiningReport(variables, n=30):
    variables.sort(reverse=True)
    for r2, name in variables[:n]:
        print(name, r2)


sql_file_path = 'C:\\Users\\chris\\OneDrive\\GIT\\Booli\\'
sql_file_name_data = 'RegressionData.sql'
sql_file_name_coordinates_subwaystations = 'CoordinatesSubwayStations.sql'
sql_file_name_coordinates_addresses = 'CoordinatesAddress.sql'

sql_data = bsql.SQL(sql_file_name_data, sql_file_path)
cnxn, cursor = sql_data.connect()
df = sql_data.executeQueryFromFile(cnxn)

sql_subwaystations = bsql.SQL(sql_file_name_coordinates_subwaystations,
                              sql_file_path)
cnxn, cursor = sql_subwaystations.connect()
df_subwaystations = sql_subwaystations.executeQueryFromFile(cnxn)

sql_addresses = bsql.SQL(sql_file_name_coordinates_addresses, sql_file_path)
cnxn, cursor = sql_addresses.connect()
df_addresses = sql_addresses.executeQueryFromFile(cnxn)

geodesic(df_subwaystations[['Latitude', 'Longitude']],
         df_addresses[['Latitude', 'Longitude']])
Exemple #9
0
def test_sql_query_postgres():
    """Tests if the SQL class supports handling queries.
    """
    result = [(0, 'Alice'), (1, 'Bob')]
    query = sql.SQL('SELECT * FROM test', 'test_postgres').execute
    assert query == result
Exemple #10
0
def test_sql_create_postgres():
    """Tests the creation of a SQL object.
    """
    sql.SQL('SELECT * FROM test', 'test_postgres')
Exemple #11
0
def test_sql_create_sqlite():
    """Tests the creation of a SQL object.
    """
    sql.SQL('SELECT * FROM test', 'test_sqlite')