Ejemplo n.º 1
0
 def getCredentials(self):
     aCredential = credentials.credentials()
     self.user = aCredential.user
     self.password = aCredential.password
     self.host = aCredential.host
     self.port = aCredential.port
     self.database = aCredential.database
Ejemplo n.º 2
0
def unfollow():
    creds = credentials.credentials(2)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    seguidores = []

    seguidores = api.followers_ids('HayHilos')
    bar1 = IncrementalBar('Processing:', max=len(seguidores))
    for follower in seguidores:
        try:
            api.destroy_friendship(follower)
            usuarioSeguido = api.get_user(follower)
            bar1.next()
            #print('User is no longer being followed: @' + usuarioSeguido.screen_name)
            time.sleep(3)

        except:
            print('\nThe user couldn\'t been unfollowed')
            time.sleep(60)
    bar1.finish()
Ejemplo n.º 3
0
def status(account):
    creds = credentials.credentials(1)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    user = api.get_user(account)
    userInfo = user._json
    print('User: '******'name'])
    print('')
    print('Description: "', userInfo['description'], '"')
    print('')
    print('Number of tweets: ', userInfo['statuses_count'])
    print('')
    followers = int(userInfo['followers_count'])
    friends = int(userInfo['friends_count'])
    nonFollowers = friends - followers
    if nonFollowers < 0:
        nonFollowers = 'You have not non followers'
    print('Followers: ', followers, "\nFollowing: ", friends,
          '\nFollow-Friends count: ', nonFollowers, '\n')
    enter = input('\n\nPress enter to go back to menu.')
Ejemplo n.º 4
0
def lagre2postgis(data, foupostgis=False):
    """Lagrer til lokal postgis installasjon"""

    cred = credentials()
    # mycred = cred['localpostgis']
    if foupostgis:
        mycred = cred['foupostgis']
    else:
        mycred = cred['localpostgis']

    conn = psycopg2.connect(database=mycred['database'],
                            user=mycred['user'],
                            password=mycred['pw'],
                            host=mycred['host'])
    curs = conn.cursor()

    curs.execute('DROP TABLE IF EXISTS bomstasjoner')

    curs.execute(
        'CREATE TABLE bomstasjoner(geom geometry, id integer PRIMARY KEY NOT NULL, navn text, anlId integer, bomId integer, ekteretning text, felt text, innkrevingsretning text, vegnettretn real, metreringretn real, kompassretn real, muligeFelt text, status text, veg text, veglenke integer, veglenkepos double precision   )'
    )
    conn.commit()

    for bom in data:
        #curs.execute( 'INSERT INTO bomstasjoner( geom, id, Navn, anlId, bomId, ekteretning, felt, innkrevingsretning, kompassretn, muligeFelt, status, veg, veglenke, veglenkepos )'
        #                'VALUES( ST_SetSRID(%(geom)s::geometry, %(srid)s), %(id)s, %(Navn)s, %(anlId)s, %(bomId)s, %(ekteretning)s, %(felt), %(innkrevingsretning), %(kompassretn), %(muligeFelt), %(status), %(veg), %(veglenke), %(veglenkepos) )' ,
        #               bom)
        # conn.commit()
        curs.execute(
            'INSERT INTO bomstasjoner( geom, id, navn, anlid, bomid, ekteretning, felt, innkrevingsretning, vegnettretn, metreringretn, kompassretn, muligefelt, status, veg, veglenke, veglenkepos)'
            'VALUES( ST_SetSRID(%(geom)s::geometry, %(srid)s), %(id)s, %(Navn)s, %(anlId)s, %(bomId)s, %(ekteretning)s, %(felt)s, %(innkrevingsretning)s, %(vegnettretn)s, %(metreringretn)s, %(kompassretn)s, %(muligeFelt)s, %(status)s, %(veg)s, %(veglenke)s, %(veglenkepos)s )',
            bom)
        conn.commit()
Ejemplo n.º 5
0
def unfollowNon():
    creds = credentials.credentials(2)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    arrFriends = api.friends_ids(screen_name='HayHilos')
    arrFollowers = api.followers_ids(screen_name='HayHilos')
    print("Unfollow process started...\n")
    contador = 0
    arrFr = len(arrFriends)
    arrFo = len(arrFollowers)
    diferencia = int(arrFr)-int(arrFo)
    bar1 = ChargingBar('Processing:', max=diferencia)
    try:
        for follower in arrFriends:
            if follower not in arrFollowers:
                api.destroy_friendship(follower)
                time.sleep(5)
                contador += 1
                bar1.next()
                if contador >= 50:
                    contador = 0
                    time.sleep(180)
        bar1.finish()
        print('\nProcess completed successfully.')
    except tweepy.RateLimitError:
        print('\nAn error ocurred.')
        time.sleep(15 * 60)

    print('\n')
Ejemplo n.º 6
0
def esperarConfirmacion():
    global respuesta
    confirmacionRecibida = True
    creds = credentials.credentials(1)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    print('\nAwaiting confirmation...')
    time.sleep(300)
    while confirmacionRecibida:
        lastMsg = api.list_direct_messages(6)
        respuesta = lastMsg[0]
        respuesta = str(respuesta.message_create)
        empieza = respuesta.find('text')
        termina = respuesta.find('entities')
        respuestaReal = respuesta[empieza:termina]
        if 'Si quiero Boti.' in respuestaReal:
            print("\nAffirmative answer.")
            respuesta = 'Si'
            confirmacionRecibida = False
        elif 'No quiero Boti.' in respuestaReal:
            print('\nNegative answer.')
            respuesta = 'No'
            confirmacionRecibida = False
        else:
            time.sleep(1200)
    return respuesta
Ejemplo n.º 7
0
 def test_save_multiple_accounts(self):
     '''
     test to check if one can save multiple accounts
     '''
     self.new_account.save_account()
     test_account = credentials("Account","Testname","TestPass")
     test_account.save_account()
     self.assertEqual(len(credentials.credential_list),2)
Ejemplo n.º 8
0
 def __init__(self, symbol):
     self.symbol = symbol
     self.credentials = credentials()
     self.s = SessionActivator(self.credentials).activateSession()
     self.session = self.s['session']
     self.connectionToken = self.s['connectionToken']
     self.browserController = BrowserController(self.credentials)
     self.checkWikifolio = CheckWikifolio(self.session, self.symbol)
