def test_username_password_exists(self): with pytest.raises(Exception) as excinfo1: API(None) with pytest.raises(Exception) as excinfo2: API(USERNAME) assert 'username' in str(excinfo1.value) assert 'password' in str(excinfo2.value)
def get_twitter_client(): """Setup Twitter API client. Return: tweepy.API object """ auth = get_twitter_auth() client = API(auth) return client
def test_invalid_session(self): test_api = API(USERNAME, session_id='abc123', database=DATABASE) assert USERNAME in str(test_api.credentials) assert DATABASE in str(test_api.credentials) with pytest.raises(AuthenticationException) as excinfo: test_api.get('User') assert 'Cannot authenticate' in str(excinfo.value) assert DATABASE in str(excinfo.value) assert USERNAME in str(excinfo.value)
def main(): sys.setrecursionlimit(10000000) api = API.API(4 * 1024, 4 * 1024) print_welcome() command = '' while command != 'quit': command = get_command() try: parse_sql(api, command) except AssertionError as e: print(e)
def fetch_words(url): """ Retrieving a json result set from the API module An API object is instantiated and a json result set is returned by calling the instance specific API.object.getr() function Args: url (str): URL string to instantiate the API object Returns: dict: JSON data as python dictionary """ api = API.API(url, '') return api.getr()
def async_populated_api(): loop = asyncio.get_event_loop() or asyncio.new_event_loop() if USERNAME and PASSWORD: session = API(USERNAME, password=PASSWORD, database=DATABASE, server=None, loop=loop) try: session.authenticate() except MyGeotabException as exception: pytest.fail(exception) return yield session else: pytest.skip('Can\'t make calls to the API without the ' 'MYGEOTAB_USERNAME and MYGEOTAB_PASSWORD ' 'environment variables being set')
def __init__(self, budget, interval, currency): self.api = API() self.wallet = Wallet(currency) self.analyzer = Analyzer(budget) self.APIS = "http://api.coinmarketcap.com/v1/ticker/" self.running = True self.BUDGET = int(budget) # USD self.investing_pr_round = self.BUDGET * 0.03 # 3% self.currency = currency self.interval = interval self.talent = 0.00005 self.wallet.create_setting(self.BUDGET) print colored("[+] cryptomate initialized.\r\n", "yellow")
def main(): """ Start zerorpc server and keep it running. """ print("Starting python server...") # Set address to localhost address = "tcp://127.0.0.1:" + parse_port() # Start server with class API as server = zerorpc.Server(API.API()) server.bind(address) print("Server started running on {}".format(address)) # Blocking command. Keeps server running server.run()
def __init__(self, address, cacheExpiry=5, api=None, logger=None, logLevel=None): self.address = address self.setCacheExpiry(cacheExpiry) self.cache = {} if logger is None: if logLevel is None: logLevel = logging.WARNING logging.basicConfig(level=logLevel) self.logger = logging.getLogger('TStat') else: self.logger = logger if api is None: self.api = API() self.api = getAPI(self.getModel()) time.sleep(2) else: self.api = api
def run(filename): api = API.API(API_KEY) hash_res = api.hash_lookup(filename) if "file_id" in hash_res.keys(): api.output_results(hash_res) return file_res = api.upload_file(filename) data_id = file_res["data_id"] res = {} # if scan_results is in the object response, we're in queue # continue requesting the results until this changes while "scan_results" not in res.keys(): res = api.file_results(data_id) time.sleep(1) # continue requesting until progress_percentage is 100% while res["scan_results"]["progress_percentage"] != 100: res = api.file_results(data_id) time.sleep(1) api.output_results(res)
def LoadService(service, send, backup, genLink, master=None): # Load Dynamicly # api = API(service, send, backup, genLink) foundServiceClass = None # if service is "Echo": # foundServiceClass = EchoService if service is "Master": foundServiceClass = MasterService # if service is "Experimental": # foundServiceClass = ExperimentalService if service is "Challenge18": foundServiceClass = Challenge18Service if service is "Manager": foundServiceClass = Challenge18Manager if foundServiceClass is not None: api = API(service, send, backup, genLink) ServiceLoader.startService(foundServiceClass, db={}, api=api, master=master) return {"obj": foundServiceClass.share, "api": api} return None
def __init__(self): self.name = 0 self.rate1 = Rate.Rate("EUR/USD", "time", "1", "2") self.snapShots = [] self.API = API.API()
# -*- coding: utf-8 -*- import API import os path = 'E:/PyCharm-wokspace/test/picture/' api = API.API(path) list = os.listdir(path) for i in range(0, len(list)): file_path = os.path.join(path, list[i]) if os.path.isfile(file_path) and not list[i].startswith('-'): api.face_detect(list[i])
def __init__(self, top=None): self.ship = API.API() self.style = ttk.Style() if sys.platform == "win32": self.style.theme_use('winnative') top.geometry("600x450+507+175") top.title("Where to eat?") top.configure(background="#d8b2a8", highlightbackground="#d9d9d9", highlightcolor="black") self.mainFrame = tk.Frame(top, bg="#d8b2a8") self.mainFrame.place(relx=0.0, rely=0.0, relheight=1, relwidth=1) self.restaurantFrame = tk.Frame(top, background="#d8b2a8", relief='flat') self.restaurantFrame.place(relx=0.0, rely=0.0, relheight=1, relwidth=1) self.detailFrame = tk.Frame(top, bg="#d8b2a8") self.detailFrame.place(relx=0.0, rely=0.0, relheight=1, relwidth=1) self.mainFrame.lift() i = Image.open('taco-512.png', mode='r') photo = ImageTk.PhotoImage(i) populateButton = tk.Button(self.mainFrame, bg="#97b3d8", activebackground="#c3edb4", relief='groove', image=photo, command=self.fetchRestaurants) populateButton.image = photo populateButton.place(relx=0.35, rely=0.5) exitButton = tk.Button(self.mainFrame, text="Exit/Cancel", activebackground="#c3edb4", background="#97b3d8", font=("Arial", 12), command=GUIsupport.destroy_window) exitButton.place(relx=0.75, rely=0.8, height=70, width=140) locationLabel = tk.Label(self.mainFrame, background="#d8b2a8", relief="groove", text='''Enter an Address, City, or State:''') locationLabel.place(relx=0.06, rely=0.07, height=31, width=187) termLabel = tk.Label(self.mainFrame, background="#d8b2a8", relief="groove", text='''Enter a keyword:''') termLabel.place(relx=0.567, rely=0.067, height=31, width=197) radiusLabel = tk.Label(self.mainFrame, background="#d8b2a8", relief="groove", text='''Enter a radius:''') radiusLabel.place(relx=0.567, rely=0.3, height=31, width=197) self.locationEntry = tk.Entry(self.mainFrame, background="white", selectbackground="#c4c4c4", selectforeground="black") self.locationEntry.place(relx=0.04, rely=0.2, relheight=0.07, relwidth=0.4) self.termEntry = tk.Entry(self.mainFrame, background="white", selectbackground="#c4c4c4", selectforeground="black") self.termEntry.place(relx=0.55, rely=0.2, relheight=0.07, relwidth=0.4) self.radiusBox = ttk.Combobox( self.mainFrame, takefocus='', values=['2 miles', '5 miles', '15 miles', '30 miles', '50 miles']) self.radiusBox.place(relx=0.65, rely=0.4, relheight=0.07, relwidth=0.2) optionButtons = [] self.optionLabels = [] place = [.021, 0.144, 0.268, 0.392, 0.515, 0.639, 0.763, 0.887] optionButtons.extend([ tk.Button(self.restaurantFrame, wraplength=60, activebackground="#c3edb4", background="#97b3d8", text='Pick #%s' % i, command=lambda idx=i: self.showRestaurantDetails(idx)) for i in range(7) ]) self.optionLabels.extend([ tk.Label(self.restaurantFrame, activebackground="#c3edb4", background="#97b3d8", font=("Arial", 10)) for i in range(7) ]) for i in range(len(optionButtons)): optionButtons[i].place(relx=0.08, rely=place[i], height=42, width=68) self.optionLabels[i].place(relx=0.208, rely=place[i], height=42, width=457) resToMain = tk.Button(self.restaurantFrame, text="Back to main menu", command=lambda: self.changeFrames( self.mainFrame, self.restaurantFrame), activebackground="#c3edb4", background="#97b3d8") resToMain.place(relx=.5, rely=0.90, height=42, width=130) self.display = tk.Text(self.detailFrame, bg="#ffd2c7", relief="groove", width=580, font=("Arial", 12)) self.display.place(relx=0.017, rely=0.089, relheight=0.66, relwidth=.95) self.backButton = tk.Button( self.detailFrame, text='Go back', command=lambda: self.changeFrames(self.restaurantFrame, self. detailFrame), activebackground="#c3edb4", background="#97b3d8", wraplength=60) self.backButton.place(relx=0.417, rely=0.822, height=52, width=84)
""" Given a frob obtained via a 'flickr.auth.getFrob' and perms (currently read, write, or delete) return a url for desktop client api authentication Deprecated in 0.4.1, use get_authurl for new applications """ return get_authurl(perms, frob=frob) def _sign_args(self, args): return sign_args(self.secret, args) class Request(urllib2.Request): """ A request to the Flickr API subclassed from urllib2.Request allowing for custom proxy, cache, headers, etc """ def __init__(self, apiurl='http://api.flickr.com/services/rest/', **args): urllib2.Request.__init__(self, url=apiurl) self.args = args if (__name__ == '__main__'): import sys try: key = sys.argv[1] secret = sys.argv[2] except IndexError: print "Usage: %s <key> <secret>" % (sys.argv[0], ) sys.exit(1) api = API(key, secret) res = api.execute_method(method='flickr.test.echo', args={'foo': 'bar'})
def main(argv): """Main function of the Test script""" try: opts, args = getopt.getopt( argv, "hu:p:d:P:s:", ["username="******"password="******"domain=", "port=", "secure-port="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit(0) elif opt in ("-u", "--username"): global user user = arg print "Username = "******"-p", "--password"): global password password = arg print "Password = "******"-d", "--domain"): global domain domain = arg print "Domain = ", domain elif opt in ("-P", "--port"): global port port = arg print "Port = ", port elif opt in ("-s", "--secure-port"): global sport sport = arg print "Secure port = ", sport myodl = ODL(auth=HTTPBasicAuth(user, password), domain=domain, port=port, sec_port=sport) api = API(odl=myodl, format='json') reportList = [] # test for add UserLink and retrieve current network topology #test_Topology_all(api, reportList) #individualTest = [] #individualTest.append("Retreive Topology") #response = api.retrieve_the_topology() #response = api.retrieve_node_flows(nodeId='00:00:b8:ca:3a:65:c6:55') #retrieve_all_nodes() #api.retrieve_node_connectors_by_node(nodeId='00:00:b8:ca:3a:65:c6:55') #prepareReport(response.status_code, reportList, individualTest) #test_SwitchManager_all(api, reportList) #test_ContainerManager_all(api, reportList) # #test_Statistics_all(api, reportList) """individualTest = [] response = api.retrieve_userLinks() individualTest.append("Retrieve UserLinks") prepareReport(response.status_code, reportList, individualTest)""" """individualTest = [] individualTest.append("Retrieve node Statistics") response = api.retrieve_node_statistics_flow(nodeId='00:00:b8:ca:3a:65:c6:55') prepareReport(response.status_code, reportList, individualTest)""" """individualTest = [] individualTest.append("Retrieve node Statisics Ports") response = api.retrieve_node_statistics_port(nodeId='00:00:b8:ca:3a:65:c6:55') prepareReport(response.status_code, reportList, individualTest)""" """individualTest = [] individualTest.append("Retrieve node Statistics Tables") response = api.retrieve_node_statistics_table(nodeId='00:00:b8:ca:3a:65:c6:55') prepareReport(response.status_code, reportList, individualTest)""" individualTest = [] individualTest.append("Retrieve node Statistics Tables") response = api.retrieve_all_nodes() #response = api.retrieve_node_connectors_by_node(nodeId='00:00:b8:ca:3a:65:c6:55') prepareReport(response.status_code, reportList, individualTest) """test_FlowProgrammer_all(api, reportList)
def test_auth_exception(self): test_api = API(USERNAME, password='******', database='this_database_does_not_exist') with pytest.raises(MyGeotabException) as excinfo: test_api.authenticate(False) assert excinfo.value.name == 'DbUnavailableException'
from Auth import User from MAC import MAC from Place import Place from Probe import Probe urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) parser = argparse.ArgumentParser(description="Scan for probes request") parser.add_argument('-i', help="interface wifi en monitor") parser.add_argument('--api', help='Base address for the API') args = parser.parse_args() username = os.environ['wiface_username'] password = os.environ['wiface_password'] creds = User(username, password) MyAPI = API(creds, args.api) mac_dic = dict() # source : https://pdfs.semanticscholar.org/f690/3910e7256946b138bf50b8dff8e9c8e73526.pdf def estimateDistance(RSSI, txPower): """Estimate the distance of the device based on the RSSI Args: RSSI ([number]): AntSignal of the frame txPower ([type]): Estimated signal strength at 1 meter Returns: number: distance estimation """ n = 2.4 return math.pow(10, (txPower - RSSI) / (10 * n))
import json import requests import API x = int(1) while x < 600: r = requests.get('https://cex.io/api/order_book/ETH/EUR/') json_data = json.loads(r.text) tradefee = 0.0016 topask = json_data['asks'][000][0] topbid = json_data['bids'][000][0] netProfit = (topask * (1 - tradefee)) - (topbid * (1 + tradefee)) if netProfit > 0: print('Profit') else: print('Loss') netFee = (topask + topbid) * tradefee print(netFee) x += 1 requests.get('https://cex.io/api/balance/') APIrequest = API()
from Tkinter import * from PIL import Image, ImageTk import os import sys import API import Game import tkMessageBox # Get an API handler, to contact the server # We'll use that handler in Game and in Window classes api = API.API() class Window(Frame): """ Window(Frame) class is our game GUI, and contains multiple "windows" We're doing so by changing the size, background and GUI elements being shown on the screen Inheriting from Tkinter's Frame class """ def __init__(self, master=None): """ Initilizing all the GUI variables required :param master: root Tk """ Frame.__init__(self, master) self.master = master # Saving image references so garbage collector won't delete those self.image_refs = []
import API import BlynkLib # Initialize Blynk blynk = BlynkLib.Blynk('9rvmtZDBOuQr0KrJ-FFwB2dZblwt3yDp') api = API.API() #Create object of API #Checks if EnableSPI button is on or off @blynk.VIRTUAL_WRITE(2) def EnableSPI(value): #If SPI is enabled then program is running #Buttons can be pressed #Functions are available if value == [u'1']: api.SPICommunication(1) blynk.virtual_write(10, "SPI On") #The user is informed that SPI is on #Handler for GetNameAndIDButton @blynk.VIRTUAL_WRITE(0) def GetNameAndID(value): if value == [u'1']: #If Button is on blynk.virtual_write(10, "Tap tag to get ID and name") text = api.getTextAndID() #ID and name are retrieved blynk.virtual_write(10, text) #ID and name are printed on screen blynk.virtual_write(0, 0) #Button is switched off #Handler for Adding a New Member button @blynk.VIRTUAL_WRITE(1)
from django.conf.urls import patterns, include, url from django.contrib import admin import Frame,Pages,Settings,API,Misc urlpatterns = patterns('', url(r'^$', Frame.Base().Home, name='Index'), url(r'^login/$', Frame.Base().Login, name='Login'), url(r'^login/_login/$', Frame.Base().ProcessLogin, name='Login'), url(r'^register/$', Frame.Base().Register, name='Register'), url(r'^register/_register/$', Frame.Base().ProcessRegister, name='Register'), url(r'^member/profile/(?P<uid>\d+)/$', Frame.Base().MakeProfile, name='Profile'), url(r'^member/usercp/$', Frame.Base().ControlPanel, name='User CP'), url(r'^member/usercp/_usercp/$', Frame.Base().ProcessUserCP, name='User CP'), url(r'^search/$', Misc.Search().doSearch, name='Search'), url(r'^forum/(?P<fid>\d+)/$', Frame.Base().Forum, name='Forum'), url(r'^thread/(?P<tid>\d+)/$', Frame.Base().Thread, name='Thread'), url(r'^action/$', Misc.Actions().Action, name='Action'), url(r'^js/(?P<fname>\w+).js', Pages.Pages()._JS, name='JavaScript File'), url(r'^css/(?P<fname>\w+).css$', Pages.Pages()._CSS, name='CSS File'), url(r'^api/v1/(?P<type>\w+)/(?P<requested>\w+|\*)/$', API.API().RenderJSON, name='API') )
# Distributed System Assignment 2 # Multithreaded Server and Client # File Name: tcpserver.py # Function: Acts as a multithreaded TCP server # Usage: In terminal "python tcpserver.py" CTRL+C to quit # Author: Rohail Altaf ########################################################### # Import necessary libraries import socket, threading, API import functionLibrary as fL from API import API # threadLock is the global thread lock variable threadLock = threading.Lock() API = API() # The Server object creates a TCP server and listens # for connections made to it. Once a connection is # made, it is passed on to the processConnection # object class Server(): TCP_ADDRESS = '' TCP_PORT = 6666 global threadLock def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.bind((self.TCP_ADDRESS, self.TCP_PORT)) print "Server Initialzed\n"
def test_call_without_credentials(self): loop = asyncio.get_event_loop() or asyncio.new_event_loop() new_api = API(USERNAME, password=PASSWORD, database=DATABASE, server=None, loop=loop) user = run(new_api.get_async('User', name='{0}'.format(USERNAME)), loop=loop) assert len(user) == 1 assert len(user[0]) == 1