def __init__(self, name, *di_args, **di_kwargs):
     API.__init__(self, name, *di_args, **di_kwargs)
     self.fails = 0
     self._run_event = Event()
     self.files_done = 0
     self._done_event = Event()
     self.message = None
 def interface_came_up(self, ip, interface_name, device_name, gateway=None, port=0):
     """
     If the initial configuration has explicitly mentioned this ip address, then use this port
     """
     for l in self._listen_args:
         if l.ip == ip:
             port = l.port
     API.interface_came_up(self, ip, interface_name, device_name, gateway=gateway, port=port)
	def __init__(self):
		self.api=API()
		self.rooms={}
		self.sections={}
		self.devices={}
		self.device_type={}
		self.section_room={}
		self.room_device={}
		self.csv=CSV(1)
    def do_POST(self):
        self.send_response(200)

        content_length = int(self.headers['content-length'])
        post_body = self.rfile.read(content_length)

        logger.info('Received new MUTATION notification')

        if len(post_body) > 0:
            API.handle_mutation_event(post_body)
示例#5
0
def initialize_extensions(app: Flask):
    DB.init_app(app=app)
    MIGRATE.init_app(app=app, db=DB)
    LIMITER.init_app(app=app)
    CORS.init_app(app=app)
    MAIL.init_app(app=app)
    sentry_sdk.init(
        integrations=[FlaskIntegration()],
        release="0.0.1",
        send_default_pii=True
    )

    # Flask Rest PLUS
    API.init_app(app=app)
示例#6
0
 def interface_came_up(self,
                       ip,
                       interface_name,
                       device_name,
                       gateway=None,
                       port=0):
     """
     If the initial configuration has explicitly mentioned this ip address, then use this port
     """
     for l in self._listen_args:
         if l.ip == ip:
             port = l.port
     API.interface_came_up(self,
                           ip,
                           interface_name,
                           device_name,
                           gateway=gateway,
                           port=port)
示例#7
0
    def __init__(self, stop_event=Event(), name="Network"):
        '''
        @param stop_event: Event that controls the run of this instance, but does not affect this event itself
        @param name: Name of the instance, must reflect the location of configuration parameters
        '''
        name += ".Dispersy"

        self.stop_event = stop_event
        self.db_reader = StatusDbReader()

        self.cfg = get_config(name)
        self.status = get_status(name)
        self.log = get_uav_logger(name)

        di_kwargs = {}
        try:
            di_kwargs = self._get_arguments_from_config()
        except:
            logger.exception(
                "Could not get arguments from config, make do with what you've got"
            )
        finally:
            self.cfg.close_connection()  # Don't need it anymore!

        API.__init__(self, name, **di_kwargs)

        self.status["state"] = self.STATES[self.state]

        self.run_event = Event()
        self.stop_on_dispersy_stop = True
        self._stopping = False

        # dictionary of known interfaces that should be used and the last state and time
        self.use_interfaces = {}  # (timestamp, status, ip)
        self._listen_args = [
            Address.unknown(l) for l in di_kwargs.get("listen", [])
        ]

        # Set callbacks
        self.state_change_callback(self._state_changed)
        self.swift_state_callback(self._swift_state_changed)

        # Set signal quit handler
        signal.signal(signal.SIGQUIT, self.on_quit)
    def __init__(self, stop_event=Event(), name="Network"):
        '''
        @param stop_event: Event that controls the run of this instance, but does not affect this event itself
        @param name: Name of the instance, must reflect the location of configuration parameters
        '''
        name += ".Dispersy"
        
        self.stop_event = stop_event
        self.db_reader = StatusDbReader()
        
        self.cfg = get_config(name)
        self.status = get_status(name)
        self.log = get_uav_logger(name)
        
        di_kwargs = {}
        try:
            di_kwargs = self._get_arguments_from_config()
        except:
            logger.exception("Could not get arguments from config, make do with what you've got")
        finally:
            self.cfg.close_connection() # Don't need it anymore!
        
        API.__init__(self, name, **di_kwargs)

        self.status["state"] = self.STATES[self.state]

        self.run_event = Event()
        self.stop_on_dispersy_stop = True
        self._stopping = False
        
        # dictionary of known interfaces that should be used and the last state and time
        self.use_interfaces = {} # (timestamp, status, ip)
        self._listen_args = [Address.unknown(l) for l in di_kwargs.get("listen", [])]
        
        # Set callbacks
        self.state_change_callback(self._state_changed)
        self.swift_state_callback(self._swift_state_changed)
        
        # Set signal quit handler
        signal.signal(signal.SIGQUIT, self.on_quit)
