Exemplo n.º 1
0
def get_all_api():
    '''
    直接同时返回本地和云端API
    :return:class obj
    '''
    conf = read_job_config()
    local_api = api(conf['local_host'], local=True)
    cloud_api = api(conf['host'], conf['hub'], conf['user'], conf['pwd'])
    return local_api, cloud_api
Exemplo n.º 2
0
 def Menu(self):
     os.system("clear")
     print(Back.WHITE + Fore.RED + '\t-SUDOKU GAME-\n')
     print(Fore.BLACK + 'Presione enter para empezar\n')
     print('Ingrese \'exit\' para salir del juego')
     print(Fore.RED + '^ATENCION: Esta accion reiniciara el tablero.')
     print(Fore.BLACK + '\n1)Empezar!\n2)Creditos\n3)Salir\n')
     print(Style.RESET_ALL)
     op = input('Opcion: ')
     if op == '1':
         self.game.__init__(api())  # Consigo tablero de la api
         return self.jugando()
     elif op == '2':
         os.system('clear')
         print(Back.GREEN + 'Code by: NicoBeast98 :D')
         print(Style.RESET_ALL)
         input('>Back to menu>')
         return self.Menu()
     elif op == '3':
         os.system("clear")
         print(Back.WHITE + Fore.BLACK + 'Chao!')
         print(Style.RESET_ALL)
         exit()
     else:
         print(Fore.RED + '{Ingreso erroneo}')
         print(Style.RESET_ALL)
         input()
         return self.Menu()
Exemplo n.º 3
0
def get_api():
    '''
    根据配置文件中的job_config中的字段local,返回对应的API对象
    :return: local = true返回本地API对象,local=false返回云API对象
    '''
    conf = read_job_config()
    if isinstance(conf, dict):
        logger.debug('Read config success.')
    else:
        logger.error('config para error.')
        raise BaseException('config para error!')
    if conf['local'] == 'True':
        return api(conf['local_host'], local=True, model=conf['model'])
    else:
        return api(conf['host'], conf['hub'], conf['user'], conf['pwd'], False,
                   conf['model'])
Exemplo n.º 4
0
    async def run(self):
        try:
            slov = await self.create_mongo.ban_chek(self.from_id)
            if len(slov["peer_ids"]) > 0:
                result = await self.apis.api_post("messages.getConversationsById", v=self.v, peer_ids=", ".join(slov["peer_ids"]))
                names = []
                j = 1
                for i in result["items"]:
                    names.append(f"{j}. {i['chat_settings']['title']}")
                    j += 1
                api_new = api(self.club_id, "7e57e7ab0bd4508a517b94cd935cea6c7f41698d363994ecfa6a77671a32a8fb7441297abf5ae785e254a")
                res = await api_new.api_post("messages.send", v=self.v, peer_id=self.peer_id,
                                       message="🕵 Вы попали в секретный раздел, сообщения здесь самоуляются через 1 минуту.\n"
                                               "⚠ Если вы не успеете ответить на любое сообщение из этого раздела, не включая это, "
                                               "ваша единственная попытка разбана на одну беседу сгорит.\n\n"
                                               "Вам необходимо пройти тест из 8 вопросов.\n"
                                               "Чтобы получить разбан, ответьте правильно на 5.\n"
                                               "Для ответа на вопрос отправьте сообщение с выбранным номером ответа.\n"
                                               "После выбора беседы сразу начнётся тест.\n\n"
                                               "Выберите номер беседы, в которой вас необходимо разбанить, "
                                               "показаны только те беседы, где доступна попытка разбана:\n" +
                                               "\n".join(names),
                                       random_id=0, expire_ttl=60, keyboard=self.keyboard_empty())

                self.create_mongo.add_user(self.peer_id, 4, 1, self.date, slov)
                #await asyncio.sleep(65)
        except Exception as e:
            print(traceback.format_exc())
