示例#1
0
def edit_item(item):
    conn = sql.connect()
    cur = conn.cursor()
    cur.execute(" SELECT * FROM items WHERE name=?", [item])
    cur_item = cur.fetchone()
    if request.method == 'POST':
        new_name = request.form['nameinput']
        new_qty = request.form['qtyinput']
        new_volume = request.form['sizeinput']
        print("got here")

        conn = sql.connect()
        cur = conn.cursor()
        cur.execute(
            " UPDATE items SET name=?,quantity=?,volume=? WHERE name=?",
            [new_name, new_qty, new_volume, cur_item[0]])
        cur.execute(" SELECT * FROM items WHERE name=?", [cur_item[0]])
        print("got here")
        conn.commit()
        conn.close()
        return (redirect(url_for('index')))

    if request.method == 'GET':
        return (render_template('create.html',
                                task='edit',
                                name=cur_item[0],
                                quantity=cur_item[1],
                                size=cur_item[2]))
示例#2
0
 def __init__(self):
     self.player_id = 0
     self.mother_fatigue = 0
     self.money = 1000
     self.neet_fulness = 0
     self.neet_motivation = 0
     self.time = "仕事前"
     sql.connect(self)
示例#3
0
def delete_item(item):
    conn = sql.connect()
    cur = conn.cursor()
    cur.execute(" DELETE FROM items WHERE name=?", [item])
    conn.commit()
    conn.close()
    return (redirect(url_for('index')))
示例#4
0
def index():
    conn = sql.connect()
    cur = conn.cursor()
    cur.execute(" SELECT * FROM items ORDER BY name")
    result_raw = cur.fetchmany(1000)
    conn.close()
    return (render_template('main.html', items=result_raw))
示例#5
0
def source_session(host, user, password, database):
    return sql.connect(None,
                       host=host,
                       user=user,
                       password=password,
                       logmech='LDAP',
                       database=database)
示例#6
0
def batch(trial,
          stack,
          images,
          diameter,
          separation=None,
          noise_size=1,
          smoothing_size=None,
          invert=True,
          junk_image=None,
          percentile=64,
          minmass=1.,
          pickN=None,
          override=False):
    """Process a list of image files using locate(), 
    and insert the centroids into the database."""
    images = _cast_images(images)
    conn = sql.connect()
    if sql.feature_duplicate_check(trial, stack, conn):
        if override:
            logger.info('Overriding')
        else:
            logging.error(
                'There are entries for this trial and stack already.')
            conn.close()
            return False
    junk_image = plt.imread(junk_image)
    for frame, filepath in enumerate(images):
        frame += 1  # Start at 1, not 0.
        centroids = locate(filepath, diameter, separation, noise_size,
                           smoothing_size, invert, junk_image, percentile,
                           minmass, pickN)
        sql.insert_feat(trial, stack, frame, centroids, conn, override)
        logger.info("Completed Trial %s Stack %s Frame %s", trial, stack,
                    frame)
    conn.close()
示例#7
0
    def __init__(self):
        self.player_id = 0
        self.mother_fatigue = 0
        self.money = 1000
        self.neet_fulness = 0
        self.neet_motivation = 0
        self.time = True
        self.count = 1

        self.foods = []  # 表示する食事のリスト()
        self.buys = []  # 表示する商品のリスト
        self.talks = []
        self.foods_id = []  # foods[i]のデータベース上のidがfoods_id[i]
        self.buys_id = []
        self.talks_id = []

        sql.connect(self)
        self.clean = False
示例#8
0
def sub(item):
    conn = sql.connect()
    cur = conn.cursor()
    cur.execute(" SELECT * FROM items WHERE name=?", [item])
    cur_count_raw = cur.fetchone()
    cur_count = cur_count_raw[1] - 1
    print(cur_count)
    cur.execute(" UPDATE items SET quantity=? WHERE name=?", [cur_count, item])
    conn.commit()
    conn.close()
    return (redirect(url_for('index')))
示例#9
0
def get(id=False):
    conn = sql.connect()
    if not conn:
        return False
    if id:
        pass
    else:
        users = []
        result = conn.cursor().execute(
            "SELECT id, login, role FROM users").fetchall()
        for row in result:
            id, login, role = row
            users.append({'id': id, 'login': login, 'role': role})
    def _player_daemon( self ):
        # This is the daemon which will add information about played media to the database
        
        # Create a connection to the database
        self.connectionWrite = sql.connect()
        
        # Create a player and monitor object
        self.Player = Widgets_Player( action = self.mediaStarted, ended = self.mediaEnded )
        self.Monitor = Widgets_Monitor( action = self.libraryUpdated )

        # Loop
        while not xbmc.abortRequested and self.running == True:
            xbmc.sleep( 1000 )
            
        del self.Player
        del self.Monitor
