Esempio n. 1
3
	def ignore_test_should_understand_redirects_to_external_targets(self):
		web = Web()
		moodle = Moodle(web)
		username = ""
		password = ""
		moodle.login(username, password)
		paeps = [ course for course in moodle.my_courses() if u"dagogische Psychologie" in course.name ].pop()
		materials = moodle.material_page_for(paeps.id)
		links = materials.find_links_in_content(materials.markup)
		for link in links:
			resource = Resource(link.getText(), link.get('href'), web, "http://elearning.uni-heidelberg.de/mod/resource/")
			response = web.head(resource.url)
			print resource.name
			print resource.url
			print response.getcode()
Esempio n. 2
0
    def __init__(self):
        self.name = 'hatch'  # Neural target
        self.results = get_args()
        self.realsense = RealSense(constants.REALSENSE_SN)
        self.camera_provider = self.realsense
        time.sleep(1)  # Let realsense run a bit before setting exposure
        self.realsense.set_exposure(10)
        if self.results.camera == 'pi':
            camera_provider = PICamera()
            logging.info('Using PI Camera provider')
        elif self.results.camera == 'realsense':
            logging.info('Using RealSense camera provider')
            camera_provider = self.realsense
        elif self.results.camera == 'cv':
            camera_provider = CVCamera(self.results.port)
        else:
            logging.error('Invalid camera provider, this shouldn\'t happen')
            sys.exit(1)

        self.display = Display(provider=camera_provider)
        if self.results.local:
            # self.tape_hsv_handler = Trackbars('2019_tape')
            self.cargo_hsv_handler = Trackbars('cargo_simple')
            self.tape_hsv_handler = FileHSV('2019_tape')
        else:
            self.tape_hsv_handler = FileHSV('2019_tape')
            self.cargo_hsv_handler = FileHSV('cargo_simple')
        if self.results.web:
            self.web = Web(self)
            self.web.start_thread()  # Run web server
        if self.results.networktables:
            self.nt = nt_handler.NT('2019')
        self.stop = False
Esempio n. 3
0
def handler(req):
	web = Web()
	load_modules(web, req)
	#raise RuntimeError("heha-1! have {0} entries".format(str(Web.menu["Monitoring"])))

	path_components = split_path(req, req.uri)

	req.content_type = "text/html"

	if path_components[0] == "":
		req.write(web.render_root_page(req))
	elif req.uri == "/style.css":
		req.content_type = "text/css"
		req.write(getStylesheet())
	elif req.uri == "/content_bandwidth_chart":
		req.write(contentBandwidthChart())
	elif path_components[0] == "module":
		text = web.module_url_handler(path_components[1], "/".join(path_components[2:]))
		req.write(text)

	elif req.uri == "/netstats":
		#req.content_type = "text/json"
		content = ""
		jsonObj = {}
		with open("/sys/class/net/eth1/statistics/rx_bytes", 'r') as content_file:
			content = int(content_file.read())
		jsonObj["date"] = time.time()
		jsonObj["stat"] = content

		req.write(json.dumps(jsonObj))

	else:
		req.write(str(path_components))

	return apache.OK
Esempio n. 4
0
    def __init__(self):
        self.results = get_args()
        self.name = self.results.target
        # Check if requested target exists
        if not utils.is_target(self.name):
            return
        if self.results.camera == 'pi':
            camera_provider = PICamera()
            logging.info('Using PI Camera provider')
        elif self.results.camera == 'realsense':
            logging.info('Using RealSense camera provider')
            camera_provider = RealSense()
        elif self.results.camera == 'cv':
            camera_provider = CVCamera(self.results.port)
        else:
            logging.error('Invalid camera provider, this shouldn\'t happen')
            sys.exit(1)

        self.display = Display(provider=camera_provider)
        if self.results.local:
            self.hsv_handler = Trackbars(self.name)
        else:
            self.hsv_handler = FileHSV(self.name)
        if self.results.web:
            self.web = Web(self)
            self.web.start_thread()  # Run web server
        if self.results.networktables:
            self.nt = nt_handler.NT(self.name)
        self.stop = False
Esempio n. 5
0
def web_remote(httpClient, httpResponse):
    """ Shows a form to enter the COM port or IP Address of a alien ezPiC-Board """
    status = 'Not connected'
    formParams = None

    port = Remote.get_port()

    if httpClient.GetRequestMethod() == 'POST':
        formParams = httpClient.ReadRequestPostedFormData()
    else:  # GET
        formParams = httpClient.GetRequestQueryParams()

    if formParams and 'port' in formParams:
        port = formParams.get('port')

    if port:
        Remote.set_port(port)
        err, ret = Remote.open()
        if err:
            Web.flash_error(httpResponse, err, ret)
        status = ret

    vars = {}
    vars['menu'] = 'remote'
    vars['port'] = port
    vars['status'] = status
    vars['com_ports'] = Remote.get_com_ports()

    return httpResponse.WriteResponsePyHTMLFile('web/www/remote.html',
                                                vars=vars)
Esempio n. 6
0
class Tab2(Tab):
    def __init__(self, master):
        Tab.__init__(self, master, u"T恤".encode('utf-8'))
        self.web = Web()
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.tshirt = StringVar()
        self.tshirt_wtime = StringVar()
        self.pair_status = StringVar()

        self.tab2_fm1 = Frame(self)
        Label(self.tab2_fm1, bg="red", fg="white", width=16, font=('Arial', 16), textvariable=sv_reg_no).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="green", fg="black", width=16, font=('Arial', 22), textvariable=sv_tshirt).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="blue", fg="white", width=16, font=('Arial', 20), textvariable=sv_tshirt_wtime).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="yellow", fg="black", width=16, font=('Arial', 22), textvariable=sv_tshirt_status).pack(side=LEFT, fill=BOTH, expand=YES)
        self.tab2_fm1.pack(side=LEFT, padx=10)

        self.tab2_fm2 = Frame(self)
        self.tab2_btn1 = Button(self.tab2_fm2, text='OK', font=('Arial', 16))
        self.tab2_btn1.pack(side=LEFT, anchor=W)
        self.tab2_btn1.bind('<Button-1>', self.get_tshirt)
        self.tab2_fm2.pack(side=LEFT, fill=BOTH, expand=YES)

    def get_tshirt(self, button):
        print type(self).__name__ + "/" + inspect.stack()[0][3]

        try:
            print uid
            result = self.web.tshirtUpdate(uid)
            sv_tshirt_wtime.set(result["result"]["tshirt_wtime"])
            sv_tshirt_status.set(result["status"])
            print result
            self.clear_profile()
        except NameError:
            sv_reg_no.set(NO_UID_ERROR)
            sv_tshirt.set(NO_UID_ERROR)
            sv_tshirt_wtime.set(NO_UID_ERROR)


    def load_profile(self, uid):
        print type(self).__name__ + "/" + inspect.stack()[0][3]

        user_info = self.web.tshirtQuery(uid)
        print user_info

        try:
            self.clear_get()

            sv_reg_no.set(str(user_info["result"]["reg_no"]) + "/" + user_info["result"]["nickname"])
            sv_tshirt.set(user_info["result"]["tshirt"])
            sv_tshirt_wtime.set(user_info["result"]["tshirt_wtime"])

            if user_info["result"]["tshirt_wtime"] != str(0):
                sv_tshirt_status.set("No T-shirt for you")

        except TypeError, ValueError:
            sv_reg_no.set(NETWORK_ERROR)
            sv_tshirt.set(NETWORK_ERROR)
            sv_tshirt_wtime.set(NETWORK_ERROR)