Exemplo n.º 5
0
class App:
    api = api.api()

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.scrollbar = Scrollbar(frame)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        self.listbox = Listbox(frame, yscrollcommand=self.scrollbar.set)
        rants = self.api.get_rants()
        for i in rants["rants"]:
            global rantlist
            self.listbox.insert(END, i["text"].encode())
            self.listbox.pack(side=TOP, fill=BOTH)
            rantlist.append(i["id"])
        self.scrollbar.config(command=self.listbox.yview)
        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="View", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        global ind
        global rantroot
        ind = self.listbox.curselection()[0]
        rant = self.api.get_rant(str(rantlist[ind]))
        rantroot = Toplevel()
        rantapp = rantview.viewrant(rantroot, rant)
        rantroot.mainloop()
Exemplo n.º 6
0
 def initServer(self):
     self.api  = api()
     self.channelDict = hardwareConfiguration.channelDict
     self.collectionTime = hardwareConfiguration.collectionTime
     self.collectionMode = hardwareConfiguration.collectionMode
     self.sequenceType = hardwareConfiguration.sequenceType
     self.isProgrammed = hardwareConfiguration.isProgrammed
     self.timeResolution = float(hardwareConfiguration.timeResolution)
     self.ddsDict = hardwareConfiguration.ddsDict
     self.timeResolvedResolution = hardwareConfiguration.timeResolvedResolution
     self.remoteChannels = hardwareConfiguration.remoteChannels
     self.collectionTimeRange = hardwareConfiguration.collectionTimeRange
     self.sequenceTimeRange = hardwareConfiguration.sequenceTimeRange
     self.haveSecondPMT = hardwareConfiguration.secondPMT
     self.haveDAC = hardwareConfiguration.DAC
     self.inCommunication = DeferredLock()
     self.clear_next_pmt_counts = 0
     self.hwconfigpath = os.path.dirname(inspect.getfile(hardwareConfiguration))
     print self.hwconfigpath
     #LineTrigger.initialize(self)
     #self.initializeBoard()
     #yield self.initializeRemote()
     #self.initializeSettings()
     #yield self.initializeDDS()
     self.ddsLock = True
     self.listeners = set()
Exemplo n.º 7
0
def main():
    hpath = "config文件路径"
    hsjon = ujson.Hjson_open(hpath)
    fileRec("开始执行脚本")
    for cfg in hsjon:
        o = api(ID=cfg, passwd=hsjon[cfg]["passwd"], debug=True)
        o.reset()
 def getCurrentPrice(self, currencyPair):
     krkApi = api()
     krakenTicker = krkApi.query_public('Ticker', {'pair': currencyPair})
     result = krakenTicker['result'][currencyPair]
     ticker = {}
     ticker['buy'] = float(result['b'][0])
     ticker['sell'] = float(result['a'][0])
     return ticker
 def getCurrentPrice(self,currencyPair):
     krkApi = api()
     krakenTicker = krkApi.query_public('Ticker', {'pair':currencyPair})
     result = krakenTicker['result'][currencyPair]
     ticker = {}
     ticker['buy'] = float(result['b'][0])
     ticker['sell'] = float(result['a'][0])
     return ticker
Exemplo n.º 10
0
 def get_params(self, params, **kwargs):
     self.params += params
     a = api()
     params_arr = a.get_params(self.kics, params, **kwargs)
     for i, star in enumerate(self.res):
         star["params"].update(params_arr[i])
     logger.info("done: %s", params)
     return 0