Ejemplo n.º 9
0
 def test_delete_credentials(self):
     '''
     test to check if one can delete account credentials
     '''
     self.new_account.save_account()
     test_account = credentials("Account","Testname","TestPass")
     test_account.save_account()
     self.new_account.delete_account()
     self.assertEqual(len(credentials.credential_list),1)
Ejemplo n.º 10
0
 def test_find_account_by_account_name(self):
     '''
     test to search for account details
     '''
     self.new_account.save_account()
     test_account = credentials("Account","Testname","TestPass")
     test_account.save_account()
     found_account = credentials.find_by_account("Account")
     self.assertEqual(found_account.user_name, test_account.user_name)
Ejemplo n.º 11
0
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

        self.c = creds.credentials()
        api_key = str(self.c.client_id)
        self.gp = google.google_photos(api_key=api_key)
 def test_save_multiple_credentials(self):
     '''
     test_save_multiple_credentials to check if we can save multiple credentials
     objects to our credentials_list
     '''
     self.new_credentials.save_credentials()
     test_credentials = credentials("*****@*****.**", "199b")
     test_credentials.save_credentials()
     self.assertEqual(len(credentials.credentials_list), 2)
    def test_delete_credentials(self):
        '''
        test_delete_personinfo to test if we can remove a personinfo from our personinfo list
        '''
        self.new_credentials.save_credentials()
        test_credentials = credentials("*****@*****.**", "199b")
        test_credentials.save_credentials()

        self.new_credentials.delete_credentials()
        self.assertEqual(len(credentials.credentials_list), 1)
    def test_credentials_exists(self):
        '''
        test to check if we can return a Boolean  if we cannot find the credentials.
        '''

        self.new_credentials.save_credentials()
        test_credentials = credentials("*****@*****.**", "199b")
        test_credentials.save_credentials()

        credentials_exists = credentials.credentials_exist(
            "*****@*****.**")

        self.assertTrue(credentials_exists)
    def test_find_credentials_by_twitter_account(self):
        '''
        test to check if we can find a credentials by twitter_account  and display information
        '''

        self.new_credentials.save_credentials()
        test_credentials = credentials("*****@*****.**",
                                       "199b")  # new credentials
        test_credentials.save_credentials()

        found_credentials = credentials.find_by_twitter_account(
            "*****@*****.**")

        self.assertEqual(found_credentials.twitter_account,
                         test_credentials.twitter_account)
Ejemplo n.º 16
0
def confirmar(full_textPlus, full_text):
    condicion = 'No'
    intentos = 0
    tomiID = '286367061'
    while intentos <= 4:
        try:
            creds = credentials.credentials(1)
            consumer_key = creds[0]
            consumer_secret = creds[1]
            access_token = creds[2]
            access_token_secret = creds[3]
            auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
            auth.set_access_token(access_token, access_token_secret)
            api = tweepy.API(auth)
            print('\nSending confirmation question... ', time.strftime("%X"))
            respRapida = 'options'
            try:
                api.send_direct_message(recipient_id=tomiID,
                                        text=full_textPlus,
                                        quick_reply_type=respRapida)
            except:
                api.send_direct_message(recipient_id=tomiID,
                                        text=full_text,
                                        quick_reply_type=respRapida)
            intentos = 10
            condicion = 'Si'
            #print(intentos)
            time.sleep(1200)
            break
        except:
            print('\nSending confirmation question FAILED... ',
                  time.strftime("%X"))
            time.sleep(300)
            intentos += 1
            if intentos >= 3:
                print("\nTwitt: " + full_text + "\n")
                print(
                    'La confirmacion ha fallado, por favor ingrese "Si" para retwittear, o ingrese "No" para no retwittear.\n'
                )
                respuesta = input("Ingrese su decision: ")
                resp = respuesta.lower()
                if resp == "si":
                    condicion = 'Si'
                elif resp == "no":
                    condicion = "No"
    return condicion
Ejemplo n.º 17
0
def compareOwnFollows():
    creds = credentials.credentials(1)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    arrFriends = api.friends_ids(screen_name='HayHilos')
    arrFollowers = api.followers_ids(screen_name='HayHilos')
    print("\n Users than not follows you: ")
    for follower in arrFriends:
        if follower not in arrFollowers:
            nonFollower = api.get_user(follower)
            print('@' + nonFollower.screen_name)
    print('\n')
Ejemplo n.º 18
0
def verify():
    cont = 1
    while cont <= 2:
        try:
            creds = credentials.credentials(cont)
            consumer_key = creds[0]
            consumer_secret = creds[1]
            access_token = creds[2]
            access_token_secret = creds[3]
            auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
            auth.set_access_token(access_token, access_token_secret)
            api = tweepy.API(auth)
            cont += 1
            api.verify_credentials()
            print('\n' + autentications[cont - 2] + " authentication OK.")
            time.sleep(2)
        except:
            print("\nError during authentication. \n")
            time.sleep(2)
Ejemplo n.º 19
0
def compareFollowers(user):
    creds = credentials.credentials(1)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    arrFw = api.followers_ids(screen_name='HayHilos')
    arrOtherFw = api.followers_ids(screen_name=user)
    totalArr = len(arrOtherFw)
    for follower in arrFw:
        if follower in arrOtherFw:
            arrOtherFw.pop()

    perCnt = (len(arrOtherFw) * 100) / totalArr

    print('For @', user, ' followers:\n\nThe ', 100 - perCnt,
          '% are following you (', totalArr - len(arrOtherFw),
          ' followers),\nThe ', perCnt, '% are not following you (',
          len(arrOtherFw), ' followers).')
    enter = input('\n\nPress enter to go back to menu.')
Ejemplo n.º 20
0
 def test_make_tmp(self):
     credentials.credentials(root=ROOT)
     r = os.path.relpath(ROOT)
     p = os.path.join(r,"tmp")
     self.assertTrue(os.path.exists(p))
Ejemplo n.º 21
0
 def test_return(self):
     c = credentials.credentials(root=ROOT)
     self.assertEqual(c.filename, ROOT+"/tmp/.credentials")
     self.assertEqual(c.dir, ROOT+"/tmp")        