Esempio n. 7
0
class Updater(object):

	days_befor_delete = 3

	def __init__(self):
		self.__logger = logging.getLogger(__name__)
		self.__load_config();
		self.__database = Database(self.__host,self.__db,self.__user,self.__password)
		self.__web = Web(self.__api_key, self.__url)
		self.__storage = Storage()
		self.last_update = self.__storage.get('last_update',date(1980,01,01))
		self.last_delete = self.__storage.get('last_delete',date.today())
		self.days = timedelta(days = self.days_befor_delete)
		self.to_delete = date.today() - self.days

	def __delete(self):
		self.__logger.info('Removing old data from the database...')
		data = self.__database.get_delete_data(str(self.last_delete), str(self.to_delete))
		self.__web.delete_geodata(data)
		self.__logger.info('finished')
		self.__storage['last_delete'] = self.to_delete


	def __add(self):
		self.__logger.info('Adding new data to the database...')
		if (self.last_update > self.to_delete):
			data = self.__database.get_new_data(self.last_update)
		else:
			data = self.__database.get_data(self.last_update, self.to_delete)
		self.__web.add_geodata(data)
		self.__logger.info('finished')
		self.__storage['last_update'] = date.today()

	def __close(self):
		self.__logger.debug("Updateing stored dates. last_update: " + str(date.today()) + ", last_delete: " + str(self.to_delete))
		self.__storage.close()

	def run(self):
		self.__logger.info('Starting updater...')
		self.__logger.debug('Last update: ' + str(self.last_update) + ' with delete date: ' + str(self.last_delete) + '. Delete data which is ' + str(self.days_befor_delete) + ' old.')
		if (self.last_update < date.today()):
			self.__add()
			self.__delete()
		else:
			self.__logger.info('Not run. Data is uptodate.')
		self.__close()
		self.__logger.info('Finish updater')

	def __load_config(self):
		config = RawConfigParser()
		config.readfp(open('config.cfg'))
		# Database config
		self.__host = config.get('Database','host')
		self.__db = config.get('Database','database')
		self.__user = config.get('Database','user')
		self.__password = config.get('Database','password')
		# Web config
		self.__api_key = config.get('web','api_key')
		self.__url = config.get('web','url')
Esempio n. 8
0
 def add_web(self, url, callback):
     @functools.wraps(callback)
     def new_callback(obj):
         return callback(obj.get())
     # A Web is a Thread.
     w = Web(url)
     w.start()
     self.add(w, 'WEB', new_callback)
Esempio n. 9
0
def main():
    """ Entry point for ezPiC """
    #test.main()

    log(LOG_DEBUG, '# Starting main init')
    if CNF['useIoT']:
        Timer.init()
        Cmd.init()
        Machine.init()
        Gadget.init()
        Gateway.init()
        Rule.init()
        Device.init()
        Variable.init()
        if CNF['useCLI']:
            CLI.init()
        if CNF['useTelnet']:
            TelnetServer.init(port=CNF['portTelnet'])
    if CNF['useWeb']:
        Web.init(port=CNF['portWeb'])

    log(LOG_INFO, '# Starting main run')
    if CNF['useIoT']:
        Timer.run()
        Cmd.run()
        Machine.run()
        Gadget.run()
        Gateway.run()
        Rule.run()
        Device.run()
        Variable.run()

        # DEBUG
        if not MICROPYTHON:
            Cmd.excecute(
                'vs Lorem_ {"e": 2, "d": 756, "c": 234, "b": 12313, "a": 123}')
            Cmd.excecute('vs Lörém_ [0, 8, 15]')
            Cmd.excecute('vs Lorem {"e":2,"d":756,"c":234,"b":12313,"a":123}')
            Cmd.excecute('vs Lörém [0,8,15]')

        log(LOG_DEBUG, '# Load settings')
        Cmd.excecute("load")

    if CNF['useWeb']:
        log(LOG_DEBUG, '# Starting web server')
        Web.run(
            threaded=CNF['useIoT'])  # this call never comes back .. normally

    if CNF['useIoT']:
        if CNF['useCLI']:
            log(LOG_DEBUG, '# Starting CLI')
            CLI.run(threaded=CNF['useTelnet'])
        if CNF['useTelnet']:
            log(LOG_DEBUG, '# Starting telnet server')
            TelnetServer.run()  # this call never comes back .. normally

    log(LOG_ERROR, 'PANIC! Server terminated')
    RUN = False
Esempio n. 10
0
    def __init__(self):
        self.text_items = []
        self.chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789~!@#$%^&*()_+-=[]\\{}E9|;':\",./<>?"
        self.char_index = 0
        self.text_entry = ""
        self.current_tick = 0
        self.ticks = 0
        self.reason_for_waiting = None
        self.tape = None
        self.side = None
        self.do_monitoring = False
        self.thread = None
        self.command_thread = None
        self.process = None
        self.mid_line = ""
        self.bottom_line = ""
        self.show_track_listing = False
        self.filepath = None
        self.name = None
        self.nice_name = None
        self.recording = False
        self.killed_process = False
        self.partial_ticks = None
        self.conservative_mode = True

        self.ignore_next = False
        self.lock = False

        self.b1 = Button('GPIO21')
        self.b2 = Button('GPIO20')
        self.b3 = Button('GPIO16')
        self.b4 = Button('GPIO12')

        self.io1 = DigitalInputDevice('GPIO17')
        self.io1.when_deactivated = self.message_available

        self.display = Adafruit_SSD1306.SSD1306_128_32(rst=None)
        self.display.begin()
        self.display.clear()
        self.display.display()

        f = "/home/pi/Code/python/pytape/dos.ttf"
        self.normal_font = ImageFont.truetype(f, 8)
        self.big_font = ImageFont.truetype(f, 16)

        self.width = self.display.width
        self.height = self.display.height
        self.image = Image.new('1', (self.width, self.height))
        self.draw = ImageDraw.Draw(self.image)

        self.tc = TapeControl()
        self.w = Web(owner=self)
        # self.start_command_monitoring()
        print "Go!"
Esempio n. 11
0
def web_main(httpClient, httpResponse):
    """ Main-Page with common dashboard """

    err, result = Web.command(httpResponse, 'info')
    if err:
        Web.flash_error(httpResponse, err, result)
        result = {}

    vars = {}
    vars['menu'] = 'main'
    vars['info'] = result

    return httpResponse.WriteResponsePyHTMLFile('web/www/main.html', vars=vars)
Esempio n. 12
0
def web_gateways(httpClient, httpResponse):
    """ TODO """

    err, ret = Web.command('gateway.list')
    if err:
        Web.flash_error(httpResponse, err, ret)
        ret = []

    vars = {}
    vars['menu'] = 'gateways'
    vars['gateway_list'] = ret

    return httpResponse.WriteResponsePyHTMLFile('web/www/gateways.html', vars=vars)