class TestApi(unittest.TestCase):
    def setUp(self):
        self.api = API()

    @mock.patch.object(tp.API, 'update_status')
    def test_update_status(self, mock_update_status):
        self.api.update_status("Hello World!")
        mock_update_status.assert_called_with("Hello World!")

    @mock.patch.object(tp.API, 'followers_ids')
    def test_get_my_follower_ids(self, mock_followers_ids):

        print("Mock followers: {}".format(mock_followers_ids))
        followers_ids = self.api.get_my_follower_ids()
        mock_followers_ids.assert_called()
        self.assertEqual(len(followers_ids), len(mock_followers_ids))

    @mock.patch.object(tp.API, 'followers')
    def test_get_my_followers(self, mock_followers):
        followers = self.api.get_my_followers()

        mock_followers.assert_called()
        self.assertEqual(len(followers), len(mock_followers))
 def api(self):
     """
     Returns an API object which can be used to perform API operations. oauth_code must be set
     before this can be used.
     """
     if self.oauth_code is None:
         return None
     if self._api is None:
         self._api = API(self.config['bungie_api_key'],
                         self.config['oauth_client_id'],
                         self.config['oauth_client_secret'],
                         self.oauth_code,
                         self.config['bungie_membership_type'])
     return self._api
示例#11
0
    def monitor_email() -> None:
        imapper = easyimap.connect(Config.get_imapserver(),
                                   Config.get_mailaccount(),
                                   Config.get_password())

        f = open("messages.json")
        processed_massages = json.loads(f.read())
        f.close()

        while True:
            print("Searching for command ... ")
            for mail_id in imapper.listids(limit=100):
                mail = imapper.mail(mail_id)
                body = html2text.html2text(mail.body)
                if str(
                        mail_id
                ) not in processed_massages:  #re.findall("^IMPORTANT COMMAND", body) \ and
                    subject = mail.title

                    citation = u"> From: " + mail.from_addr + '\n'
                    citation += u"> Date: " + mail.date + '\n'
                    citation += u"> Body: " + html2text.html2text(mail.body)

                    # TODO: process the body and subject through RASA and then send mail reply.
                    # Work on the seperate module for making the web hook call
                    message = API.post_request(
                        message=html2text.html2text(mail.body))

                    # TODO: Improved on the send mail response
                    EmailBot.send_mail([str(mail.from_addr)], subject, message)

                    print(citation)
                    processed_massages[str(mail_id)] = {
                        'subject': subject,
                        'message': message,
                        'ts': int(time.time())
                    }
                    f = open("messages.json", "w")
                    f.write(json.dumps(processed_massages))
                    f.close()

                    print(str(mail_id) + " processed!")
            time.sleep(Config.get_refresh())
示例#12
0
def sendProjectData():

    projectData = ProjectData(
        "Testing",
        datetime.datetime.now(),
        [
            Device("AABC1", 40),
            Device("AABC2", 70)
        ],
        110,
        80,
        "101.1212, 112.1133"
        )

    try:
        response = API.sendProjectData(keypair, projectData)

    except Exception as e:
        raise (response)
        print(e)