Exemplo n.º 11
0
    def test_api(self):

        mock_response = MagicMock()
        mock_response.json = MagicMock(return_value={"response":True,"size":"9","squares":
        [{"x":0,"y":1,"value":6},
            {"x":0,"y":7,"value":1},
            {"x":0,"y":8,"value":2},
            {"x":1,"y":1,"value":2},
            {"x":1,"y":4,"value":3},
            {"x":1,"y":5,"value":9},
            {"x":1,"y":7,"value":5},
            {"x":1,"y":8,"value":6},
            {"x":2,"y":1,"value":7},
            {"x":2,"y":2,"value":4},
            {"x":2,"y":5,"value":6},
            {"x":2,"y":6,"value":3},
            {"x":3,"y":0,"value":4},
            {"x":3,"y":3,"value":6},
            {"x":3,"y":4,"value":2},
            {"x":3,"y":5,"value":8},
            {"x":3,"y":8,"value":9},
            {"x":4,"y":0,"value":7},
            {"x":4,"y":2,"value":6},
            {"x":4,"y":4,"value":5},
            {"x":4,"y":6,"value":2},
            {"x":4,"y":8,"value":3},
            {"x":5,"y":0,"value":9},
            {"x":5,"y":3,"value":4},
            {"x":5,"y":8,"value":5},
            {"x":6,"y":0,"value":2},
            {"x":6,"y":2,"value":5},
            {"x":6,"y":3,"value":1},
            {"x":6,"y":6,"value":9},
            {"x":6,"y":7,"value":8},
            {"x":7,"y":1,"value":9},
            {"x":7,"y":3,"value":3},
            {"x":7,"y":4,"value":8},
            {"x":7,"y":6,"value":5},
            {"x":7,"y":7,"value":2},
            {"x":8,"y":1,"value":4},
            {"x":8,"y":2,"value":1},
            {"x":8,"y":4,"value":9},
            {"x":8,"y":6,"value":6},
            {"x":8,"y":7,"value":3}]})

        with patch("api.requests.get", return_value=mock_response):
            result = api(9)

        self.assertEqual(result, [["x", "x", "x", "4", "7", "9", "2", "x", "x"],
                                  ["6", "2", "7", "x", "x", "x", "x", "9", "4"],
                                  ["x", "x", "4", "x", "6", "x", "5", "x", "1"],
                                  ["x", "x", "x", "6", "x", "4", "1", "3", "x"],
                                  ["x", "3", "x", "2", "5", "x", "x", "8", "9"],
                                  ["x", "9", "6", "8", "x", "x", "x", "x", "x"],
                                  ["x", "x", "3", "x", "2", "x", "9", "5", "6"],
                                  ["1", "5", "x", "x", "x", "x", "8", "2", "3"],
                                  ["2", "6", "x", "9", "3", "5", "x", "x", "x"]])
Exemplo n.º 12
0
 def tradeCurrency(self,currencyPair, type, price):
     krkApi = api()
     limitPrice = price + 0.01
     req = {'pair':currencyPair, 'type':type, 'ordertype':'limit', 'price': limitPrice}
     krackenOrder = krkApi.query_private('AddOrder', req)
     print krackenOrder['description']
     print krackenOrder['txid']
     print self.config['exchange.kraken.username']
     return krackenOrder
Exemplo n.º 13
0
 def test_API_2(self):
     mock_response = MagicMock()
     mock_response.json = MagicMock(return_value={"response":True,"size":"4","squares":[{"x":0,"y":0,"value":4},{"x":0,"y":2,"value":3},{"x":0,"y":3,"value":1},{"x":1,"y":1,"value":3},{"x":2,"y":0,"value":3},{"x":2,"y":1,"value":1},{"x":2,"y":3,"value":2},{"x":3,"y":1,"value":4}]})
     with patch("api.requests.get", return_value=mock_response):
         result = api(4)
     self.assertEqual(result, [["4", "x", "3", "x"],
                               ["x", "3", "1", "4"],
                               ["3", "x", "x", "x"],
                               ["1", "x", "2", "x"]])
Exemplo n.º 14
0
 def generar_tablero(self):
     #genero un tablero, por medio de la self.logica, que lo trae de la api
     self.tablero = api(self.size)
     self.logica = Sudoku(self.tablero)
     self.prohibidos = []
     # del tablero generado, veo que posiciones no pueden modificarse
     for i in range(self.size):
         for j in range(self.size):
             if (self.tablero[i][j] != 'x'):
                 self.prohibidos.append((i, j))