Esempio n. 13
0
def web_rule_del(httpClient, httpResponse, args):
    """ TODO """
    idx = int(args['idx'])

    err, ret = Web.command('rule.delete', index=idx)
    if err:
        Web.flash_error(httpResponse, err, ret, idx)
    else:
        err, ret = Web.command('save')
        msg = 'Rule task deleted'
        httpResponse.FlashMessage(msg, 'info')

    return httpResponse.WriteResponseRedirect('/rules')
Esempio n. 14
0
def web_rules_list(httpClient, httpResponse):
    """ TODO """

    err, ret = Web.command('plugin.rule.list')
    if err:
        Web.flash_error(httpResponse, err, ret)
        ret = []

    vars = {}
    vars['menu'] = 'rules'
    vars['rule_list'] = ret

    return httpResponse.WriteResponsePyHTMLFile('web/www/rules_list.html', vars=vars)
Esempio n. 15
0
def web_gateway_del(httpClient, httpResponse, args):
    """ TODO """
    idx = int(args['idx'])

    err, ret = Web.command(httpResponse, 'gateway.delete', index=idx)
    if err:
        Web.flash_error(httpResponse, err, ret, idx)
    else:
        err, ret = Web.command(httpResponse, 'save')
        msg = 'Gateway instance deleted'
        httpResponse.FlashMessage(msg, 'info')

    return httpResponse.WriteResponseRedirect('/gateways')
Esempio n. 16
0
def web_rule_add(httpClient, httpResponse, args):
    """ TODO """
    rupid = args['rupid']

    params = {'rupid': rupid}
    err, ret = Web.command('rule.add', items=params)
    if err:
        Web.flash_error(httpResponse, err, ret, rupid)
    else:
        Web.command('save')
        msg = 'Rule "{}" added'.format(rupid)
        httpResponse.FlashMessage(msg, 'info')

    return httpResponse.WriteResponseRedirect('/rules')
Esempio n. 17
0
def web_gateway_add(httpClient, httpResponse, args):
    """ TODO """
    gwpid = args['gwpid']

    params = {'gwpid': gwpid}
    err, ret = Web.command('gateway.add', items=params)
    if err:
        Web.flash_error(httpResponse, err, ret, gwpid)
    else:
        Web.command('save')
        msg = 'Gateway "{}" added'.format(gwpid)
        httpResponse.FlashMessage(msg, 'info')

    return httpResponse.WriteResponseRedirect('/gateways')
Esempio n. 18
0
def web_rule_add(httpClient, httpResponse, args):
    """ TODO """
    ezPID = args['ezPID']

    params = {'ezPID': ezPID}
    err, ret = Web.command(httpResponse, 'rule.add', items=params)
    if err:
        Web.flash_error(httpResponse, err, ret, ezPID)
    else:
        Web.command(httpResponse, 'save')
        msg = 'Rule "{}" added'.format(ezPID)
        httpResponse.FlashMessage(msg, 'info')
        return httpResponse.WriteResponseRedirect('/rules/edit/' + str(ret))

    return httpResponse.WriteResponseRedirect('/rules')
Esempio n. 19
0
 def __login(self, username, password):
     # Login URP with specified username and password.
     login_url = 'https://uis1.fudan.edu.cn/amserver/UI/Login'
     data = {"IDToken0": "", "IDToken1": username, "IDToken2": password,
             "IDButton": "Submit", "goto": "", "encoded": "false",
             "inputCode": "", "gx_charset": "UTF-8"}
     self.__connect = Web(login_url, data)
Esempio n. 20
0
def web_rules_list(httpClient, httpResponse):
    """ TODO """

    err, ret = Web.command(httpResponse, 'rule.stage.list')
    if err:
        Web.flash_error(httpResponse, err, ret)
        ret = []

    ret.sort(key=lambda x: x['PNAME'].upper())

    vars = {}
    vars['menu'] = 'rules'
    vars['rule_list'] = ret

    return httpResponse.WriteResponsePyHTMLFile('web/www/rules_list.html',
                                                vars=vars)
Esempio n. 21
0
def book_comment(user, book_id, title, comment, proxy=None, headless=True):
    try:
        user = User(user)
        logger.info(
            '{} ver: {} author: {} worker: {} start book comment'.format(
                __title__, __version__, __author__, user.nickname))

        with Web(proxy=proxy, headless=headless) as chrome:
            if user.cookies:
                try:
                    LoginWithCookies(chrome, user).run()
                except Exception:
                    Login(chrome, user).run()
            else:
                Login(chrome, user).run()

            conf = deepcopy(FUNCTION_BOOK_COMMENT_CONFIG)
            conf['book_id'] = book_id
            conf['title'] = title
            conf['comment'] = comment

            BookComment(chrome, user, config=conf).run()

    except Exception:
        logger.error('{}|{} -->'.format('Work', 'FAILED REASON'),
                     exc_info=True)
Esempio n. 22
0
    def __init__(self, master):
        Tab.__init__(self, master, u"新增".encode('utf-8'))

        self.web = Web()
        self.db = DBController("/home/pi/pyconapac-rpi/db/pycon2015.db")
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.fullname = StringVar()
        self.uid = StringVar()
        self.pair_status = StringVar()
        self.is_reg_no = False

        self.tab3_fm1 = Frame(self)
        self.txt3_fm1 = Text(self.tab3_fm1, width=3, height=1, font=('Arial', 12))
        self.txt3_fm1.pack(side=TOP, fill=X, expand=YES)
        self.txt3_fm1.focus()

        self.tab3_btn1 = Button(self.tab3_fm1, text='OK')
        self.tab3_btn1.pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.tab3_btn1.bind('<Button-1>', self.load_profile)
        self.tab3_fm1.pack(side=LEFT, fill=BOTH, expand=YES)

        self.tab3_fm2 = Frame(self)
        Label(self.tab3_fm2, bg="red", fg="white", width=12, font=('Arial', 16), textvariable=self.reg_no).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab3_fm2, bg="green", fg="black", width=12, font=('Arial', 10), textvariable=self.nickname).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab3_fm2, bg="blue", fg="white", width=12, font=('Arial', 16), textvariable=self.fullname).pack(side=TOP, fill=BOTH, expand=YES)
        self.tab3_fm2.pack(side=LEFT, padx=10)

        self.tab3_fm3 = Frame(self)
        self.tab3_lbl_uid = Label(self.tab3_fm3, bg="white", fg="black", width=10, font=('Arial', 12), textvariable=sv_uid).pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.tab3_btn1 = Button(self.tab3_fm3, text='Pair', font=('Arial', 10))
        self.tab3_btn1.pack(side=LEFT, anchor=W)
        self.tab3_btn1.bind('<Button-1>', self.pair_uid)
        self.tab3_lbl_pair_status = Label(self.tab3_fm3, bg="yellow", fg="black", width=4, font=('Arial', 24), textvariable=self.pair_status).pack(side=LEFT, fill=BOTH, expand=YES)
        self.tab3_fm3.pack(side=LEFT, fill=BOTH, expand=YES)
Esempio n. 23
0
	def ignore_test_should_do_a_head_request(self):
		#Arrange
		url = "http://localhost:5000/" # run serve.py to run this server

		# System under Test
		web = Web()

		# Act
		response = web.head(url)

		# Assert
		contentType = response.headers["Content-Type"]
		self.assertIn("text/html", contentType)

		content = response.read()
		self.assertEqual(content, "")