示例#13
0
文件: main2.py 项目: QuimLaz/HackEPS
def main():
    # create a selector class
    comparison_parameters = [1, 1, 1, 1, 1, 1, 1, 1]
    learning_rate = 0.1
    weight = 0.1
    #model = Selector(comparison_using_importance, comparison_parameters, learning_rate, weight)
    model = Selector(learning_rate, weight)
    N = 10000
    hits = 0
    last_hits = 0
    frequency = 100
    for i in range(1, N + 1):
        # get one scenario
        sample = API.get_scenario_guess_from_dataset(i)
        scenario = sample.scenario
        if scenario.agent_id != "1":
            continue
        true_solution_id = sample.task_id
        # make prediction
        prediction = model.predict(scenario)
        # check the prediction and update parameters
        guess = ScenarioGuess(scenario, prediction.id)
        # correct, true_solution_id = API.post_scenario(guess)
        if true_solution_id == guess.task_id:
            hits += 1
            last_hits += 1
        new_params = model.compute_new_params(true_solution_id)
        model.update_params(new_params)
        #model.update_params(true_solution_id)
        # save model
        if i % frequency == 0:
            print('Iterations: {}'.format(i))
            print('params: {}'.format(model.comparison_parameters))
            print('Accuracy (overall): {0:.2f}%'.format(hits / i * 100))
            print('Accuracy (last): {0:.2f}%'.format(last_hits / frequency *
                                                     100))
            print('--------------------')
            last_hits = 0
            file_name = '../models/model_v1.mod'
            save_model(file_name, model)
 def __init__(self, name, *di_args, **di_kwargs):
     API.__init__(self, name, *di_args, **di_kwargs)
     self._run_event = Event()
     self.sock_states = []
class Schematic():
	def __init__(self):
		self.api=API()
		self.rooms={}
		self.sections={}
		self.devices={}
		self.device_type={}
		self.section_room={}
		self.room_device={}
		self.csv=CSV(1)

	def getSchematic(self):
		if(self.getMetaData()==0):
			sys.exit()
		#print("Meta Data Collected")

		if(self.getSections()!=1):
			print("error occured while mapping sections")
			sys.exit()
		#print(self.sections)

		if(self.getRooms()!=1):
			print("error occured while mapping rooms")
			sys.exit()
		#print(self.rooms)
		#print(self.section_room)

		if(self.getDevices()!=1):
			print("error occured while mapping devices")
			sys.exit()

		#print(self.devices)
		#print(self.room_device)
		#print(self.device_type)

		# for a in self.devices:
		# 	did=a
		# 	name=self.getDeviceName(did)
		# 	dtype=self.getDeviceTypes(did)
		# 	print(str(did)+" - "+name+" - "+dtype)
		# sys.exit()
		return 1

	def getDeviceName(self,device):
		try:
			return self.devices[device]
		except Exception as e:
			#print('Device Not Found')
			#print(e)
			return None
		

	def getDevices(self):
		response=self.api.getDevices()
		for res in response:
			self.devices[res['id']]=res['name']
			self.room_device.setdefault(res['roomID'],[])
			self.room_device[res['roomID']].append(res['id'])
			self.device_type[res['id']]=res['type']
		return 1

	def getRoomName(self,room):
		try:
			return self.rooms[room]
		except Exception as e:
			#print('Room Not Found')
			#print(e)
			return None

	def getRoomId(self,device):
		for roomID,deviceIDs in self.room_device.items():
			for deviceID in deviceIDs:
				if(device==deviceID):
					return roomID
				else:
					flag = None
		return flag

	def getRooms(self):
		response=self.api.getRooms()
		for res in response:
			self.rooms[res['id']]=res['name']
			self.section_room.setdefault(res['sectionID'],[])
			self.section_room[res['sectionID']].append(res['id'])
		return 1

	def getSections(self):
		response=self.api.getSections()
		for res in response:
			self.sections[res['id']]=res['name']
		return 1

	def getSectionName(self,section):
		try:
			return self.sections[section]
		except Exception as e:
			#print('Section Not Found')
			#print(e)
			return None

	def getSectionId(self,room):
		for sectionID,roomIDs in self.section_room.items():
			for roomID in roomIDs:
				if(room==roomID):
					return sectionID
				else:
					flag = None
		return flag

	def getDeviceTypes(self,device):
		try:
			return self.device_type[device]
		except Exception as e:
			#print('Device Not Found')
			#print(e)
			return None

	def getMetaData(self):
		response=self.api.getInfo()
		self.csv.write(['HC Name','Serial Number','MAC Address'])
		self.csv.write([response['hcName'],response['serialNumber'],response['mac']])
		print("Extracting for : "+response['hcName'])
		return 1

	def getDeviceValue(self,device,value):
		try:
			d_type=self.getDeviceTypes(device)
			if(d_type == 'com.fibaro.doorLock'):
				if(value == '1.0'):
					return 'Locked'
				else:
					return 'Unloacked'
			elif(d_type == 'com.fibaro.binarySwitch'):
				if(value == '1.0'):
					return 'On'
				else:
					return 'Off'
			elif(d_type == 'com.fibaro.multilevelSwitch'):
				if(value == '0.0'):
					return 'Off'
				else:
					txt = str(value)+" %"
					return txt
			elif(d_type == 'com.fibaro.motionSensor'):
				if(value == '1.0'):
					return "Movement Detected (Breach State)"
				else:
					return "No Movement (Safe State)"
			elif(d_type == 'com.fibaro.doorSensor'):
				if(value == '1.0'):
					return "Door Opened (Breach State)"
				else:
					return "Door Closed (Safe State)"
			elif(d_type == 'com.fibaro.temperatureSensor'):
				txt = str(value)+" C"
				return txt
			elif(d_type == 'com.fibaro.lightSensor'):
				txt = str(value)+" LUX"
				return txt
			else:
				return value	

		except Exception as e:
			return None