Ejemplo n.º 22
0
def tweet():
    creds = credentials.credentials(2)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    print("Boti esta iniciando")
    queries = ["Abro Hilo", "Abro hilo", "abro hilo"]
    mensajes = [
        'Siguenos y mantente al tanto de todo lo que esta pasando #QueHilosHay #AbroHilo #HilosDeTwitter'
    ]
    #'Hola! Los invitamos a pasarse por nuestro perfil para estar al tanto de todos los hilos que son tendencia y ayudarnos con un follow! #QueHilosHay #AbroHilo #HilosDeTwitter']

    msj = [
        'Nuevo hilo #QueHilosHay #AbroHilo #HilosDeTwitter',
        'Ya viste este hilo? #QueHilosHay #AbroHilo #HilosDeTwitter',
        'Te traemos un nuevo hilo #QueHilosHay #AbroHilo #HilosDeTwitter',
        'Otro hilo más! #QueHilosHay #AbroHilo #HilosDeTwitter',
        'Dejo este hilo por aca... #QueHilosHay #AbroHilo #HilosDeTwitter',
        'Habemus hilo nuevo! #QueHilosHay #AbroHilo #HilosDeTwitter'
    ]

    tweets_per_query = 300
    loop = True
    ownTweet = 0
    notRetweeted = 0
    minimo = [100000]
    crasheos = 0
    num = 0
    fechaTweet = False
    confirmado = ''
    resp = ''
    nacChecked = ''
    textChecked = ''
    while loop:
        try:
            for monto in minimo:
                # print('Searching tweets with more than '+ minimo[monto] +' retweets')
                print("Volvi a empezar.")
                new_tweets = 0
                for querry in queries:
                    if ownTweet >= 2:
                        time.sleep(240)
                        ownTweet = 0
                    if notRetweeted >= 20:
                        time.sleep(180)
                        notRetweeted = 0
                    print("")
                    print("#" * 39)
                    print("#    Starting new query: " + querry + "    #")
                    print("#" * 39)
                    print("")
                    for tweet in tweepy.Cursor(
                            api.search, q=querry,
                            tweet_mode="extended").items(tweets_per_query):
                        user = tweet.user.screen_name
                        id = tweet.id
                        # print(tweet)
                        retweets = tweet.retweet_count
                        url = 'https://twitter.com/' + user + '/status/' + str(
                            id)
                        try:
                            text = tweet.retweeted_status.full_text.lower()
                        except:
                            text = tweet.full_text.lower()
                        if "Abro Hilo" in text or "Abro hilo" in text or "abro hilo" in text:
                            txtt = open("docs/idsRT.txt")
                            txt = txtt.read()
                            try:
                                rtStatus = tweet.retweeted_status.id_str
                            except:
                                rtStatus = tweet.id_str
                            txtt.close()
                            print(url)
                            # print('retweets: '+retweets)
                            nacionalidad = ''
                            todayMonth = date.today().month
                            try:
                                tweetMonth = tweet.retweeted_status.created_at.month
                            except:
                                tweetMonth = tweet.created_at.month
                            if todayMonth == tweetMonth or todayMonth == tweetMonth - 1:
                                fechaTweet = True
                            if 'RT' in tweet.full_text and retweets >= 400 and fechaTweet:
                                nacionalidad = tweet.user._json['location']
                                nacChecked = controller.checkNation(
                                    nacionalidad, 'Nation')
                            try:
                                print("Retweets: " + retweets)
                            except:
                                print(retweets)
                            try:
                                if nacionalidad != '':
                                    print('Location: ' + nacionalidad)
                                else:
                                    print('Location: Undefined')
                            except:
                                print('Location: Undefined')
                            retwittear = True
                            # textChecked = controller.checkNation(tweet.full_text, 'Text')
                            if tweet.id_str in txt or rtStatus in txt or retweets < 400 or nacChecked:
                                retwittear = False
                            else:
                                try:
                                    try:
                                        textChecked = controller.checkNation(
                                            tweet.full_text, 'Text')
                                        if textChecked:
                                            retwittear = False
                                    except:
                                        nacionalidadUser = tweet.retweeted_status.user._json[
                                            'location']
                                        textChecked = controller.checkNation(
                                            nacionalidadUser, 'Text')
                                        if textChecked:
                                            retwittear = False
                                except:
                                    pass
                            if retwittear:
                                if 'RT' in tweet.full_text:
                                    textRtFv = tweet.retweeted_status.full_text + '\nRts: ', str(
                                        tweet.retweeted_status.retweet_count
                                    ) + '\nFavs: ', str(
                                        tweet.retweeted_status.favorite_count)
                                    resp = confirmation.confirmar(
                                        textRtFv,
                                        tweet.retweeted_status.full_text)
                                else:
                                    textRtFv = tweet.full_text + '\nRts: ' + str(
                                        tweet.retweet_count
                                    ) + '\nFavs: ' + str(tweet.favorite_count)
                                    resp = confirmation.confirmar(
                                        textRtFv, tweet.full_text)
                                if resp == 'Si':
                                    confirmado = confirmation.esperarConfirmacion(
                                    )
                                if confirmado == 'Si':
                                    txt = open("docs/idsRT.txt", "a")
                                    try:
                                        miUrl = url
                                        if num > 5:
                                            num = 0
                                        twit = msj[num]
                                        num += 1
                                        api.update_status(
                                            status=twit,
                                            in_reply_to_status_id=tweet.id_str,
                                            attachment_url=miUrl)
                                        print("\n\t √ Retweeted")
                                        print("")
                                        new_tweets += 1
                                        ownTweet += 1
                                        try:
                                            if "RT" in tweet.full_text:
                                                idSaved = tweet.retweeted_status.id_str
                                                txt.write(idSaved + "\n")
                                                txt.close()
                                            else:
                                                idSaved = tweet.id_str
                                                txt.write(idSaved + "\n")
                                                txt.close()
                                        except:
                                            pass
                                        try:
                                            pass
                                            replyTo = tweet.retweeted_status.user.screen_name
                                            reply = "@" + replyTo + " Hola, los invitamos a pasar por nuestro perfil para estar al tanto de todos los hilos que son tendencia y ayudarnos con un follow! #QueHilosHay #AbroHilo #HilosDeTwitter"
                                            api.update_status(
                                                reply,
                                                tweet.retweeted_status.id_str)
                                        except:
                                            pass
                                        time.sleep(1400)
                                    except tweepy.TweepError as e:
                                        # miUrl = url
                                        # api.update_status('Síguenos para enterarte de los mejores hilos de twitter!! #QueHilosHay #AbroHilo', str(id), attach_url=miUrl)

                                        print('\n\t ! Not Retweeted')
                                        print("")
                                        notRetweeted += 1
                                        txt.close()
                                elif confirmado == 'No':
                                    txt = open("docs/idsRT.txt", "a")
                                    if "RT" in tweet.full_text:
                                        idSaved = tweet.retweeted_status.id_str
                                        txt.write(idSaved + "\n")
                                        txt.close()
                                    else:
                                        idSaved = tweet.id_str
                                        txt.write(idSaved + "\n")
                                        txt.close()
                            else:
                                print('\n\t ! Not Retweeted')
                                print("")
                                txt = open("docs/idsRT.txt", "a")
                                if "RT" in tweet.full_text:
                                    idSaved = tweet.retweeted_status.id_str
                                    txt.write(idSaved + "\n")
                                    txt.close()
                                else:
                                    idSaved = tweet.id_str
                                    txt.write(idSaved + "\n")
                                    txt.close()
            print("New Tweets: " + str(new_tweets))
        except:
            crasheos += 1
            print("#" * 60)
            print("#" * 60)
            print("#" * 60)
            print("\t Crasheo el programa, reconectando...")
            print("#" * 60)
            print("#" * 60)
            print("#" * 60)
            time.sleep(100)
            if crasheos >= 2:
                print(".")
                time.sleep(1)
                print(".")
                time.sleep(1)
                print(".")
                time.sleep(1)
                print(".")
                time.sleep(1)
                print(".")
                time.sleep(1)
                print(".")
                print("Reiniciando el servicio...\n")
                print(time.strftime("%X"))
                time.sleep(1000)
                crasheos = 0