Esempio n. 24
0
def web_gateways(httpClient, httpResponse):
    """ TODO """

    err, ret = Web.command(httpResponse, 'gateway.list')
    if err:
        Web.flash_error(httpResponse, err, ret)
        ret = []

    ret.sort(key=lambda x: x['NAME'].upper())

    vars = {}
    vars['menu'] = 'gateways'
    vars['gateway_list'] = ret

    return httpResponse.WriteResponsePyHTMLFile('web/www/gateways.html',
                                                vars=vars)
Esempio n. 25
0
def web_cmd(httpClient, httpResponse):
    """ Shows a form to enter a command and display the result for testing the ezPiC-commands """
    cmd = ''
    err = ''
    ret = ''
    formParams = None

    if httpClient.GetRequestMethod() == 'POST':
        formParams = httpClient.ReadRequestPostedFormData()
    else:  # GET
        formParams = httpClient.GetRequestQueryParams()

    if formParams and 'cmd' in formParams:
        cmd = formParams.get('cmd')
        #cmd = html.escape(cmd)

    if cmd:
        err, ret = Web.command(httpResponse,
                               cmd,
                               useCLI=True,
                               source=httpClient._addr)
        ret = Tool.json_str(ret)
        #ret = html.escape(ret)
        log(LOG_DEBUG, 'Web command: {}', cmd)

    vars = {}
    vars['menu'] = 'tools'
    vars['cmd'] = cmd
    vars['err'] = err
    vars['ret'] = ret

    return httpResponse.WriteResponsePyHTMLFile('web/www/cmd.html', vars=vars)
Esempio n. 26
0
def register_user(user_type='worker'):
    user_type_set = {'worker', 'marketer'}
    if user_type not in user_type_set:
        raise Exception('user_type Error')

    with Web(headless=False, proxy=get_proxy()) as chrome:
        Register(chrome, user_type=user_type).run()
    time.sleep(8)
Esempio n. 27
0
 def root_web(self):
     """Get root web"""
     if self.is_property_available('RootWeb'):
         return self.properties['RootWeb']
     else:
         return Web(
             self.context,
             ResourcePathEntry(self.context, self.resource_path, "RootWeb"))
Esempio n. 28
0
class CurrentState(CommonFrame):
    def __init__(self, parent, **kw):
        CommonFrame.__init__(self, parent, **kw)

        self.parent = parent

        self.current_row = 0

        self.headers = ["name", "state", "cpu", "memory"]

        self.web = Web()

        try:
            self.agents, self.statuses, self.last_info = self.web.get_current()

        except requests.RequestException:
            showerror("error!", "Не могу соединиться с веб службой")
            self.agents = []

        self.amountOfAgents = len(self.agents)

    def pack(self, **kw):
        Frame.pack(self, **kw)

        self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        self.bottomFrame.pack(side=BOTTOM, expand=YES, fill=BOTH)

        self.bottomFrame.columnconfigure(0, weight=1)

        ThemedButton(self.topFrame, text="R", command=self.refresh).pack(side=LEFT)

        for (i, text) in zip(range(4), self.headers):
            MyLabel(self.bottomFrame, text=text).grid(row=0, column=i, sticky=EW)
            self.bottomFrame.columnconfigure(i, weight=1)

        self.current_row += 1

        for i in range(0, self.amountOfAgents):
            for (j, item) in zip(range(0, 4), (self.agents[i], self.statuses[self.agents[i]], self.last_info[self.agents[i]]["cpu"], self.last_info[self.agents[i]]["used"])):
                if j == 1 and item == "on":
                    bg = "green"
                elif j == 1:
                    bg = "red"
                else:
                    bg = "light grey"
                ent = ColoredEntry(self.bottomFrame, width=15, readonlybackground=bg)
                ent.insert(0, item)
                ent.config(state="readonly")

                ent.grid(row=i + 1, column=j, sticky=EW)

            self.current_row += 1

    def refresh(self):
        self.canvas.delete(ALL)
        self.canvas.destroy()
        self.__init__(self.parent)
        self.pack(expand=YES, fill=BOTH)