Exemplo n.º 15
0
    def ingresar_tamaño_tablero(self):#se ingresa el tamaño del tablero
        self.tamaño = 0
        while self.tamaño != "9" and self.tamaño != "4":
            self.tamaño = input("Ingrese el tamaño del tablero (4/9)\n")
            if self.tamaño != "9" and self.tamaño != "4":
                print("Ingrese el tamaño del tablero nuevamente\n")

        self.tamaño = int(self.tamaño)      
        self.board = api(int(self.tamaño))
        self.game = Sudoku(self.board)
Exemplo n.º 16
0
		def fetch(self):
			"""
			Fetch the user's friend list
			""" 
			# TODO: Follow extra pages
			try:
				rsp = api.api(self.token, 'auth/verify')
				username = rsp['auth']['username']
				self.put(PownceFS.User(self.token, username))
				rsp = api.api(self.token, 'users/%s/friends' % username,
					{'limit': 100})
				users = rsp['friends']['users']
				for u in users:
					self.put(PownceFS.User(self.token, u['username']))
				self.stat.st_atime = time.time()
				self.stat.st_mtime = self.stat.st_atime
				self.stat.st_ctime = self.stat.st_atime
			except:
				pass
Exemplo n.º 17
0
        def fetch(self):
            """
			Fetch the user's friend list
			"""
            # TODO: Follow extra pages
            try:
                rsp = api.api(self.token, 'auth/verify')
                username = rsp['auth']['username']
                self.put(PownceFS.User(self.token, username))
                rsp = api.api(self.token, 'users/%s/friends' % username,
                              {'limit': 100})
                users = rsp['friends']['users']
                for u in users:
                    self.put(PownceFS.User(self.token, u['username']))
                self.stat.st_atime = time.time()
                self.stat.st_mtime = self.stat.st_atime
                self.stat.st_ctime = self.stat.st_atime
            except:
                pass
Exemplo n.º 18
0
def total_yesterday():
    if article_check()[0] == 'True':
        api_data = api()
        yesterday_total_data = api_data['response']['body']['items']['item'][
            18]
        yesterday_total = int(yesterday_total_data['incDec'])
        yesterday_in_total = int(yesterday_total_data['localOccCnt'])
        yesterday_out_total = int(yesterday_total_data['overFlowCnt'])

        return (yesterday_total, yesterday_in_total, yesterday_out_total)
    else:
        api_data = api()
        yesterday_total_data = api_data['response']['body']['items']['item'][
            37]
        yesterday_total = int(yesterday_total_data['incDec'])
        yesterday_in_total = int(yesterday_total_data['localOccCnt'])
        yesterday_out_total = int(yesterday_total_data['overFlowCnt'])

        return (yesterday_total, yesterday_in_total, yesterday_out_total)
Exemplo n.º 19
0
def run_api():
    list_of_isins = il.list_of_isin

    for isin in list_of_isins:
        try:
            res = api(isin)
            print(res)
        except Exception as e:
            print(e)
            continue
Exemplo n.º 20
0
 def __init__(self, conf):
     self.case_end_flag = False
     self.time_out_flag = False
     self.conf = conf
     self.sdk = api(self.conf['host'], self.conf['hub'], self.conf['user'],
                    self.conf['pwd'])
     filename = "stability_debug.log"
     # error_file = "stability_error_" + "".join(self.conf['hub'].split(':')) + '.txt'
     self.logger = logs.set_logger(__name__, filename=filename)
     self.downlogs = Download_logs(self.conf['local_host'].split('/', 2)[2],
                                   22, 'root', '3_5*rShsen')