Ejemplo n.º 23
0
 def test_first_run(self):
     password = "******"
     encrypted_password = credentials.credentials(root=ROOT).encrypt(password)
     decrypted_password = credentials.credentials(root=ROOT).decrypt(encrypted_password)
     self.assertEqual(password,decrypted_password)
Ejemplo n.º 24
0
	def load_user_data():
		self.consumer_key = credentials().consumer_key
		self.consumer_secret = credentials().consumer_secret
		self.access_token = credentials().access_token
		self.access_token_secret = credentials().access_token_secret
Ejemplo n.º 25
0
import tweepy
import credentials

creds = credentials.credentials(1)
consumer_key = creds[0]
consumer_secret = creds[1]
access_token = creds[2]
access_token_secret = creds[3]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

info = api.get_user('tricolorbolso96')
print(info)
'''
full_text = 'probando funcionalidad'
tomiID = '286367061'
print('\nSending confirmation question...')
respRapida = 'options'
api.send_direct_message(recipient_id=tomiID, text=full_text, quick_reply_type=respRapida)
print'''
Ejemplo n.º 26
0
# change directory
import os
root = os.path.dirname(os.path.realpath(__file__))
os.chdir(root)

import time
from datetime import timedelta, datetime

# load or get user credentials

import credentials 
my_credentials = credentials.credentials()
my_credentials.load()

import iofunctions

# post data

import urllib

# Fetch data
from bs4 import BeautifulSoup
import re

try:
    import pycurl
    
    #### load login form
    #pycurl.global_init(pycurl.GLOBAL_SSL)
    f = open('tmp/StudentCentre.html','w')
    c = pycurl.Curl()
Ejemplo n.º 27
0
 def setUp(self):
     '''
     set up method to run before each test cases
     '''
     self.new_account = credentials("Account","Testname","TestPass")
Ejemplo n.º 28
0
def create_account(account_name, user_name, password):
    '''
    function to create new account
    '''
    new_account = credentials(account_name, user_name, password)
    return new_account
Ejemplo n.º 29
0
def create_credentials(twitter_account, password):
    """
    Function to create new credentials
    """
    new_credentials = credentials("*****@*****.**", "199b")
    return new_credentials