Esempio n. 29
0
    def run(self):
        w = Web()

        while True:
            print self.current_tab

            p = subprocess.Popen('/home/pi/3rd/libnfc-1.7.0-rc7/examples/nfc-poll', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            for line in p.stdout.readlines():

                if "error" in line:
                    print line
                    # error
                    sv_reg_no.set(NFC_ERROR)
                    sv_nickname.set(NFC_ERROR)
                    sv_uid.set(NFC_ERROR)

                if "UID (NFCID1)" in line:
                    global uid
                    uid_nfcid = line.split(":")
                    uid = uid_nfcid[1].strip(' \t\n\r')
                    os.system("sudo python /home/pi/pyconapac-rpi/buzzer.py &")

                    if self.current_tab == TAB1 :
                        tab1 = Tab1(root)
                        tab1.load_profile(uid)

                    elif self.current_tab == TAB2 :
                        tab2 = Tab2(root)
                        tab2.load_profile(uid)

                    elif self.current_tab == TAB3 :
                        sv_reg_no.set("");
                        sv_nickname.set("");
                        #tab3.load_profile(uid)

                        data = {'action':'query', 'uid':uid}
                        r = w.post(data);
                        j = json.loads(r.text)

                        print uid
                        sv_uid.set(uid)


            retval = p.wait()
            time.sleep(0.1)
Esempio n. 30
0
    def __init__(self):
        """
        Create all initial handlers based on parameters from get_args.

        camera_provider : CVCamera or PICamera or RealSense
            - the type of camera to be used by self.display
        """
        self.results = get_args()
        self.name = self.results.target
        # Check if requested target exists
        if not utils.is_target(self.name):
            return

        # Set the camera provider
        if self.results.camera == 'pi':
            camera_provider = PICamera()
            logging.info('Using PI Camera provider')
        elif self.results.camera == 'realsense':
            logging.info('Using RealSense camera provider')
            camera_provider = RealSense()
        elif self.results.camera == 'cv':
            camera_provider = CVCamera(self.results.port)
        else:
            logging.error('Invalid camera provider, this shouldn\'t happen')
            sys.exit(1)

        # Create the display
        self.display = Display(provider=camera_provider)
        if self.results.local:
            self.hsv_handler = Trackbars(self.name)
        else:
            self.hsv_handler = FileHSV(self.name)

        # Create the web server
        if self.results.web:
            self.web = Web(self)
            self.web.start_thread()

        # Create the networktables server
        if self.results.networktables:
            self.nt = nt_handler.NT(self.name)

        self.logger = Logger(self)

        self.stop = False
Esempio n. 31
0
 def add(self, web_creation_information):
     web_creation_information._include_metadata = self.include_metadata
     payload = web_creation_information.payload
     from web import Web
     web = Web(self.context)
     qry = ClientQuery(self.url + "/add", ActionType.PostMethod, payload)
     self.context.add_query(qry, web)
     self.add_child(web)
     return web
Esempio n. 32
0
class Tab1(Tab):
    def __init__(self, master):
        Tab.__init__(self, master, u"報到".encode('utf-8'))
        self.web = Web()
        self.db = DBController("/home/pi/pyconapac-rpi/db/pycon2015.db.nofacebook")
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.uid = StringVar()
        self.tshirt_wtime = StringVar()

        self.tab1_lbl_reg_no = Label(self, bg="red", fg="white", font=('Arial', 16), textvariable=sv_reg_no).pack(fill=X)
        self.tab1_lbl_nickname = Label(self, bg="green", fg="black", font=('Arial', 22), textvariable=sv_nickname).pack(fill=X)
        self.tab1_lbl_uid = Label(self, bg="blue", fg="white", font=('Arial', 20), textvariable=sv_uid).pack(fill=X)
        self.tab1_lbl_status = Label(self, bg="yellow", fg="black", font=('Arial', 22), textvariable=sv_regist_status).pack(side=LEFT, fill=BOTH, expand=YES)

    def load_profile(self, uid):
        print type(self).__name__ + "/" + inspect.stack()[0][3]
        try:
            result = self.web.infoQuery(uid)
            status = result['result']['regist_wtime'] if result['result']['regist_wtime'] != '0' else 'First Check-in'
            reg_no = result['result']['reg_no']
            nickname = result['result']['nickname']
            user_info = self.db.getInfoByReg(reg_no)
            sv_reg_no.set(reg_no + "/" + user_info.ticket_type.split(' ')[-1])
            sv_nickname.set(nickname)
            sv_uid.set(uid)

            sv_regist_status.set(status)
            result = self.web.registerUpdate(reg_no, uid)

            # user_info = self.web.infoQuery(uid)
            # sv_reg_no.set(str(user_info['result']['reg_no']))
            # sv_nickname.set(str(user_info['result']['nickname']))
            # sv_uid.set(str(user_info['result']['uid']))
            # result = self.web.registerUpdate(user_info['result']['reg_no'], uid)
            print result

            # if user_info.regist_wtime == None:
            #     self.db.checkIn(uid)

        except ValueError:
            sv_reg_no.set(VALUE_ERROR)
            sv_nickname.set(VALUE_ERROR)
            sv_uid.set(uid)
Esempio n. 33
0
	def __init__(self):
		self.__logger = logging.getLogger(__name__)
		self.__load_config();
		self.__database = Database(self.__host,self.__db,self.__user,self.__password)
		self.__web = Web(self.__api_key, self.__url)
		self.__storage = Storage()
		self.last_update = self.__storage.get('last_update',date(1980,01,01))
		self.last_delete = self.__storage.get('last_delete',date.today())
		self.days = timedelta(days = self.days_befor_delete)
		self.to_delete = date.today() - self.days
Esempio n. 34
0
class Event:
    def __init__(self, tag_search):
        self.tw = Twitter()
        self.web = Web()
        self.tag_search = tag_search

    @staticmethod
    def summarization(doc):
        pattern = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
        doc = re.sub(pattern, '', str(doc))
        try:
            hasil = summarize(doc)
            return hasil
        except:
            # None data to summarize
            return None

    @staticmethod
    def get_date_event(doc):
        date_format = re.compile(
            r"[ADFJMNOS]\w* [\d]{1,2}, [\d]{4}|[ADFJMNOS]\w* [\d]{1,2} [\d]{4}"
        )
        date_event = date_format.findall(str(doc))
        if date_event:
            return date_event[0]
        else:
            return None

    def start(self):
        out_data = []
        link_from_tweet = self.tw.agent_get_link_on_screen(self.tag_search)
        self.web.urls = link_from_tweet

        text_clean_format, detail = self.web.start_get()

        for index, doc in enumerate(text_clean_format):
            try:
                # print(detail[index]['link'])
                out_data.append(
                    # {'date': self.get_date_event(doc), 'summarize': self.summarization(doc), 'detail': detail[index]}) # using gensim.summarize
                    {
                        'date':
                        self.get_date_event(doc),
                        'summarize':
                        "{} <a href='{}' target='_blank'>Read More and register here...</a>"
                        .format(text_summarize(doc, list_score=12),
                                detail[index]['link']),
                        'detail':
                        detail[index]
                    })
            except Exception as e:
                print("error: {}".format(e))

        print("Finish.........\n")
        return out_data
Esempio n. 35
0
def main():
    tw = Tweet()
    tweets = tw.get_tweets()
    exclude_list = generate_exclude_list()
    wordcloud_tweet = WC(tweets, exclude_list)
    wordcloud_tweet.generate_word_cloud("word_cloud_tweet.png")
    # wordcloud_tweet.generate_word_cloud("word_cloud_tweet_alpha.png", alpha=True)
    # wordcloud_tweet.generate_word_cloud("word_cloud_tweet_face_profile.png", mask="mask_photos/head-profile-of-young-male.png")
    # wordcloud_tweet.generate_word_cloud("word_cloud_tweet_face_profile_alpha.png", alpha=True, mask="mask_photos/head-profile-of-young-male.png")
    # wordcloud_tweet.generate_word_cloud("word_cloud_tweet_twitter_bird.png", mask="mask_photos/twitter.png")
    # wordcloud_tweet.generate_word_cloud("word_cloud_tweet_twitter_bird_alpha.png", alpha=True, mask="mask_photos/twitter.png")
    # wordcloud_tweet.overdraw_image()
    print("makarov: ")
    print(run_makarov(tweets))
    wordcloud_trend = WC(tw.get_trends_tokyo(), [])
    wordcloud_trend.generate_word_cloud("trend_tokyo.png")
    web = Web(BASE_URL, WEB_EXCLUDE_LIST)
    wordcloud_blog_words = WC(web.get_text_by_base_url(), exclude_list)
    wordcloud_blog_words.generate_word_cloud("word_cloud_blog.png", alpha=False, mask="rect")
    wordcloud_blog_words.generate_word_cloud("word_cloud_blog_large.png", alpha=True, mask="rect_large")
    conv_webp("word_cloud_blog.png")
Esempio n. 36
0
    def __init__(self):

        self.config = conf

        self.__irc = IRC()
        self.on = self.__irc.add
        self.speak = self.__irc.speak
        self.join = self.__irc.join
        self.part = self.__irc.part
        self.quit = self.__irc.quit

        self.__web = Web(self.__irc)
        self.web = self.__web.add
Esempio n. 37
0
    def __init__(self, master):
        Tab.__init__(self, master, u"報到".encode('utf-8'))
        self.web = Web()
        self.db = DBController("/home/pi/pyconapac-rpi/db/pycon2015.db")
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.uid = StringVar()
        self.tshirt_wtime = StringVar()

        self.tab1_lbl_reg_no = Label(self, bg="red", fg="white", font=('Arial', 16), textvariable=sv_reg_no).pack(fill=X)
        self.tab1_lbl_nickname = Label(self, bg="green", fg="black", font=('Arial', 22), textvariable=sv_nickname).pack(fill=X)
        self.tab1_lbl_uid = Label(self, bg="blue", fg="white", font=('Arial', 20), textvariable=sv_uid).pack(fill=X)
        self.tab1_lbl_status = Label(self, bg="yellow", fg="black", font=('Arial', 22), textvariable=sv_regist_status).pack(side=LEFT, fill=BOTH, expand=YES)
Esempio n. 38
0
 def __init__(self, version):
     self.core = Core(self.log)
     self.web = Web(self.log)
     master = Tk()
     Frame.__init__(self, master)
     master.title('AV Downloader ' + version)
     root_path_config = config.read_config(
         'config.ini', 'Paths', 'root_path')
     self.root_path = os.path.join(
         os.path.expanduser("~"), "downloads") if root_path_config is '' else root_path_config
     self.executor_ui = futures.ThreadPoolExecutor(1)
     self.window = master
     self.pack()
     self.createWidgets()
Esempio n. 39
0
def web_index(httpClient, httpResponse):
    """ Index-Page with Description. Additional handle commands over HTTP-GET"""
    queryParams = httpClient.GetRequestQueryParams()
    if queryParams and 'cmd' in queryParams:
        cmd = queryParams.get('cmd')
        err, ret = Web.command(httpResponse, cmd)
        json = {'code': err, 'result': ret}
        return httpResponse.WriteResponseJSONOk(json)

    vars = {}
    vars['menu'] = ''

    return httpResponse.WriteResponsePyHTMLFile('web/www/index.html',
                                                vars=vars)
Esempio n. 40
0
class TestDBAccess(unittest.TestCase):
    def setUp(self):
        self.web = Web()
        self.UID = '09  4d  06  02'

    def test_register(self):
        req = self.web.infoQuery(self.UID)
        self.assertEqual("60", req['result']['reg_no'])
        self.assertEqual("Bruce Tsai", req['result']['nickname'])
        req = self.web.registerUpdate(req['result']['reg_no'], self.UID)
        self.assertEqual("ok", req['status'])

    def test_query(self):
        req = self.web.infoQuery(self.UID)
        self.assertEqual("60", req['result']['reg_no'])
        self.assertEqual("Bruce Tsai", req['result']['nickname'])

    def test_tshirt_query(self):
        req = self.web.tshirtQuery(self.UID)
        self.assertEqual("M /160~170cm", req['result']['tshirt'])

    def test_tshirt_update(self):
        req = self.web.tshirtUpdate(self.UID)
        self.assertEqual("ok", req['status'])
Esempio n. 41
0
    def __init__(self, parent, start, end, first, **kw):
        CommonFrame.__init__(self, parent, **kw)

        self.parent = parent

        self.current_row = 0

        self.headers = ["name", "date", "cpu", "memory"]

        self.web = Web()

        self.btn = ThemedButton(self.topFrame, text="OK", command=self.accept)

        self.start = SmartEntry(self.topFrame, start, first)

        self.end = SmartEntry(self.topFrame, end, first)

        self.amountOfEntries = 0
Esempio n. 42
0
    def __init__(self, parent, **kw):
        CommonFrame.__init__(self, parent, **kw)

        self.parent = parent

        self.current_row = 0

        self.headers = ["name", "state", "cpu", "memory"]

        self.web = Web()

        try:
            self.agents, self.statuses, self.last_info = self.web.get_current()

        except requests.RequestException:
            showerror("error!", "Не могу соединиться с веб службой")
            self.agents = []

        self.amountOfAgents = len(self.agents)
Esempio n. 43
0
def daily_work(headless=WEBDRIVER_HEADLESS):
    """
    日常工作的任务包括登录、收藏及阅读默认的书籍
    :return:
    """
    try:
        user = User(get_sequence_user())
        logger.info('{} ver: {} author: {} worker: {} START DAILY WORK'.format(
            __title__, __version__, __author__, user.nickname))

        with Web(headless=headless) as chrome:

            user_recomment_num = api_user_info(user, 'recomment')

            if user_recomment_num:
                login = Login(chrome, user)
            elif user.last_work_time and user.cookies:
                if is_today(user.last_work_time):
                    login = LoginWithCookies(chrome, user)
                else:
                    login = Login(chrome, user)
            else:
                login = Login(chrome, user)

            login.run()

            # 收藏
            if user.is_collect == '0':
                func_collect = CollectBook(chrome, user)
                func_collect.run()

            # 推荐
            if user_recomment_num:
                func_recommend = RecommendBook(chrome, user)
                func_recommend.run()

            # 阅读
            func_read = ReadBook(chrome, user)
            func_read.run()
    except Exception:
        logger.error('{}|{} -->'.format('Work', 'FAILED REASON'),
                     exc_info=True)
Esempio n. 44
0
def web_rule_edit(httpClient, httpResponse, args):
    """ TODO """
    idx = int(args['idx'])

    err, ret = Web.command(httpResponse, 'rule.getparams', index=idx)
    if err:
        Web.flash_error(httpResponse, err, ret, idx)
        return httpResponse.WriteResponseRedirect('/rules')

    params = {}
    params.update(ret)

    if httpClient.GetRequestMethod() == 'POST':
        formParams = httpClient.ReadRequestPostedFormData()
        if formParams:
            formParams['ENABLE'] = 'ENABLE' in formParams  # checkbox -> bool
            params.update(formParams)
        err, ret = Web.command(httpResponse,
                               'rule.setparams',
                               index=idx,
                               params=formParams)
        if not err:
            err, ret = Web.command(httpResponse, 'save')
        if err:
            Web.flash_error(httpResponse, err, ret, idx)
        else:
            httpResponse.FlashMessage('Settings saved', 'info')
    else:  # GET
        pass

    vars = {}
    vars['menu'] = 'rules'
    vars['index'] = idx
    vars.update(params)

    err, html = Web.command(httpResponse, 'rule.gethtml', index=idx)

    return httpResponse.WriteResponsePyHTMLFile(html, vars=vars)
Esempio n. 45
0
    def __init__(self, master):
        Tab.__init__(self, master, u"T恤".encode('utf-8'))
        self.web = Web()
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.tshirt = StringVar()
        self.tshirt_wtime = StringVar()
        self.pair_status = StringVar()

        self.tab2_fm1 = Frame(self)
        Label(self.tab2_fm1, bg="red", fg="white", width=16, font=('Arial', 16), textvariable=sv_reg_no).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="green", fg="black", width=16, font=('Arial', 22), textvariable=sv_tshirt).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="blue", fg="white", width=16, font=('Arial', 20), textvariable=sv_tshirt_wtime).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab2_fm1, bg="yellow", fg="black", width=16, font=('Arial', 22), textvariable=sv_tshirt_status).pack(side=LEFT, fill=BOTH, expand=YES)
        self.tab2_fm1.pack(side=LEFT, padx=10)

        self.tab2_fm2 = Frame(self)
        self.tab2_btn1 = Button(self.tab2_fm2, text='OK', font=('Arial', 16))
        self.tab2_btn1.pack(side=LEFT, anchor=W)
        self.tab2_btn1.bind('<Button-1>', self.get_tshirt)
        self.tab2_fm2.pack(side=LEFT, fill=BOTH, expand=YES)