示例#16
0
from flask import Flask, render_template, url_for
from flask_ask import Ask, statement, question, session

# Local imports
from src.api import API

app = Flask(__name__)
ask = Ask(app, '/')
api_instance = API()


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/code')
def get_code():
    return "Does this text get sent?"
    # return api_instance.write()

@ask.launch
def new_coding_session():
    welcome_msg = render_template('welcome')
    return question(welcome_msg)


@ask.intent("ProgramIntent")
def create_program(verb, name):
    print('program:', name)
    if name is None:
示例#17
0
 def setUp(self):
     self.api = API()
 def stop(self):
     self._stopping = True
     self.log.info("Stopping")
     API.stop(self)
     self._stop()
 def finish(self):
     API.finish(self)
     self._done_event.set()
示例#20
0
class App():
	def __init__(self):
		self.api=API()
		self.schematic=Schematic()
		self.csv=CSV(0)

	def start(self):
		if(self.checkCredentials()):
			print("Authentication complete")
		else:
			print("Incorrect Credentials")
			sys.exit()

		print("Mapping Schematic")

		if(self.schematic.getSchematic()):
			print("Schematic extracted")
		else:
			print("Unable to extract schematic")
			sys.exit()

		print("Extracting Event History")
		if(self.getEventHistory()):
			print("History extracted")
		else:
			print("Unable to extract History")
			sys.exit()

	def checkCredentials(self):
		response=self.api.getLoginStatus()
		if(response['status']):
			return 1
		else:
			return 0

	def getEventHistory(self):
		c=0
		end = int(str(time.time()).split('.')[0])
		start = end-86400
		#response = self.api.getHistory(str(start),str(end))

		csv_row = ['Section ID','Section Name','Room ID','Room Name','Device ID','Device Name','Device Type','Value (Int)','Value (Str)','DateTime']
		if(self.csv.write(csv_row)):
			pass
		else:
			print("I/O Error Occured")
			sys.exit()
		while(start>0):
			print("Day["+str(c)+"] : Extracting for "+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end)))
			response = self.api.getHistory(str(start),str(end))
			if(self.parser(response)):
				print("Day["+str(c)+"] : Extraction Completed for "+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end)))
			else:
				print("Day["+str(c)+"] : No Data found for "+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end)))
			c=c+1
			end=start
			start=start-86400
			
		print("Done")
		return 1
		#response=self.api.getHistory(start,end)

	def parser(self,data):
		for dat in data:
			if(dat):
				csv_row = []
				roomid=self.schematic.getRoomId(int(dat['deviceID']))
				#print(str(dat['deviceID'])+"="+str(roomid))
				roomname=self.schematic.getRoomName(roomid)
				sectionid=self.schematic.getSectionId(roomid)
				sectionname=self.schematic.getSectionName(sectionid)
				devicetype=self.schematic.getDeviceTypes(int(dat['deviceID']))
				devicename=self.schematic.getDeviceName(int(dat['deviceID']))
				value=dat['value']
				valuename=self.schematic.getDeviceValue(int(dat['deviceID']),value)
				datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(dat['timestamp'])))#data['timestamp']

				csv_row = [sectionid,sectionname,roomid,roomname,int(dat['deviceID']),devicename,devicetype,value,valuename,datetime]
				if(self.csv.write(csv_row)):
					pass
				else:
					print("I/O Error Occured")
					return -1
		return 1