示例#11
0
def create_item():
    if request.method == 'POST':
        name = request.form['nameinput']
        qty = request.form['qtyinput']
        volume = request.form['sizeinput']

        conn = sql.connect()
        cur = conn.cursor()
        cur.execute(
            " INSERT INTO items(name, quantity, volume) VALUES(?, ?, ?) ",
            [name.lower(), qty, volume.lower()])
        conn.commit()
        conn.close()
        return (redirect(url_for('index')))
    if request.method == 'GET':
        return (render_template("create.html", task='create'))
    def _player_daemon(self):
        # This is the daemon which will add information about played media to the database

        # Create a connection to the database
        self.connectionWrite = sql.connect()

        # Create a player and monitor object
        self.Player = Widgets_Player(action=self.mediaStarted,
                                     ended=self.mediaEnded)
        self.Monitor = Widgets_Monitor(action=self.libraryUpdated)

        # Loop
        while not xbmc.abortRequested and self.running == True:
            xbmc.sleep(1000)

        del self.Player
        del self.Monitor
示例#13
0
def login():
    #Post grabs from html file?
    if request.method == 'POST':

        #try to get username and password and add to
        #database
        try:
            username = request.form['username']
            pw = request.form['pw']

            #connect to database and save as con
            with sql.connect("mynewdb.sqlite") as con:

                #Connect database (con) to cursor. Use bound database to cursor
                #to fetch results

                c = con.cursor()

                #Excute SQLite commands could also create schema for this
                c.execute(
                    "INSERT INTO users (userName,password)"
                    "VALUES (?,?)", (username, pw))

                #Commit database information
                con.commit()
                msg = ("successfully added")

        #If unable to add to database. Rollback database
        except:
            con.rollback()
            msg = ("unable to copy")

        #Use results html to displays message to inform user if the
        #username has been added to the database or not
        finally:
            return render_template("results.html", msg=msg)
            #close database
            con.close()
示例#14
0
文件: feature.py 项目: tacaswell/mr
def batch(trial, stack, images, diameter, separation=None,
          noise_size=1, smoothing_size=None, invert=True, junk_image=None,
          percentile=64, minmass=1., pickN=None, override=False):
    """Process a list of image files using locate(), 
    and insert the centroids into the database."""
    images = _cast_images(images)
    conn = sql.connect()
    if sql.feature_duplicate_check(trial, stack, conn):
        if override:
            logger.info('Overriding')
        else:
            logging.error('There are entries for this trial and stack already.')
            conn.close()
            return False
    junk_image = plt.imread(junk_image)
    for frame, filepath in enumerate(images):
        frame += 1 # Start at 1, not 0.
        centroids = locate(filepath, diameter, separation, 
                           noise_size, smoothing_size, invert, junk_image,
                           percentile, minmass, pickN)
        sql.insert_feat(trial, stack, frame, centroids, conn, override)
        logger.info("Completed Trial %s Stack %s Frame %s", 
                    trial, stack, frame)
    conn.close()
示例#15
0
 def add_fact(self, topic, fact):
     conn = connect(self.url)
     run_sql(conn, INSERT_FACT_SQL, results=False,
             parameters=[topic, dumps(fact)])
示例#16
0
 def after_id(self, topic, id):
     conn = connect(self.url)
     topic = self._translate_wildcards(topic)
     result = run_sql(conn, GET_AFTER_ID_FACTS_SQL,
                      results=True, parameters=[topic, id])
     return map(self._format_fact, result)
示例#17
0
 def last_n(self, topic, number):
     conn = connect(self.url)
     topic = self._translate_wildcards(topic)
     result = run_sql(conn, GET_LAST_N_FACTS_SQL % (number,),
                      results=True, parameters=[topic])
     return map(self._format_fact, result)
示例#18
0
 def list_topics(self):
     conn = connect(self.url)
     result = run_sql(conn, GET_TOPICS_SQL, results=True)
     return map(lambda x: x[0], result)
示例#19
0
 def __init__(self, url):
     self.url = url
     conn = connect(self.url)
     result = run_sql(conn, CHECK_FACTS_TABLE_SQL, results=True)[0][0]
     if result != 1:
         raise MissingTableError('Facts table not present.')
示例#20
0
                        elif key == 'Title':
                            book_info['name'] = ':'.join(ar[1:]).strip()
                            book_info[
                                'enter_path'] = book_info['name'] + '.txt'
                        elif key == 'Release Date':
                            book_info['date'] = ':'.join(ar[1:]).strip()
            except Exception:
                pass
        sql.add_book(book_info['publisher_id'], book_info['name'], book_info['main_path'], \
            book_info['enter_path'], book_info['date'], book_info['wiki_link'], book_info['description'])
        update_book_table()
        shutil.copyfile(file_name, build_path(book_info))
        fill_book_form(book_info)