Esempio n. 46
0
def web_rule_edit(httpClient, httpResponse, args):
    """ TODO """
    idx = int(args['idx'])

    err, ret = Web.command('rule.getparam', index=idx)
    if err:
        Web.flash_error(httpResponse, err, ret, idx)
        return httpResponse.WriteResponseRedirect('/rules')

    params = {}
    params.update(ret)

    if httpClient.GetRequestMethod() == 'POST':
        formParams = httpClient.ReadRequestPostedFormData()        
        if formParams:
            formParams['enable'] = 'enable' in formParams   # checkbox -> bool
            formParams['timer'] = int(formParams.get('timer', 0))
            for key, value in params.items():
                if key in formParams:
                    params[key] = formParams.get(key)
        err, ret = Web.command('rule.setparam', index=idx, params=params)
        if err:
            Web.flash_error(httpResponse, err, ret, idx)
        err, ret = Web.command('save')
        httpResponse.FlashMessage('Settings saved', 'info')
    else: # GET
        pass

    vars = {}
    vars['menu'] = 'rules'
    vars['index'] = idx
    vars.update(params)

    err, html = Web.command('rule.gethtml', index=idx)

    return httpResponse.WriteResponsePyHTMLFile(html, vars=vars)
Esempio n. 47
0
    def __init__(self, parent, **kw):

        CommonFrame.__init__(self, parent, **kw)

        self.buttonText = ["+", "-", "M"]
        self.handlers = [self.add, self.delete, self.modify]
        self.labelText = ["name", "http", "period"]

        self.rawArray = []

        self.web = Web()

        try:
            self.agent = self.web.create_agent()

        except requests.RequestException:
            self.agent = Agent([], [], [], [], {})

        self.amountOfAgents = len(self.agent.agents) + 1

        self.current_row = 0

        self.checked_row = 0