Exemplo n.º 21
0
 def __init__(self):
     base()
     self.thread_pool = []
     self.urls = {
         "kd_intr": "http://www.kuaidaili.com/free/intr/",
         "kd_inha": "http://www.kuaidaili.com/free/inha/",
         'xc_http': 'http://www.xicidaili.com/wt/',
         'xc_https': 'http://www.xicidaili.com/wn/',
         'route_showapi': "http://route.showapi.com/22-1"
     }
     self.functions = {'xc': xc(), 'route': api(), 'kd': kd()}
Exemplo n.º 22
0
 def __init__(self, conf):
     self.case_end_flag = False
     self.time_out_flag = False
     self.conf = conf
     self.sdk = api(self.conf['host'], self.conf[
                    'hub'], self.conf['user'], self.conf['pwd'])
     debug_file = "stability_debug_" + \
         "".join(self.conf['hub'].split(':')) + ".txt"
     error_file = "stability_error_" + \
         "".join(self.conf['hub'].split(':')) + '.txt'
     self.logger = set_logger(
         __name__, debugfile=debug_file, errorfile=error_file)
Exemplo n.º 23
0
 def do_GET(self):
     ''' Handle GET request '''
     self.send_response(200)
     self.send_header('Content-type', 'application/json')
     self._headers()
     query = urlparse(self.path).query
     path = urlparse(self.path).path
     params = {k: v[0] for k, v in parse_qs(query).items()}
     self.end_headers()
     err, response = api.api(path, params, self.headers)
     print response
     self.wfile.write(marshall(response, err))
Exemplo n.º 24
0
def total_today():

    if article_check()[0] == 'True':
        today_data = article_check()
        return (today_data[1] + today_data[2], today_data[1], today_data[2])
    else:
        api_data = api()
        today_total_data = api_data['response']['body']['items']['item'][18]
        today_total = int(today_total_data['incDec'])
        today_in_total = int(today_total_data['localOccCnt'])
        today_out_total = int(today_total_data['overFlowCnt'])

        return (today_total, today_in_total, today_out_total)
Exemplo n.º 25
0
 def play(self):
     print ("......SUDOKU......\n")
     print("Intente llenar el tablero sin repetir valores en filas, columnas y bloques \n")
     jugar = Sudoku(api(self.ingresar_dimension()),self.tamaño)
     #self.ingresar_dimension()
     while not jugar.juego_terminado():
         # mostrar tablero
         print(jugar.tabla())
         # jugar.write(*self.ingresar_valor(self.tamaño))
         x, y, n = self.ingresar_valor(jugar,self.tamaño)
         jugar.write(x, y, n)
     
     print("Felicitaciones, ganó el juego")
Exemplo n.º 26
0
 def tradeCurrency(self, currencyPair, type, price):
     krkApi = api()
     limitPrice = price + 0.01
     req = {
         'pair': currencyPair,
         'type': type,
         'ordertype': 'limit',
         'price': limitPrice
     }
     krackenOrder = krkApi.query_private('AddOrder', req)
     print krackenOrder['description']
     print krackenOrder['txid']
     print self.config['exchange.kraken.username']
     return krackenOrder
Exemplo n.º 27
0
 def initServer( self ):
     self.api = api()
     self.inCommunication = DeferredLock()
     self.registry = self.client.registry        
     self.dacDict = dict(hc.elec_dict.items() + hc.sma_dict.items())
     print("dacDict:")
     print(len(self.dacDict.items()))
     self.queue = Queue()
     self.multipoles = hc.default_multipoles
     self.currentVoltages = {}
     self.initializeBoard()
     self.listeners = set() 
     yield self.setCalibrations()
     self.setPreviousControlFile()