def build_path(book_info: dict) -> str:
    '''
    build path to book file
    
    :param book_info: provider of book path info
	:return: book file_path 
    '''
    return '\\'.join(
        [script_path, book_info['main_path'], book_info['enter_path']])


if __name__ == '__main__':
    sql.connect()
    showMain()
    sql.close()
示例#21
0
	def getfromdb(self):
		conn = connect()
		cur = conn.cursor()
		cur.execute('select DoubanId from celebrity')
		for r in cur.fetchmany(100000):
			self.celebritylist.append(r[0])
示例#22
0
import shutil, os
import sql
conn, cursor = sql.connect()
rootDir = os.getcwd()[:-10]

def uploadChall():
    id = sql.getNextId(conn,cursor,'challs')
    title = raw_input("chall title : ")
    flag = raw_input("flag : ")
    tags = raw_input("tags(seperate by space) : ").split()
    draftSrc = '../drafts/{}'.format(title)

    challPath = rootDir+'challs/'+str(id)

    if os.path.isdir(draftSrc):
        shutil.copytree(draftSrc,challPath)
        sql.uploadChallQuery(conn,cursor,id,title,flag,tags)
    else:
        print "draft doesn't exist"

def deleteChall():
    title = raw_input("chall title : ")

    id = sql.challTitleToId(conn,cursor,title)
    challPath = rootDir+'challs/'+str(id)

    shutil.rmtree(challPath)
    sql.deleteChallQuery(conn,cursor,title,id)