Esempio n. 48
0
def web_variable_full_list(httpClient, httpResponse, args=None):
    """ TODO """
    key = ''
    value = ''
    if args:
        act_tick = int(args.get('tick', 0))
    else:
        act_tick = 0

    if httpClient.GetRequestMethod() == 'POST':
        formParams = httpClient.ReadRequestPostedFormData()
    else:  # GET
        formParams = httpClient.GetRequestQueryParams()

    if formParams and 'key' in formParams:
        key = formParams.get('key')
        value = formParams.get('value')
        variable = {}
        variable['key'] = key
        variable['value'] = value
        #variable['source'] = 'WEB-SET'
        err, ret = Web.command(httpResponse, 'variable.set', items=variable)
        if err:
            Web.flash_error(httpResponse, err, ret)

    err, ret = Web.command(httpResponse, 'variable.full.list', index=act_tick)
    if err:
        Web.flash_error(httpResponse, err, ret)
        ret = {}

    vars = {}
    vars['menu'] = 'tools'
    vars['variable_list'] = ret['variables']
    vars['last_tick'] = ret['tick']
    vars['act_tick'] = act_tick
    vars['add_key'] = key
    vars['add_value'] = value

    return httpResponse.WriteResponsePyHTMLFile('web/www/variablesfull.html',
                                                vars=vars)


#######
Esempio n. 49
0
from web import Web
from game import Game
import time
import pyautogui

running = True
while running == True:
    try:

        online_status = 'status_three'
        streaming = False

        #we want to generate the liveinfo.aspx data and parse it @ status_three or status_two
        while online_status == 'status_three' or online_status == 'status_two':
            #values stores all the web data available
            values = Web.get_web_data()
            players_online = []
            rooms = []

            for room in values['rooms']:
                rooms.append(room['id'])
                rooms.append(room['name'])

            for player in values['players']:
                players_online.append(player['name'])
                players_online.append(player['room'])
                players_online.append(player['afk'])

            #check_player_status returns an array with the status of the user [0], and roomid [1]
            #status_one: player is online and NOT AFK
            #status_two: player is online but AFK
Esempio n. 50
0
def main(uid):
    web = Web()
    r = web.infoQuery(uid)
Esempio n. 51
0
 def __init__(self,dic):
      Web.__init__(self,dic)
      self.url='http://stock.cfi.cn/BCA0A4127A4346A4440.html'
      self.soup=None
      self.fromweb="中财网研报"
      print '中财网研报启动成功'
Esempio n. 52
0
 def __init__(self,dic):
      Web.__init__(self,dic)
      self.url='http://stock.10jqka.com.cn/tzjh_list/'
      self.soup=None
      self.fromweb="同花顺投资机会"
      print '同花顺投资机会初始化成功'
Esempio n. 53
0
class Winged(QWidget):

    def __init__(self, box, pref):
        QWidget.__init__(self)
        self._box = box
        self.pref = pref

        vbox = QVBoxLayout(self)

        hbox = QHBoxLayout()
        self.btnMyFiles = QPushButton(QIcon(config.images['myfiles']), 'My Files')
        self.btnFriendFiles = QPushButton(QIcon(config.images['friends']), 'Friends Files')
        self.btnUpload = QPushButton(QIcon(config.images['upload']), 'Manage/Upload')
        self.btnFind = QPushButton(QIcon(config.images['search']), 'Find Friends')
        hbox.addWidget(self.btnMyFiles)
        hbox.addWidget(self.btnFriendFiles)
        hbox.addWidget(self.btnUpload)
        hbox.addWidget(self.btnFind)
        vbox.addLayout(hbox)

        self.stack = StackedWidget()
        self.myFiles = MyFiles(self, self.pref)
        self.stack.addWidget(self.myFiles)
        self.friendFiles = FriendFiles(self, self.pref)
        self.stack.addWidget(self.friendFiles)
        self.uploadFiles = UploadFiles()
        self.stack.addWidget(self.uploadFiles)
        self.inviteFriends = InviteFriends(self)
        self.stack.addWidget(self.inviteFriends)
        vbox.addWidget(self.stack)

        self._status = StatusBar(self)
        self._status.hide()
        vbox.addWidget(self._status)

        self.overlay = Overlay(self)
        self.overlay.show()

        self.shortFind = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self)
        
        self.connect(self.btnMyFiles, SIGNAL("clicked()"), lambda: self.stack.setCurrentIndex(0))
        self.connect(self.btnFriendFiles, SIGNAL("clicked()"), lambda: self.stack.setCurrentIndex(1))
        self.connect(self.btnUpload, SIGNAL("clicked()"), lambda: self.stack.setCurrentIndex(2))
        self.connect(self.btnFind, SIGNAL("clicked()"), lambda: self.stack.setCurrentIndex(3))
        self.connect(self.shortFind, SIGNAL("activated()"), self._status.show_status)

        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL("timeout()"), self.update)
        self.timer.start(self.pref.get('time', 10) * 1000 * 60)

    def update(self):
        self.tempSizeFiles = self.sizeMyFiles
        self.tempSizeFriends = self.sizeFriendFiles
        self.thread.executable = self.thread.update_files
        self.thread.start()

    def find_friend(self, name):
        self.thread.api.invite(name)

    def files_updated(self):
        self.load_tables()
        if self.tempSizeFiles != self.sizeMyFiles or self.tempSizeFriends != self.sizeFriendFiles:
            self.show_tray_message('New Files added!')

    def find(self, text):
        widget = self.stack.currentWidget()
        widget.find(text)

    def delete(self, data):
        self.thread.api.delete_file(data)

    def preview_item(self, link):
        html = '<html><body><img src="' + link + '"/></body></html>'
        self.web = Web(self, '', html)
        self.web.show()

    def save_file(self, data, folder):
        self.myFiles._btnDownload.setEnabled(False)
        self.friendFiles._btnDownload.setEnabled(False)
        self._status.showMessage('DOWNLOADING...', 2000)
        self.thread.data = data
        self.thread.folder = folder
        self.thread.executable = self.thread.download_file
        self.thread.start()

    def load_tables(self):
        self.overlay.hide()
        self.myFiles.load_table(self.thread.api.files)
        self.friendFiles.load_table(self.thread.api.filesFriends)
        self.sizeMyFiles = len(self.thread.api.files)
        self.sizeFriendFiles = len(self.thread.api.filesFriends)
        self._status.hide()

    def clean_tables(self):
        rowsCount = range(self.myFiles._table.rowCount())
        rowsCount.reverse()
        for i in rowsCount:
            self.myFiles._table.removeRow(i)
        rowsCount = range(self.friendFiles._table.rowCount())
        rowsCount.reverse()
        for i in rowsCount:
            self.friendFiles._table.removeRow(i)

    def show(self):
        self._box.setFixedWidth(800)
        self._box.setFixedHeight(350)
        self.thread = Thread(self._box.user, self._box.password)
        self.thread.executable = self.thread.get_files
        self.connect(self.thread, SIGNAL("filesList()"), self.load_tables)
        self.connect(self.thread, SIGNAL("filesUpdated()"), self.files_updated)
        self.connect(self.thread, SIGNAL("downloadFinished(QString)"), self.download_complete)
        self.thread.start()
        self.setVisible(True)

    def download_complete(self, name):
        self.show_tray_message('DOWNLOAD COMPLETE: ' + name)
        self.myFiles._btnDownload.setEnabled(True)
        self.friendFiles._btnDownload.setEnabled(True)

    def show_tray_message(self, message):
        self._box._tray.showMessage('WingedBox', message, QSystemTrayIcon.Information, 2000)

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()
Esempio n. 54
0
 def preview_item(self, link):
     html = '<html><body><img src="' + link + '"/></body></html>'
     self.web = Web(self, '', html)
     self.web.show()