Exemplo n.º 28
0
    def ingresar_dimension(self):
        self.tamaño = 0

        #Para ingresear la dimension del tablero
        while self.tamaño != "9" and self.tamaño != "4":
            self.tamaño = input("Ingrese el tamaño del tablero (4/9)\n")
            if self.tamaño != "9" and self.tamaño != "4":
                print(
                    "EL TAMAÑO DEL TABLERO NO ES CORRECTO \nIngrese el tamaño del tablero nuevamente...\n"
                )

        self.tamaño = int(self.tamaño)
        self.tablero = api(int(self.tamaño))
        self.game = Sudoku(self.tablero)
Exemplo n.º 29
0
 def initServer(self):
     self.api = api()
     self.inCommunication = DeferredLock()
     self.registry = self.client.registry
     self.dacDict = dict(hc.elecDict.items() + hc.smaDict.items())
     print("dacDict:")
     print(len(self.dacDict.items()))
     self.queue = Queue()
     self.multipoles = hc.defaultMultipoles
     self.currentVoltages = {}
     self.initializeBoard()
     self.listeners = set()
     yield self.setCalibrations()
     self.setPreviousControlFile()
Exemplo n.º 30
0
def get_popular_users():
    data = api()
    tweet = mongo.db.dataset.find().distinct('fromuser')
    count_tweet = []
    for s in tweet:
        count_tweet.append({
            'fromuser':
            s,
            'total_tweet':
            mongo.db.dataset.find({
                'fromuser': s
            }).count()
        })
    result = data.get_popular_users(count_tweet)
    return jsonify(result)
Exemplo n.º 31
0
    def do_POST(self):
        ''' Handle POST request '''
        def _decoder(length):
            decoded = self.rfile.read(length)
            return json.loads(decoded.decode('utf-8'))

        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        data = _decoder(int(self.headers['Content-Length']))
        self._headers()
        self.end_headers()
        path = urlparse(self.path).path
        err, response = api.api(path, data, self.headers)
        print response
        self.wfile.write(marshall(response, err))
Exemplo n.º 32
0
    def play(self):

        print("\n\n         BIENVENIDO AL SUDOKU        \n\n")
        jugar = Sudoku(
            api(self.ingresar_dimension()),
            self.tamano)  #El resultado de la api se lo envia a la clase Sudoku

        while not jugar.fin_juego():

            print(jugar.tablero())  # mostrar tablero
            x, y, n = self.ingresar_valor(
                jugar, self.tamano
            )  #Le envia el valor del tamano al metodo ingresar_valor
            jugar.escribir(x, y, n)

        print("             Has ganado!!!! Fin del juego             \n")
Exemplo n.º 33
0
		def fetch(self):
			"""
			Fetch this friend's files
			"""
			# TODO: Follow extra pages
			try:
				rsp = api.api(self.token, 'note_lists/%s' % self.name,
					{'type': 'files', 'filter': 'sent', 'limit': 100})
				notes = rsp['notes']
				for n in notes:
					self.put(PownceFS.File(self.token, n['file']['name'],
						n['file']['direct_url'], n['file']['content_length']))
				self.stat.st_atime = time.time()
				self.stat.st_mtime = self.stat.st_atime
				self.stat.st_ctime = self.stat.st_atime
			except:
				pass
Exemplo n.º 34
0
 def initServer(self):
     self.api  = api()
     self.channelDict = hardwareConfiguration.channelDict
     self.collectionTime = hardwareConfiguration.collectionTime
     self.collectionMode = hardwareConfiguration.collectionMode
     self.sequenceType = hardwareConfiguration.sequenceType
     self.isProgrammed = hardwareConfiguration.isProgrammed
     self.timeResolution = hardwareConfiguration.timeResolution
     self.ddsDict = hardwareConfiguration.ddsDict
     self.timeResolvedResolution = hardwareConfiguration.timeResolvedResolution
     self.remoteChannels = hardwareConfiguration.remoteChannels
     self.inCommunication = DeferredLock()
     self.initializeBoard()
     yield self.initializeRemote()
     self.initializeSettings()
     yield self.initializeDDS()
     self.listeners = set()