def resetChalls():
    sure = raw_input("this will delete every data related to challenge from service"
示例#23
0
import sql

parser = argparse.ArgumentParser()
parser.add_argument("--page_num_max",
                    help="Enter the no. of pages to parse",
                    type=int)
parser.add_argument("--dbname", help="Enter name of the db ", type=str)
args = parser.parse_args()

# Getting HTML
url = "https://www.codewithharry.com/blog/?number="

page_num_MAX = args.page_num_max
scrapped_info_list = []

sql.connect(args.dbname)
for page_num in range(1, (page_num_MAX + 1)):
    url1 = url + str(page_num)
    print("GET request for: " + url1)
    req = requests.get(url1)
    htmlcontent = req.content
    #print(htmlcontent)

    #Parsing
    soup = BeautifulSoup(htmlcontent, 'html.parser')
    #print(soup)

    #HTML tree trasversal
    #Finding all the blogs title
    blog_title = soup.find_all('h2')
    #print(blog_title) #This will result in HTML code
    def _daemon(self):
        # This is a daemon which will update the widget with latest suggestions
        self.connectionRead = sql.connect(True)
        count = 0
        while not xbmc.abortRequested:
            if xbmc.getCondVisibility(
                    "Skin.HasSetting(enable.smartish.widgets)"):
                count += 1
                if count >= 60 or self.movieWidget is None or self.episodeWidget is None or self.albumWidget is None or self.pvrWidget is None:
                    nextWidget = self._getNextWidget()

                    # If no media playing, clear last played
                    if not xbmc.Player().isPlaying():
                        library.lastplayedType = None
                        library.lastplayedID = None

                    if nextWidget is not None:
                        log("### Starting to get widget " + nextWidget)
                        # If live tv is playing, call the mediaStarted function in case channel has changed
                        if self.playingLiveTV:
                            self.mediaStarted(self.connectionRead)

                        # Get the users habits out of the database
                        habits, freshness = sql.getFromDatabase(
                            self.connectionRead, nextWidget)

                        if nextWidget == "movie" and habits == self.lastMovieHabits:
                            log("### Not updating widget")
                            self.movieLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            count = 0
                            continue
                        if nextWidget == "episode" and habits == self.lastEpisodeHabits:
                            log("### Not updating widget")
                            self.episodeLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            count = 0
                            continue
                        if nextWidget == "album" and habits == self.lastAlbumHabits:
                            log("### Not updating widget")
                            self.albumLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            count = 0
                            continue

                        # Pause briefly, and again check that abortRequested hasn't been called
                        xbmc.sleep(100)
                        if xbmc.abortRequested:
                            return

                        # Get all the media items that match the users habits
                        weighted, items = library.getMedia(
                            nextWidget, habits, freshness)

                        # Pause briefly, and again check that abortRequested hasn't been called
                        xbmc.sleep(100)
                        if xbmc.abortRequested:
                            return

                        # Generate the widgets
                        if weighted is not None:
                            listitems = library.buildWidget(
                                nextWidget, weighted, items)
                        else:
                            listitems = []

                        # Save the widget
                        if nextWidget == "movie":
                            log("### Saving movie widget")
                            self.movieWidget = listitems
                            self.movieLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            self.lastMovieHabits = habits
                            self.WINDOW.setProperty("smartish.movies",
                                                    self.movieLastUpdated)
                        elif nextWidget == "episode":
                            log("### Saving episode widget")
                            self.episodeWidget = listitems
                            self.episodeLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            self.lastEpisodeHabits = habits
                            self.WINDOW.setProperty("smartish.episodes",
                                                    self.episodeLastUpdated)
                        elif nextWidget == "pvr":
                            log("### Saving PVR widget")
                            self.pvrWidget = listitems
                            self.pvrLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            self.WINDOW.setProperty("smartish.pvr",
                                                    self.pvrLastUpdated)
                        elif nextWidget == "album":
                            log("### Saving album widget")
                            self.albumWidget = listitems
                            self.albumLastUpdated = strftime(
                                "%Y%m%d%H%M%S", gmtime())
                            self.lastAlbumHabits = habits
                            self.WINDOW.setProperty("smartish.albums",
                                                    self.albumLastUpdated)

                    # Reset counter and update widget type
                    count = 0

            xbmc.sleep(1000)
    def _daemon( self ):
        # This is a daemon which will update the widget with latest suggestions
        self.connectionRead = sql.connect( True )
        count = 0
        while not xbmc.abortRequested:
            if xbmc.getCondVisibility( "Skin.HasSetting(enable.smartish.widgets)" ):
                count += 1
                if count >= 60 or self.movieWidget is None or self.episodeWidget is None or self.albumWidget is None or self.pvrWidget is None:
                    nextWidget = self._getNextWidget()

                    # If no media playing, clear last played
                    if not xbmc.Player().isPlaying():
                        library.lastplayedType = None
                        library.lastplayedID = None

                    if nextWidget is not None:
                        log( "### Starting to get widget " + nextWidget )
                        # If live tv is playing, call the mediaStarted function in case channel has changed
                        if self.playingLiveTV:
                            self.mediaStarted( self.connectionRead )
                            
                        # Get the users habits out of the database
                        habits, freshness = sql.getFromDatabase( self.connectionRead, nextWidget )
                        
                        if nextWidget == "movie" and habits == self.lastMovieHabits:
                            log( "### Not updating widget" )
                            self.movieLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            count = 0
                            continue
                        if nextWidget == "episode" and habits == self.lastEpisodeHabits:
                            log( "### Not updating widget" )
                            self.episodeLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            count = 0
                            continue
                        if nextWidget == "album" and habits == self.lastAlbumHabits:
                            log( "### Not updating widget" )
                            self.albumLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            count = 0
                            continue
                        
                        # Pause briefly, and again check that abortRequested hasn't been called
                        xbmc.sleep( 100 )
                        if xbmc.abortRequested:
                            return
                            
                        # Get all the media items that match the users habits
                        weighted, items = library.getMedia( nextWidget, habits, freshness )
                        
                        # Pause briefly, and again check that abortRequested hasn't been called
                        xbmc.sleep( 100 )
                        if xbmc.abortRequested:
                            return
                            
                        # Generate the widgets
                        if weighted is not None:
                            listitems = library.buildWidget( nextWidget, weighted, items )
                        else:
                            listitems = []
                        
                        # Save the widget
                        if nextWidget == "movie":
                            log( "### Saving movie widget" )
                            self.movieWidget = listitems
                            self.movieLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            self.lastMovieHabits = habits
                            self.WINDOW.setProperty( "smartish.movies", self.movieLastUpdated )
                        elif nextWidget == "episode":
                            log( "### Saving episode widget" )
                            self.episodeWidget = listitems
                            self.episodeLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            self.lastEpisodeHabits = habits
                            self.WINDOW.setProperty( "smartish.episodes", self.episodeLastUpdated )
                        elif nextWidget == "pvr":
                            log( "### Saving PVR widget" )
                            self.pvrWidget = listitems
                            self.pvrLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            self.WINDOW.setProperty( "smartish.pvr", self.pvrLastUpdated )                        
                        elif nextWidget == "album":
                            log( "### Saving album widget" )
                            self.albumWidget = listitems
                            self.albumLastUpdated = strftime( "%Y%m%d%H%M%S",gmtime() )
                            self.lastAlbumHabits = habits
                            self.WINDOW.setProperty( "smartish.albums", self.albumLastUpdated )
                    
                    # Reset counter and update widget type
                    count = 0
                    
            xbmc.sleep( 1000 )