Ejemplo n.º 30
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:

            try:
                # Create the renderer, the render window, and the interactor. The renderer
                # draws into the render window, the interactor enables mouse- and
                # keyboard-based interaction with the scene.
                ren = vtk.vtkRenderer()
                renWin = vtk.vtkRenderWindow()
                renWin.AddRenderer(ren)
                iren = vtk.vtkRenderWindowInteractor()
                iren.SetRenderWindow(renWin)
                iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

                cred = credentials()

                mydb = mysql.connector.connect(host="localhost",
                                               user=cred[0],
                                               password=cred[1],
                                               database="iqweb")

                mycursor = mydb.cursor()
                sql = "SELECT path FROM image WHERE seriesuid = %s"
                params = (self.uid, )
                mycursor.execute(sql, params)

                files = mycursor.fetchall()
                fileset = vtk.vtkStringArray()
                for file in files:
                    fileset.InsertNextValue(file[0])

                sorter = vtk.vtkDICOMFileSorter()
                sorter.SetInputFileNames(fileset)
                sorter.Update()

                sortedFiles = vtk.vtkStringArray()
                sortedFiles = sorter.GetFileNamesForSeries(0)

                reader = vtk.vtkDICOMReader()
                reader.AutoRescaleOff()  #only because our preset is shifted
                reader.SetFileNames(sortedFiles)
                reader.Update()

                # The volume will be displayed by ray-cast alpha compositing.
                # A ray-cast mapper is needed to do the ray-casting, and a
                # compositing function is needed to do the compositing along the ray.
                volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
                volumeMapper.SetInputConnection(reader.GetOutputPort())
                volumeMapper.SetBlendModeToComposite()
                volumeMapper.AutoAdjustSampleDistancesOff()
                volumeMapper.UseJitteringOn()

                # The color transfer function maps voxel intensities to colors.
                # It is modality-specific, and often anatomy-specific as well.
                # The goal is to one color for flesh (between 500 and 1000)
                # and another color for bone (1150 and over).
                volumeColor = vtk.vtkColorTransferFunction()
                volumeColor.AddRGBPoint(1024, 0.53125, 0.171875, 0.0507813)
                volumeColor.AddRGBPoint(1031, 0.488281, 0.148438, 0.0351563)
                volumeColor.AddRGBPoint(1000, 0.589844, 0.0257813, 0.0148438)
                volumeColor.AddRGBPoint(1170, 0.589844, 0.0257813, 0.0148438)
                volumeColor.AddRGBPoint(1181, 0.957031, 0.996094, 0.878906)
                volumeColor.AddRGBPoint(2024, 0.976563, 0.996094, 0.929688)
                volumeColor.AddRGBPoint(3014, 0.488281, 0.488281, 0.488281)

                # The opacity transfer function is used to control the opacity
                # of different tissue types.
                volumeScalarOpacity = vtk.vtkPiecewiseFunction()
                #volumeScalarOpacity.AddPoint(0,    0.00)
                #volumeScalarOpacity.AddPoint(500,  0.15)
                #volumeScalarOpacity.AddPoint(1000, 0.15)
                #volumeScalarOpacity.AddPoint(1150, 0.85)

                volumeScalarOpacity.AddPoint(1131, 0)
                volumeScalarOpacity.AddPoint(1463, 1)
                volumeScalarOpacity.AddPoint(3135, 1)

                # The gradient opacity function is used to decrease the opacity
                # in the "flat" regions of the volume while maintaining the opacity
                # at the boundaries between tissue types.  The gradient is measured
                # as the amount by which the intensity changes over unit distance.
                # For most medical data, the unit distance is 1mm.
                volumeGradientOpacity = vtk.vtkPiecewiseFunction()
                volumeGradientOpacity.AddPoint(0, 0.0)
                volumeGradientOpacity.AddPoint(90, 0.9)
                volumeGradientOpacity.AddPoint(100, 1.0)

                # The VolumeProperty attaches the color and opacity functions to the
                # volume, and sets other volume properties.  The interpolation should
                # be set to linear to do a high-quality rendering.  The ShadeOn option
                # turns on directional lighting, which will usually enhance the
                # appearance of the volume and make it look more "3D".  However,
                # the quality of the shading depends on how accurately the gradient
                # of the volume can be calculated, and for noisy data the gradient
                # estimation will be very poor.  The impact of the shading can be
                # decreased by increasing the Ambient coefficient while decreasing
                # the Diffuse and Specular coefficient.  To increase the impact
                # of shading, decrease the Ambient and increase the Diffuse and Specular.
                volumeProperty = vtk.vtkVolumeProperty()
                volumeProperty.SetColor(volumeColor)
                volumeProperty.SetScalarOpacity(volumeScalarOpacity)
                volumeProperty.SetGradientOpacity(volumeGradientOpacity)
                volumeProperty.SetInterpolationTypeToLinear()
                volumeProperty.ShadeOn()
                volumeProperty.SetAmbient(0.4)  # 0.1
                volumeProperty.SetDiffuse(0.5)  # 0.9
                volumeProperty.SetSpecular(0.2)  # 0.2
                volumeProperty.SetSpecularPower(10)

                # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
                # and orientation of the volume in world coordinates.
                volume = vtk.vtkVolume()
                volume.SetMapper(volumeMapper)
                volume.SetProperty(volumeProperty)

                # Finally, add the volume to the renderer
                ren.AddViewProp(volume)

                # Set up an initial view of the volume.  The focal point will be the
                # center of the volume, and the camera position will be 400mm to the
                # patient's left (which is our right).
                camera = ren.GetActiveCamera()
                c = volume.GetCenter()
                camera.SetFocalPoint(c[0], c[1], c[2])
                camera.SetPosition(c[0] + 400, c[1], c[2])
                camera.SetViewUp(0, 0, -1)

                # Increase the size of the render window
                #renWin.SetSize(640, 480)
                #renWin.SetSize(432, 336)
                renWin.SetSize(320, 240)

                # Interact with the data.
                #iren.Initialize()
                renWin.Render()

                # vtkweb
                self.getApplication().GetObjectIdMap().SetActiveObject(
                    "VIEW", renWin)
            except:
                print("Unexpected error:", sys.exc_info()[0])
Ejemplo n.º 31
0
 def setUp(self):
     self.c = credentials.credentials(root=ROOT)
     self.c.get(input_func=my_input("23958461"),pass_input_func=my_input("password"))
     self.username = "******"
     self.password = "******"
     self.email = "*****@*****.**"
Ejemplo n.º 32
0
import tweepy
from pymongo import MongoClient
import json
from credentials import credentials # Class containing credentials for OAuth on twitter. Secret.

# Getting the credentials to get authenticated.
consumer_key = credentials().consumer_key
consumer_secret = credentials().consumer_secret
access_token = credentials().access_token
access_token_secret = credentials().access_token_secret

# Connecting to local mongodb instance
client = MongoClient()
db = client.antibiotic_tweets
tweets = db.tweets

class listener(tweepy.StreamListener):
	def on_data(self, data):
		tweets.insert_one(json.loads(data))
		print "Tweet recorded..."
		return True

	def on_error(self, status):
		print status


auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitterstream = tweepy.Stream(auth, listener())
twitterstream.filter(track=['antibiotic'])
Ejemplo n.º 33
0
 def test_save(self):
     # check if get makes credentials file
     c = credentials.credentials(root=ROOT)
     p = os.path.relpath(c.filename)
     c.get(input_func=my_input("23958461"),pass_input_func=my_input("password"))
     self.assertTrue(os.path.exists(p))
 def setUp(self):
     '''
     Set up method to run before each test cases.
     '''
     self.new_credentials = credentials("*****@*****.**",
                                        "199b")  # create credentials object
Ejemplo n.º 35
0
 def test_returns_with_U(self):
     c = credentials.credentials(root=ROOT)
     c.get(input_func=my_input("U23958461"),pass_input_func=my_input("password"))
     self.assertEqual(c.username, "23958461")
     self.assertEqual(c.password, "password")  
     self.assertEqual(c.email, "*****@*****.**")      
from oauth2client import tools
import credentials
from googleapiclient.discovery import build
from apiclient.http import MediaFileUpload

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

##sending params to get credentials
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'MARS PHOTO UPLOADER'
creds_obj = credentials.credentials(SCOPES, CLIENT_SECRET_FILE,
                                    APPLICATION_NAME)
credentials = creds_obj.get_credentials()

##creating link
http = credentials.authorize(httplib2.Http())
drive_service = build('drive', 'v3', http)