Exemplo n.º 35
0
def send_text():
    while True:
        try:
            # 질병관리청 Text Check
            if article_check()[0] == 'True':
                print(1)
                break

            # 공공데이터포털 Api
            else:
                api_data = api()
                api_data['response']['body']['items']['item'][37]
                print(2)
                break
        except IndexError:
            print(3)
            time.sleep(60)

    auto()
Exemplo n.º 36
0
def start(name, collection_bots, document_tokens):
    with open(f'{name}.txt') as f:
        lines = f.read().splitlines()

    print(f"number tokens: {len(lines)}")
    #print(lines)

    loop = asyncio.get_event_loop()
    tasks = [
        loop.create_task(
            api(0,
                i.split('&')[0]).api_get("groups.getById", v=f"{V}"))
        for i in lines
    ]
    loop.run_until_complete(asyncio.wait(tasks))

    tokens = []
    tokens_new = []
    tokens_new_t = []
    ids = []
    for i in range(len(tasks)):
        result = tasks[i].result()
        if "error" not in result:
            if result[0]["id"] not in ids:
                ids.append(result[0]["id"])
                tokens.append({
                    "id": result[0]["id"],
                    "token": lines[i].split('&')[0],
                    "name": result[0]["name"],
                    "them": lines[i].split('&')[1]
                })
                tokens_new.append(lines[i])
                tokens_new_t.append(lines[i].split('&')[0])

            elif result[0]["id"] in ids:
                pass
    f = open(f'{name}.txt', 'w')
    f.write("\n".join(tokens_new))
    f.close()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(tokens_setting(V).main(tokens_new_t, ids))
    create_mongo.create_db(collection_bots, document_tokens, tokens, ids)
    return tokens
Exemplo n.º 37
0
    def __init__(self, pkg_addr):
        '''app container, loads packages/modules,
        builds the api, resolves dependencies and activates
        the packages/modules'''
        # TODO: implement pkgcontainer class, to persist pkgs?
        # Right now it's left to api, but that sort of violates SRP.
        # Pkgs that don't expose functionality have to expose "dummy"
        # functionality to "stay alive".
        self.app_api = api.api()

        # creates a pkgloader instance to load the initial packages.
        # this instance will load another pkgloader instance into the
        # api in order to expose package-loading functionality.
        pkgl = pl.pkgloaderhandler(self.app_api)
        pkg_list = pkgl.LoadPackages(pkg_addr)

        self.app_api.Call(
            "activate_packages",
            self.app_api.GetPackages()
        )

        self.app_api.Call("set_packages", pkg_list)
 def initServer(self):
     self.api  = api()
     #user configuration
     self.ttl_channels = user_configuration.ttl_channels
     self.dds_channels = user_configuration.dds_channels
     self.remote_dds_channels = user_configuration.remote_dds_channels
     #hardware configuration
     self.collectionTime = hardwareConfiguration.collectionTime
     self.collectionMode = hardwareConfiguration.collectionMode
     self.sequenceType = hardwareConfiguration.sequenceType
     self.isProgrammed = hardwareConfiguration.isProgrammed
     self.timeResolution = float(hardwareConfiguration.timeResolution)
     self.timeResolvedResolution = hardwareConfiguration.timeResolvedResolution
     self.collectionTimeRange = hardwareConfiguration.collectionTimeRange
     self.haveSecondPMT = hardwareConfiguration.secondPMT
     self.inCommunication = DeferredLock()
     self.clear_next_pmt_counts = 0
     LineTrigger.initialize(self)
     self.initializeBoard()
     yield self.initializeRemote()
     self.initializeSettings()
     yield self.initializeDDS()
     self.listeners = set()