示例#21
0
	def __init__(self):
		self.api=API()
		self.schematic=Schematic()
		self.csv=CSV(0)
 def get_todays_image() -> str:
     return API.get_image_of_day()
示例#23
0
import logging

from src import request_handler
from src.api import API
from src.config import Config
from src.logger import setup_logger

logger = logging.getLogger(__name__)

if __name__ == "__main__":
    setup_logger('output.log')

    api = API()
    api.add_filters(Config.get_option('CALLBACK_URL'), ['MUTATION'])

    request_handler.start_listening(int(Config.get_option('PORT')))
示例#24
0
    def __init__(self):
        pass

    @staticmethod
    def run_flask(*args):
        app.run(port=args[0], debug=False, use_reloader=True)


if __name__ == "__main__":
    node_list = []  # For Dev Test, Originally it will read from config.
    port = sys.argv[1]
    if len(node_list) == 0:  # Then read from config.yml
        print("Reading from config file.")
        configs = get_configs(os.getcwd() + '/config.yml')
        node_list = get_host_from_configs(configs)
    replication_factor = get_replication_factor(configs)

    handler = MainHandler(node_list)
    api_handler = ApiHandler(API())

    print("====> Replication Factor===>>", replication_factor)
    print("====>> Incoming Worker Host ===>>", node_list)

    flask_app = StartService.run_flask
    fl = Process(target=flask_app, args=(port, ))
    fl.start()
    fl1 = Process(target=health_check_nodes, args=(node_list, ))
    fl1.start()

    handle_cli(fl, handler)
示例#25
0
 def test_good_login(self):
     r = API().login(self.username, self.password)
     self.assertEqual(r.status_code, 200)
 def static_init() -> None:
     return API.static_init()
示例#27
0
 def stop(self):
     self._stopping = True
     self.log.info("Stopping")
     API.stop(self)
     self._stop()
示例#28
0
elif __file__:
    BASE_DIR = pathlib.Path(os.path.dirname(__file__))

app = Flask(__name__,
            static_folder=str(BASE_DIR / 'assets'),
            template_folder=str(BASE_DIR / 'templates'))


@app.route("/")
def home():
    return render_template("home.html", context={"name": "PyDesktop App"})


@app.route("/static/")
def serve_static():
    path_arg = request.args.get('path')  # ?path=
    if path_arg:
        abs_path = pathlib.Path(path_arg).resolve()
        if abs_path.exists():
            file_dir = abs_path.parent
            file_name = abs_path.name
            return send_from_directory(file_dir, file_name)
    return render_template("home.html", context={"name": "PyDesktop App"})


if __name__ == "__main__":
    js_api = API(name='Justin')
    window_args = {"js_api": js_api, "width": 1200}
    window = webview.create_window("PyDesktop", app, **window_args)
    js_api._window = window
    webview.start(debug=True)
 def __init__(self, name, *di_args, **di_kwargs):
     API.__init__(self, name, *di_args, **di_kwargs)
     self._need_socket_event = Event()
     self._running = Event()