##upload files to mars_photos folder
def upload(filename, filepath, mimetype):
    folder_id = '1Ew6RTaoTrlJNfurpjQfHWaI6x9etGwH2'
    file_metadata = {'name': filename, 'parents': [folder_id]}
    media = MediaFileUpload(filepath, mimetype=mimetype, resumable=True)
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
Ejemplo n.º 37
0
 def __init__(self):
     self.auth_url = 'https://accounts.google.com/o/oauth2/v2/auth'
     self.token_endpoint = 'https://www.googleapis.com/oauth2/v4/token'
     #self.code_challenge = base64.b64encode(generate_random_string(100))
     self.c = credentials.credentials()
Ejemplo n.º 38
0
def follow():
    creds = credentials.credentials(1)
    consumer_key = creds[0]
    consumer_secret = creds[1]
    access_token = creds[2]
    access_token_secret = creds[3]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    seguidores = []
    seguidos = 0
    nombres = []
    nombres = input("Please insert de screen names: ").strip().split(" ")
    print('')
    for nombre in nombres:
        print('Starting following the users that follows to: ' + nombre)
        user_info = api.get_user(nombre)
        fallos = 0
        try:
            seguidores = api.followers_ids(nombre)
        except:
            user_info = api.get_user(nombre)
            seguidores = api.followers_ids(user_info.id)
        users = []
        for follower in seguidores:
            t = 15
            #print(len(str(follower)))
            if len(str(follower)) == 19:
                try:
                    txt = open("docs/idsF.txt")
                    txtR = txt.read()
                    txt.close()
                    #   print(txtR)
                    if str(follower) not in txtR:
                        txtF = open('./docs/F2F.txt')
                        txtF2F = txtF.read()
                        if txtF2F == 0 or txtF2F == '0':
                            api.create_friendship(follower)
                            usuarioSeguido = api.get_user(follower)
                            print('The user has been followed: @'+ usuarioSeguido.screen_name)
                            fallos = 0
                            txtW = open("docs/idsF.txt", "a")
                            txtW.write(str(follower) + "\n")
                            txtW.close()
                            seguidos += 1
                            t = 15
                        else:
                            user = api.get_user(follower)
                            userInfo = user._json
                            usuarioSeguido = api.get_user(follower)
                            limit = int(txtF2F)
                            flw = int(userInfo['followers_count'])
                            if flw >= limit:
                                api.create_friendship(follower)
                                print('The user has been followed: @' + usuarioSeguido.screen_name)
                                fallos = 0
                                txtW = open("docs/idsF.txt", "a")
                                txtW.write(str(follower) + "\n")
                                txtW.close()
                                seguidos += 1
                                t = 15
                            else:
                                print('User cannot reach the conditions.')
                                t = 5

                        if seguidos == 400:
                            break
                        time.sleep(t)

                except:
                    if fallos >= 3:
                        break
                    print('The user couldn\'t been followed')
                    fallos += 1
                    time.sleep(60)