Exemplo n.º 39
0
def perform_looped_db_run():

    logging.info('Getting API')
    api_instance = api(api_key=Keys.API_KEY)

    api_parameters=Parameters.BASE_API_PARAMETERS

    batch_id = run_sql(Parameters.SQL_GET_BATCH_ID)
    logging.info('Starting Batch {}'.format(batch_id))
    run_sql(Parameters.SQL_LOG_ENTRY.format(batch_id=batch_id, level='I', message='Starting Batch'))

    for outcode in Parameters.OUTCODES:
        api_parameters['postcode'] = outcode

        run_sql(Parameters.SQL_CLEAR_STAGE)

        run_sql(Parameters.SQL_LOG_ENTRY.format(batch_id=batch_id, level='I', message='Pulling data for outcode [{}]'.format(outcode)))
        stage_listings(batch_id, api_instance, api_parameters)

        run_sql(Parameters.SQL_LOG_ENTRY.format(batch_id=batch_id, level='I', message='Merging data for outcode [{}]'.format(outcode)))
        run_sql_multi(Parameters.SQL_MERGE_STAGE)

    run_sql(Parameters.SQL_LOG_ENTRY.format(batch_id=batch_id, level='I', message='Finished Batch'))
Exemplo n.º 40
0
def main():
    e_api = api.api()
    codes= {'keyID': '#######', 'vCode': 'abc'}
    print 'Checking skill queue'
    e_api.skill_check(codes)
Exemplo n.º 41
0
import api

api = api.api(False,True,False,False)

print api.i2chandler.packetNumber
print api.i2chandler.packetNumber2

api.setInk(0,0,200,4)

api.drawPixel(0,0)
api.drawPixel(0,10)
api.drawPixel(10,0)
api.drawPixel(10,10)
Exemplo n.º 42
0
#!/usr/bin/env python3

from api import GooglePlayAPI as api

_api = api()
_api.search("com.tellm.android.app")
Exemplo n.º 43
0
import api
emulated = True
LEDGrided = True
LCDed = False
keyboardHacked = True
touch = False

gameList = ('app','orthello','connect4','draughts','inkspill','pixelArt','simon','solitare','tetris','ticTacToe','missionmars','scamper','gridTest','flame')

# 0       1             2           3          4      5           6         7        8         9          10           11    12      
api = api.api(emulated, LEDGrided, LCDed, keyboardHacked, touch)

button = 4 #api.waitForScreenButtonPress()

#while True:
	
gameImport = __import__(gameList[button])
print "ldr1"
game = gameImport.thisapp(api)
print "ldr2"
	#button = api.waitForScreenButtonPress()
Exemplo n.º 44
0
 def initServer(self):
     self.api  = api()
     self.inCommunication = DeferredLock()
     self.initializeBoard()
Exemplo n.º 45
0
Arquivo: run.py Projeto: nechutny/ISJ
	*				Don't delete downloaded files
	*
	*/'''


import sys;
import os;
import re;
from arguments import arguments;
from api import api;
from subtitle import subtitle;
#from movie import movie

parameters = arguments(sys.argv);

api = api();
downloads = [];

if parameters.downloaded == False:
	if parameters.url != False:
		downloads = api.searchBySubs(parameters.url, parameters.lang);
	elif parameters.name != False :
		parameters.url = api.searchByName(parameters.name, parameters.lang);
		downloads = api.subtitlesByLink(parameters.url);
	elif parameters.filename != False:
		parameters.url = api.searchByFile(parameters.filename, parameters.lang);
		downloads = api.subtitlesByLink(parameters.url);

	#print parameters.url;

	
Exemplo n.º 46
0
 def startApi(self):
  self.api = api()
Exemplo n.º 47
0
def csv_runner():
    logging.info('Getting API')
    api_instance = api(version=1, api_key=Keys.API_KEY)

    #single_run(api_instance, Parameters.BASE_API_PARAMETERS, Parameters.BASE_OUTPUT_FILE_NAME.format('single'))
    looped_run(api_instance, Parameters.BASE_API_PARAMETERS, Parameters.BASE_OUTPUT_FILE_NAME, 5)