Esempio n. 55
0
class Bot(object):

    __web = None
    __irc = None

    def __init__(self):

        self.config = conf

        self.__irc = IRC()
        self.on = self.__irc.add
        self.speak = self.__irc.speak
        self.join = self.__irc.join
        self.part = self.__irc.part
        self.quit = self.__irc.quit

        self.__web = Web(self.__irc)
        self.web = self.__web.add

    def hook(self, source, rule, function):

        """Allow for the addition of existing functions without using the
        decorator pattern
        """

        if source == 'irc':

            self.__irc.hooks.append({
                'rule': re.compile(rule),
                'function': function
            })

        elif source == 'web':

            self.__web.hooks.append({
                'rule': re.compile(rule),
                'function': function
            })

    def monitor(self, **kwargs):

        """Determine the configuration, setup the connection, and then listen
        for data from the server. PONG when a PING is recieved. Otherwise
        iterate over the functions and check if the rule matches the message.
        If so, call the function with the context and the result of the
        matching.
        """

        for key in kwargs.keys():

                conf[key] = kwargs[key]

        conf['channels'] = conf['channels'].split(',')

        connection.connect()

        self.__irc.monitor()
        self.__web.monitor()

        while True:

            pass
Esempio n. 56
0
	def test_should_do_a_get_request(self):
		url = "http://localhost:5000/file_that_is_not_there" # run serve.py to run this server
		web = Web()
		response = web.get(url)
		status = response.getcode()
		self.assertEqual(200, status)
Esempio n. 57
0
from web import Web

web = Web()
cmd = {'action':'restore'}
r = web.post(cmd)
print r.status_code
print r.text

Esempio n. 58
0
class Tab3(Tab):
    def __init__(self, master):
        Tab.__init__(self, master, u"新增".encode('utf-8'))

        self.web = Web()
        self.db = DBController("/home/pi/pyconapac-rpi/db/pycon2015.db")
        self.reg_no = StringVar()
        self.nickname = StringVar()
        self.fullname = StringVar()
        self.uid = StringVar()
        self.pair_status = StringVar()
        self.is_reg_no = False

        self.tab3_fm1 = Frame(self)
        self.txt3_fm1 = Text(self.tab3_fm1, width=3, height=1, font=('Arial', 12))
        self.txt3_fm1.pack(side=TOP, fill=X, expand=YES)
        self.txt3_fm1.focus()

        self.tab3_btn1 = Button(self.tab3_fm1, text='OK')
        self.tab3_btn1.pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.tab3_btn1.bind('<Button-1>', self.load_profile)
        self.tab3_fm1.pack(side=LEFT, fill=BOTH, expand=YES)

        self.tab3_fm2 = Frame(self)
        Label(self.tab3_fm2, bg="red", fg="white", width=12, font=('Arial', 16), textvariable=self.reg_no).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab3_fm2, bg="green", fg="black", width=12, font=('Arial', 10), textvariable=self.nickname).pack(side=TOP, fill=BOTH, expand=YES)
        Label(self.tab3_fm2, bg="blue", fg="white", width=12, font=('Arial', 16), textvariable=self.fullname).pack(side=TOP, fill=BOTH, expand=YES)
        self.tab3_fm2.pack(side=LEFT, padx=10)

        self.tab3_fm3 = Frame(self)
        self.tab3_lbl_uid = Label(self.tab3_fm3, bg="white", fg="black", width=10, font=('Arial', 12), textvariable=sv_uid).pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.tab3_btn1 = Button(self.tab3_fm3, text='Pair', font=('Arial', 10))
        self.tab3_btn1.pack(side=LEFT, anchor=W)
        self.tab3_btn1.bind('<Button-1>', self.pair_uid)
        self.tab3_lbl_pair_status = Label(self.tab3_fm3, bg="yellow", fg="black", width=4, font=('Arial', 24), textvariable=self.pair_status).pack(side=LEFT, fill=BOTH, expand=YES)
        self.tab3_fm3.pack(side=LEFT, fill=BOTH, expand=YES)

    def clear_profile(self):
        self.reg_no.set("")
        self.nickname.set("")
        self.fullname.set("")
        self.txt3_fm1.delete("1.0", "end")

    def clear_pair(self):
        sv_uid.set("")
        self.pair_status.set("")


    def load_profile(self, button):
        print type(self).__name__ + "/" + inspect.stack()[0][3]
        global reg_no
        reg_no = self.txt3_fm1.get("1.0", "end")
        user_info = self.db.getInfoByReg(int(reg_no))
        reg_no = user_info.reg_no
        self.reg_no.set(str(user_info.reg_no) + "/" + user_info.ticket_type.split(' ')[-1])
        self.nickname.set(user_info.nickname)
        self.fullname.set(user_info.fullname)
        self.clear_pair()
        self.is_reg_no = True

    def pair_uid(self, button):
        print type(self).__name__ + "/" + inspect.stack()[0][3]
        # from nfc import NFC
        # NFC('/home/pi/3rd/libnfc-1.7.0-rc7/examples/nfc-poll').read()
        try :
            if self.is_reg_no != True:
                return
            result = self.web.registerUpdate(reg_no, uid)
            print result
            self.pair_status.set(result["status"])
            self.is_reg_no = False
        except NameError:
            print "NameError"
            self.pair_status.set("NameError")
        finally:
            self.clear_profile()
            sv_uid.set("")
Esempio n. 59
0
 def setUp(self):
     self.web = Web()
     self.UID = '09  4d  06  02'
Esempio n. 60
0
	def test_should_do_a_get_request(self):
		url = "http://localhost:5000/" # run serve.py to run this server
		web = Web()
		response = web.get(url)
		content = response.read()
		self.assertEqual(content, "Hello")