Ejemplo n.º 39
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            vtk_override_protocols.vtkWebPublishImageDelivery(decode=False))

        # Custom API
        self.registerVtkWebProtocol(VtkCone())

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_Server.authKey)

        if not _Server.view:

            # draw the borders of a renderer's viewport
            def ViewportBorder(renderer, color, last):
                # points start at upper right and proceed anti-clockwise
                points = vtk.vtkPoints()
                points.SetNumberOfPoints(4)
                points.InsertPoint(0, 1, 1, 0)
                points.InsertPoint(1, 0, 1, 0)
                points.InsertPoint(2, 0, 0, 0)
                points.InsertPoint(3, 1, 0, 0)

                # create cells, and lines
                cells = vtk.vtkCellArray()
                cells.Initialize()

                lines = vtk.vtkPolyLine()

                # only draw last line if this is the last viewport
                # this prevents double vertical lines at right border
                # if different colors are used for each border, then do
                # not specify last
                if (last):
                    lines.GetPointIds().SetNumberOfIds(5)
                else:
                    lines.GetPointIds().SetNumberOfIds(4)

                for i in range(0, 4):
                    lines.GetPointIds().SetId(i, i)

                if (last):
                    lines.GetPointIds().SetId(4, 0)

                cells.InsertNextCell(lines)

                # now make tge polydata and display it
                poly = vtk.vtkPolyData()
                poly.Initialize()
                poly.SetPoints(points)
                poly.SetLines(cells)

                # use normalized viewport coordinates since
                # they are independent of window size
                coordinate = vtk.vtkCoordinate()
                coordinate.SetCoordinateSystemToNormalizedViewport()

                mapper = vtk.vtkPolyDataMapper2D()
                mapper.SetInputData(poly)
                mapper.SetTransformCoordinate(coordinate)

                actor = vtk.vtkActor2D()
                actor.SetMapper(mapper)
                actor.GetProperty().SetColor(color)
                actor.GetProperty().SetLineWidth(2.0)

                renderer.AddViewProp(actor)

            def getViewport(viewNr):
                if viewNr == 0:
                    return [0.0, 0.5, 0.5, 1.0]
                elif viewNr == 1:
                    return [0.5, 0.5, 1.0, 1.0]
                elif viewNr == 2:
                    return [0.0, 0.0, 0.5, 0.5]
                elif viewNr == 3:
                    return [0.5, 0.0, 1.0, 0.5]
                else:
                    logging.warning('invalid view nr {}'.format(viewNr))
                    return [0.0, 0.0, 1.0, 1.0]

            def doVolumeRendering(renWin, reader, viewNr):
                # The volume will be displayed by ray-cast alpha compositing.
                # A ray-cast mapper is needed to do the ray-casting, and a
                # compositing function is needed to do the compositing along the ray.
                volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
                volumeMapper.SetInputConnection(reader.GetOutputPort())
                volumeMapper.SetBlendModeToComposite()
                volumeMapper.AutoAdjustSampleDistancesOff()
                volumeMapper.UseJitteringOn()

                offset = -1024

                # The color transfer function maps voxel intensities to colors.
                # It is modality-specific, and often anatomy-specific as well.
                # The goal is to one color for flesh (between 500 and 1000)
                # and another color for bone (1150 and over).
                volumeColor = vtk.vtkColorTransferFunction()
                volumeColor.AddRGBPoint(1024 + offset, 0.53125, 0.171875,
                                        0.0507813)
                volumeColor.AddRGBPoint(1031 + offset, 0.488281, 0.148438,
                                        0.0351563)
                volumeColor.AddRGBPoint(1000 + offset, 0.589844, 0.0257813,
                                        0.0148438)
                volumeColor.AddRGBPoint(1170 + offset, 0.589844, 0.0257813,
                                        0.0148438)
                volumeColor.AddRGBPoint(1181 + offset, 0.957031, 0.996094,
                                        0.878906)
                volumeColor.AddRGBPoint(2024 + offset, 0.976563, 0.996094,
                                        0.929688)
                volumeColor.AddRGBPoint(3014 + offset, 0.488281, 0.488281,
                                        0.488281)

                # The opacity transfer function is used to control the opacity
                # of different tissue types.
                volumeScalarOpacity = vtk.vtkPiecewiseFunction()
                #volumeScalarOpacity.AddPoint(0,    0.00)
                #volumeScalarOpacity.AddPoint(500,  0.15)
                #volumeScalarOpacity.AddPoint(1000, 0.15)
                #volumeScalarOpacity.AddPoint(1150, 0.85)

                volumeScalarOpacity.AddPoint(1131 + offset, 0)
                volumeScalarOpacity.AddPoint(1463 + offset, 1)
                volumeScalarOpacity.AddPoint(3135 + offset, 1)

                # The gradient opacity function is used to decrease the opacity
                # in the "flat" regions of the volume while maintaining the opacity
                # at the boundaries between tissue types.  The gradient is measured
                # as the amount by which the intensity changes over unit distance.
                # For most medical data, the unit distance is 1mm.
                volumeGradientOpacity = vtk.vtkPiecewiseFunction()
                volumeGradientOpacity.AddPoint(0, 0.0)
                volumeGradientOpacity.AddPoint(90, 0.9)
                volumeGradientOpacity.AddPoint(100, 1.0)

                # The VolumeProperty attaches the color and opacity functions to the
                # volume, and sets other volume properties.  The interpolation should
                # be set to linear to do a high-quality rendering.  The ShadeOn option
                # turns on directional lighting, which will usually enhance the
                # appearance of the volume and make it look more "3D".  However,
                # the quality of the shading depends on how accurately the gradient
                # of the volume can be calculated, and for noisy data the gradient
                # estimation will be very poor.  The impact of the shading can be
                # decreased by increasing the Ambient coefficient while decreasing
                # the Diffuse and Specular coefficient.  To increase the impact
                # of shading, decrease the Ambient and increase the Diffuse and Specular.
                volumeProperty = vtk.vtkVolumeProperty()
                volumeProperty.SetColor(volumeColor)
                volumeProperty.SetScalarOpacity(volumeScalarOpacity)
                volumeProperty.SetGradientOpacity(volumeGradientOpacity)
                volumeProperty.SetInterpolationTypeToLinear()
                volumeProperty.ShadeOn()
                volumeProperty.SetAmbient(0.4)  # 0.1
                volumeProperty.SetDiffuse(0.5)  # 0.9
                volumeProperty.SetSpecular(0.2)  # 0.2
                volumeProperty.SetSpecularPower(10)

                # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
                # and orientation of the volume in world coordinates.
                volume = vtk.vtkVolume()
                volume.SetMapper(volumeMapper)
                volume.SetProperty(volumeProperty)

                ren = vtk.vtkRenderer()
                ren.SetBackground(0.0, 0.0, 0.0)
                ren.SetViewport(*getViewport(viewNr))
                renWin.AddRenderer(ren)

                # Finally, add the volume to the renderer
                ren.AddViewProp(volume)

                # Set up an initial view of the volume.  The focal point will be the
                # center of the volume, and the camera position will be 400mm to the
                # patient's left (which is our right).
                camera = ren.GetActiveCamera()
                c = volume.GetCenter()
                camera.SetFocalPoint(c[0], c[1], c[2])
                camera.SetPosition(c[0] + 400, c[1], c[2])
                camera.SetViewUp(0, 0, -1)
                ViewportBorder(ren, [1, 1, 1], True)

                ren.ResetCamera()

            def doReslice(renWin, reader, viewNr, orientation, level, window):

                # Calculate the center of the volume
                reader.Update()
                (xMin, xMax, yMin, yMax, zMin,
                 zMax) = reader.GetExecutive().GetWholeExtent(
                     reader.GetOutputInformation(0))
                (xSpacing, ySpacing,
                 zSpacing) = reader.GetOutput().GetSpacing()
                (x0, y0, z0) = reader.GetOutput().GetOrigin()

                center = [
                    x0 + xSpacing * 0.5 * (xMin + xMax),
                    y0 + ySpacing * 0.5 * (yMin + yMax),
                    z0 + zSpacing * 0.5 * (zMin + zMax)
                ]

                # Matrices for axial, coronal, sagittal, oblique view orientations
                axial = vtk.vtkMatrix4x4()
                axial.DeepCopy((1, 0, 0, center[0], 0, 1, 0, center[1], 0, 0,
                                1, center[2], 0, 0, 0, 1))

                coronal = vtk.vtkMatrix4x4()
                coronal.DeepCopy((1, 0, 0, center[0], 0, 0, 1, center[1], 0,
                                  -1, 0, center[2], 0, 0, 0, 1))

                sagittal = vtk.vtkMatrix4x4()
                sagittal.DeepCopy((0, 0, -1, center[0], 1, 0, 0, center[1], 0,
                                   -1, 0, center[2], 0, 0, 0, 1))

                # Extract a slice in the desired orientation
                reslice = vtk.vtkImageReslice()
                reslice.SetInputConnection(reader.GetOutputPort())
                reslice.SetOutputDimensionality(2)
                reslice.SetResliceAxes(axial)
                if orientation == "coronal":
                    reslice.SetResliceAxes(coronal)
                if orientation == "sagittal":
                    reslice.SetResliceAxes(sagittal)
                reslice.SetInterpolationModeToLinear()

                range1 = int(level) - int(window) / 2
                range2 = int(level) + int(window) / 2

                # Create a greyscale lookup table
                table = vtk.vtkLookupTable()
                table.SetRange(range1, range2)  # image intensity range
                table.SetValueRange(0.0, 1.0)  # from black to white
                table.SetSaturationRange(0.0, 0.0)  # no color saturation
                table.SetRampToLinear()
                table.Build()

                # Map the image through the lookup table
                color = vtk.vtkImageMapToColors()
                color.SetLookupTable(table)
                color.SetInputConnection(reslice.GetOutputPort())

                # Display the image
                actor = vtk.vtkImageActor()
                actor.GetMapper().SetInputConnection(color.GetOutputPort())

                cornerAnnotation = vtk.vtkCornerAnnotation()
                cornerAnnotation.SetLinearFontScaleFactor(1)
                cornerAnnotation.SetNonlinearFontScaleFactor(1)
                cornerAnnotation.SetMinimumFontSize(12)
                cornerAnnotation.SetMaximumFontSize(20)
                cornerAnnotation.SetText(0, "lower left")
                cornerAnnotation.SetText(1, "lower right")
                cornerAnnotation.SetText(2, "upper left")
                cornerAnnotation.SetText(3, "upper right")
                cornerAnnotation.GetTextProperty().SetColor(1, 1, 1)

                ren = vtk.vtkRenderer()
                ren.SetBackground(0.0, 0.0, 0.0)
                ren.AddActor(actor)
                #ren.AddViewProp( cornerAnnotation )
                ren.SetViewport(*getViewport(viewNr))
                renWin.AddRenderer(ren)
                ren.ResetCamera()

                camera = ren.GetActiveCamera()
                camera.Zoom(1.4)

                ViewportBorder(ren, [1, 1, 1], False)

                return reslice

            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and
            # keyboard-based interaction with the scene.

            renWin = vtk.vtkRenderWindow()
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)
            interactorStyleImage = vtk.vtkInteractorStyleImage()
            interactorStyleTrackball = vtk.vtkInteractorStyleTrackballCamera()
            interactorStyleTrackball.SetMotionFactor(
                20
            )  # 10 is default, we need twice the speed to compensate the smaller viewport
            iren.SetInteractorStyle(interactorStyleImage)

            cred = credentials()

            mydb = mysql.connector.connect(host="localhost",
                                           user=cred[0],
                                           password=cred[1],
                                           database="iqweb")

            mycursor = mydb.cursor()
            sql = "SELECT path FROM image WHERE seriesuid = %s"
            params = (self.uid, )
            mycursor.execute(sql, params)

            files = mycursor.fetchall()
            fileset = vtk.vtkStringArray()
            for file in files:
                fileset.InsertNextValue(file[0])

            sorter = vtk.vtkDICOMFileSorter()
            sorter.SetInputFileNames(fileset)
            sorter.Update()

            sortedFiles = vtk.vtkStringArray()
            sortedFiles = sorter.GetFileNamesForSeries(0)

            reader = vtk.vtkDICOMReader()
            reader.SetFileNames(sortedFiles)
            reader.Update()

            meta = reader.GetMetaData()

            level = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1050)).AsUTF8String().split("\\")[0]
            window = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1051)).AsUTF8String().split("\\")[0]

            resliceList = []

            resliceList.append(
                doReslice(renWin, reader, 0, 'axial', level, window))

            resliceList.append(
                doReslice(renWin, reader, 1, 'coronal', level, window))

            resliceList.append(
                doReslice(renWin, reader, 2, 'sagittal', level, window))

            doVolumeRendering(renWin, reader, 3)

            # Create callbacks for slicing the image
            actions = {}
            actions["Slicing"] = 0
            actions["ViewNr"] = 0

            def GetViewNrOnMousePosition(iren):
                (mouseX, mouseY) = iren.GetEventPosition()
                (sizeX, sizeY) = iren.GetSize()
                ratioX = mouseX / sizeX
                ratioY = mouseY / sizeY
                if (ratioX < 0.5 and ratioY < 0.5):
                    return 2
                elif (ratioX > 0.5 and ratioY < 0.5):
                    return 3
                elif (ratioX < 0.5 and ratioY > 0.5):
                    return 0
                else:
                    return 1

            def ButtonCallback(obj, event):
                actions["ViewNr"] = GetViewNrOnMousePosition(iren)
                if (actions["ViewNr"] >= 0 and actions["ViewNr"] <= 2):
                    iren.SetInteractorStyle(interactorStyleImage)
                else:
                    iren.SetInteractorStyle(interactorStyleTrackball)

                if event == "LeftButtonPressEvent":
                    actions["Slicing"] = 1
                    iren.GetInteractorStyle().OnLeftButtonDown()
                else:
                    actions["Slicing"] = 0
                    iren.GetInteractorStyle().OnLeftButtonUp()

            def MouseMoveCallback(obj, event):
                (lastX, lastY) = iren.GetLastEventPosition()
                (mouseX, mouseY) = iren.GetEventPosition()
                if actions["Slicing"] == 1 and actions[
                        "ViewNr"] >= 0 and actions["ViewNr"] <= 2:
                    deltaY = mouseY - lastY
                    reslice = resliceList[actions["ViewNr"]]
                    reslice.Update()
                    sliceSpacing = reslice.GetOutput().GetSpacing()[2]
                    matrix = reslice.GetResliceAxes()
                    # move the center point that we are slicing through
                    center = matrix.MultiplyPoint(
                        (0, 0, sliceSpacing * deltaY, 1))
                    matrix.SetElement(0, 3, center[0])
                    matrix.SetElement(1, 3, center[1])
                    matrix.SetElement(2, 3, center[2])
                    renWin.Render()
                else:
                    currentViewNr = GetViewNrOnMousePosition(iren)
                    if (currentViewNr == 3):
                        iren.GetInteractorStyle().OnMouseMove()

            interactorStyleTrackball.AddObserver("MouseMoveEvent",
                                                 MouseMoveCallback)
            interactorStyleTrackball.AddObserver("LeftButtonPressEvent",
                                                 ButtonCallback)
            interactorStyleTrackball.AddObserver("LeftButtonReleaseEvent",
                                                 ButtonCallback)

            interactorStyleImage.AddObserver("MouseMoveEvent",
                                             MouseMoveCallback)
            interactorStyleImage.AddObserver("LeftButtonPressEvent",
                                             ButtonCallback)
            interactorStyleImage.AddObserver("LeftButtonReleaseEvent",
                                             ButtonCallback)

            renWin.Render()

            # vtkweb
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renWin)