Exemple #1
0
    def default(self):
        doc = dominate.document(title='Watcher')
        doc.attributes['lang'] = 'en'

        with doc.head:
            Head.insert()
            link(rel='stylesheet',
                 href=core.URL_BASE + '/static/css/status.css')
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/{}/status.css'.format(core.THEME))
            link(rel='stylesheet',
                 href=core.URL_BASE + '/static/css/movie_status_popup.css')
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/{}/movie_status_popup.css'.format(core.THEME))
            script(type='text/javascript',
                   src=core.URL_BASE + '/static/js/status/main.js?v=12.27')

        with doc:
            Header.insert_header(current="status")
            with div(id='content'):
                self.movie_list()
            div(id='overlay')
            div(id='status_pop_up')

        return doc.render()
Exemple #2
0
 def __init__(self, params=None):
     Header.__init__(self, params)
     self.name = "Accept"
     self.max_types = 10  # Allow this many types
     self.valid_media_range = {
         "application": [
             "javascript", "json", "x-www-form-urlencoded", "xml", "zip",
             "pdf", "sql", "graphsql", "ld+json", "msword",
             "vnd.openxmlformats-officedocument.wordprocessingml.document",
             "vnd.ms-excel",
             "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
             "vnd.ms-powerpoint",
             "vnd.openxmlformats-officedocument.presentationml.presentation",
             "vnd.oasis.opendocument.text", "*"
         ],
         "audio": ["mpeg", "ogg", "*"],
         "multipart": ["form-data", "*"],
         "text": ["css", "html", "csv", "plain", "*"],
         "image": ["png", "jpeg", "gif", "*"],
         "*": ["*"]
     }
     self.valid_param_range = {
         "q": [str(float(i) / 10) for i in range(11)],
         "charset": ["UTF-8"]
     }
     self.value = self.generate_valid_value()
Exemple #3
0
 def _send_packets(self):
     finished = False
     for pos in range(self.window_base, self.window_max + 1):
         if pos >= len(self.queue):
             data = self.data[:500]
             self.data = self.data[500:]
             if not data:
                 self._finish()
                 finished = True
                 break
             header = Header(self.seqn,
                             self.received_seqn,
                             pos,
                             self.window_size,
                             Header.checksum(data),
                             ftp=True)
             packet = Packet(header.formatted + data)
             self.seqn += len(data)
             self.queue.append(packet)
         packet = self.queue[pos]
         if packet.state not in [RECEIVED, SENT] or packet.timeout():
             packet.send(self.udp_connection, self.host, self.port)
         self._receive()
     if finished is False:
         self._advance_window()
     else:
         return False
Exemple #4
0
    def __init__(self,
                 in_code,
                 seq_number,
                 ack_number,
                 d_port,
                 s_port,
                 win_size=0,
                 data=b'',
                 fin=False,
                 syn=False):
        if in_code == 4:  # ack packet
            Header.__init__(self,
                            seq_number,
                            s_port,
                            d_port,
                            ack_number,
                            ack=True,
                            win_size=win_size,
                            syn=syn)
            self.data = data

        if in_code == 3:  # data packet
            Header.__init__(self,
                            seq_number,
                            s_port,
                            d_port,
                            ack_number,
                            fin=fin)
            self.data = bitstring.BitArray(data)
Exemple #5
0
    def __init__(self):
        super(SongListScreen, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('song list')
        layout = self.get_layout_manager()

        self.header = Header('All Songs')
        self.header.set_width(self.get_width())
        layout.add(self.header, clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.right_arrow = RightArrow()

        songs = Song.objects.filter(approved=True).order_by('title')
        self.songs = ScrollingText(map(BlinkingText, songs),
                                   items_on_screen=settings.SONG_LIST_ITEMS)
        self.songs.set_width(self.get_width() - (self.left_arrow.get_width() +
                                                 self.right_arrow.get_width()))
        self.songs.set_height(self.get_height() - self.header.get_height())

        layout.add(self.songs, clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_END)

        layout.add(self.left_arrow, clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.right_arrow, clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)
class UserInterface(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.header = Header(self)
        self.header.pack(side="top", fill="both")
        self.view = tk.Frame(master=self)
        fontStyle = tkFont.Font(family="Lucida Grande", size=20)
        self.welcome = tk.Label(master=self.view,
                                text="WELCOME",
                                pady=10,
                                font=fontStyle,
                                bg="lightgrey")
        self.welcome.pack(fill="x", expand=True)
        self.underHeading = tk.Label(master=self.view,
                                     text="Press the menu to get started",
                                     pady=30)
        self.underHeading.pack()
        self.view.pack(fill="both")

    #def switchSidebar(self, sidebar):
    #    self.sidebar.pack_forget()
    #    self.sidebar = Sidebar(self, sidebar)
    #    self.sidebar.pack(side="left", fill = "x")

    def switchView(self, view):
        self.view.pack_forget()
        if (view == "Clients"):
            self.view = ClientsView(self)
        elif (view == "Invoices"):
            self.view = InvoicesView(self)
        elif (view == "Products"):
            self.view = ProductsView(self)
        self.view.pack(fill="both")
Exemple #7
0
 def __init__(self, src_port=0x0, dst_port=0x0, data=''):
     super().__init__()
     self.src_port = src_port
     self.dst_port = dst_port
     self.header = Header()
     self.data = data
     pass
Exemple #8
0
    def default(self):
        doc = dominate.document(title='Watcher')

        with doc.head:
            Head.insert()
            link(rel='stylesheet', href=core.URL_BASE + '/static/css/add_movie.css')
            link(rel='stylesheet', href=core.URL_BASE + '/static/css/{}/add_movie.css'.format(core.THEME))
            link(rel='stylesheet', href=core.URL_BASE + '/static/css/movie_info_popup.css')
            link(rel='stylesheet', href=core.URL_BASE + '/static/css/{}/movie_info_popup.css'.format(core.THEME))
            script(type='text/javascript', src=core.URL_BASE + '/static/js/add_movie/main.js?v=01.03')

        with doc:
            Header.insert_header(current="add_movie")
            with div(id='search_box'):
                input(id='search_input', type="text", placeholder="Search...", name="search_term")
                with button(id="search_button"):
                    i(cls='fa fa-search')
            div(id='thinker')
            with div(id="database_results"):
                ul(id='movie_list')

            div(id='overlay')

            div(id='info_pop_up')

        return doc.render()
Exemple #9
0
class Segment:
    def __init__(self, src_port=0x0, dst_port=0x0, data=''):
        super().__init__()
        self.src_port = src_port
        self.dst_port = dst_port
        self.header = Header()
        self.data = data
        pass

    def build_segment(self, seq=0x0, ack=0x0):
        self.header.source_port = self.src_port
        self.header.destination_port = self.dst_port
        self.header.sequence_number = seq
        self.header.ack_number = ack
        segmento = ''
        if len(self.data) != 0:
            self.header.window_size = len(self.data)
            segmento = self.header.build_header()
            if len(self.data) == 700: segmento += self.data
            else: segmento += self.data + (700 - len(self.data)) * "0"

        else:
            self.header.window_size = 0x0
            segmento = self.header.build_header()
        return bytearray.fromhex(segmento)

    pass
Exemple #10
0
class Filetype(object):
    
    def __init__(self, process_map, extra_header):
        self.lock = True
        self.logger = logging.getLogger(__name__)
        conf = Config()
        root = conf.config_directory["ROOT"]

        requested_file = root + process_map["FILE"]
        self.status = self.__get_status(requested_file)
        self.header = Header(self.status)
        self.process_map = process_map
        self.body = ""
        for key, value in extra_header.iteritems():
            self.header.set_extra(key, value)

    def __get_status(self, requested_file):
        if not os.path.isfile(requested_file):
            # maybe chcanged for dynamic 404 displaying
            return Status_NOTFOUND()
        else:
            return Status_OK(requested_file)

    @abstractmethod
    def set_header(self):
        pass

    def sendinfo(self):
        self.set_header()
        if not isinstance(self.status, Status_OK):
            self.header.set_type("text")
        return self.header.get_header() + self.body
Exemple #11
0
	def send(self, data):

		header = Header()
		header.size = len(data)
		header.sequence_number = self.send_sequence

		data = header.to_bytes() + data

		while True:
			#TODO: this could be done more elegantly
			if(len(self.workers) == 0):
				Log.log("Shutdown multiplexer. No workers found")
				self.cleanup()
				sys.exit(0)

			worker = self.workers[self.send_index][0]

			#Increment the sequence number and the send_index to send along another worker
			self.send_index = (1 + self.send_index) % len(self.workers)

			try:

				worker.write(data)
				worker.flush()

				break
			except IOError as e:
				if e.errno == 11:
					#TODO: whut. Why did I do this?
					pass
				else:
					raise e

		self.send_sequence = self.send_sequence + 1
Exemple #12
0
class ArtistDetailScreen(Screen):
    def __init__(self, artist):
        super(ArtistDetailScreen, self).__init__(
            clutter.BinLayout(clutter.BIN_ALIGNMENT_CENTER,
                              clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('artist detail %s' % artist.name)
        layout = self.get_layout_manager()

        photo = artist.random_photo()
        self.background = BackgroundImages(artist)
        #self.background = clutter.Texture(settings.MEDIA_ROOT + "/" + photo.photo.name)
        self.background.set_opacity(30)
        layout.add(self.background, clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_END)
        self.background.lower_bottom()

        self.header = Header('Artist Details')
        self.header.set_width(self.get_width())
        layout.add(self.header, clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()

        songs = artist.song_set.filter(approved=True).order_by('title')
        self.songs = None
        if len(songs) > 0:
            self.right_arrow = RightArrow()
            self.songs = ScrollingText(
                map(BlinkingText, songs),
                items_on_screen=settings.SONG_LIST_ITEMS)
            self.songs.set_width(self.get_width() -
                                 (self.left_arrow.get_width() +
                                  self.right_arrow.get_width()))
            self.songs.set_height(self.get_height() - self.header.get_height())
            layout.add(self.songs, clutter.BIN_ALIGNMENT_CENTER,
                       clutter.BIN_ALIGNMENT_END)
            layout.add(self.right_arrow, clutter.BIN_ALIGNMENT_END,
                       clutter.BIN_ALIGNMENT_CENTER)

        else:
            text = clutter.Text('Router Bold 70', 'No songs available.')
            text.set_color(clutter.Color(200, 200, 200, 0xff))
            layout.add(text, clutter.BIN_ALIGNMENT_CENTER,
                       clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.left_arrow, clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

    def on_press(self, actor, event):
        """
        """
        if self.songs:
            self.songs.on_press(actor, event)

        if event.keyval == clutter.keysyms.Left:
            self.get_parent().remove_screen(self)
        if event.keyval == clutter.keysyms.Right:
            if self.songs:
                self.get_parent().new_screen(
                    SongDetailScreen(self.songs.selected.obj))
Exemple #13
0
def create_header(headerText, rightHeaderLines, logoUrl):
    header = Header(headerMarginTop=0.9, debug=False)
    logo = importSVG(
        logoUrl, scale=1.0, width=60,
        height=110)  # important for scaling inside the header table !
    defaultHeader, reportTitle = header.headerBuild(
        headerText, figure_left=logo, right_lines=rightHeaderLines)
    return defaultHeader
Exemple #14
0
 def _set_header(self, key, value):
   header = self._get_header(key)
   if not header:
     header = Header(key, value)
     self._headers.append(header)
   else:
     header.value = value
   return self
Exemple #15
0
def test_header():
	header = Header()
	assert(header.size == 0)
	assert(header.sequence_number == 0)

	header.size = 10
	header.sequence_number = 23

	assert(header.to_string() == "SIZE=10&SEQUENCE=23\n")
Exemple #16
0
    def default(self):
        doc = dominate.document(title='Watcher')
        doc.attributes['lang'] = 'en'

        with doc.head:
            Head.insert()
            link(rel='stylesheet',
                 href=core.URL_BASE + '/static/css/status.css?v=02.22')
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/{}status.css?v=02.22'.format(
                     core.CONFIG['Server']['theme']))
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/movie_status_popup.css?v=02.22')
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/{}movie_status_popup.css?v=02.22'.format(
                     core.CONFIG['Server']['theme']))
            script(type='text/javascript',
                   src=core.URL_BASE + '/static/js/status/main.js?v=02.17')

        with doc:
            Header.insert_header(current="status")
            with div(id='content'):
                with div(id='view_config'):
                    span('Display: ')
                    with select(id='list_style'):
                        options = ['Posters', 'List', 'Compact']
                        for opt in options:
                            option(opt, value=opt.lower())
                    span('Order By: ')
                    with select(id='list_sort'):
                        options = ['Status', 'Title', 'Year']
                        option('Title', value='title')
                        option('Year', value='year')
                        option('Status', value='status_sort')
                with div(id='key'):
                    span(cls='wanted')
                    span('Wanted')
                    span(cls='found')
                    span('Found')
                    span(cls='snatched')
                    span('Snatched')
                    span(cls='finished')
                    span('Finished')
                self.movie_list()

            with div(id='import'):
                with a(href=u'{}/import_library'.format(core.URL_BASE)):
                    i(cls='fa fa-hdd-o', id='import_library')
                    span('Import existing library.')

            div(id='overlay')
            div(id='status_pop_up')

        return doc.render()
Exemple #17
0
 def __init__(self, params=None):
     Header.__init__(self, params)
     self.name = "Accept-Encoding"
     self.max_types = 10  # Allow this many types
     self.valid_encoding_values = [
         "*", "aes128gcm", "br", "compress", "deflate", "exi", "gzip",
         "identity", "pack200-gzip", "x-compress", "x-gzip", "z-std",
         "bzip2", "lzma", "peerdist", "sdch", "xpress", "xz"
     ]
     self.value = self.generate_valid_value()
Exemple #18
0
 def _receive(self):
     try:
         data = self.udp_connection.recv(non_blocking=True)
         packet = data[0]
         header = Header.parse(packet[:Header.size()])
         pos = header.ftp_pos
         self.received_seqn = header.seqn
         self.queue[pos].state = RECEIVED if header.ack else FAILED
     except socket.error:
         pass
Exemple #19
0
 def _transmit_filename(self, filename):
     header = Header(self.seqn,
                     self.received_seqn,
                     0,
                     self.window_size,
                     Header.checksum(filename),
                     file_name=True)
     self.udp_connection.send_packet(header.formatted + filename, self.host,
                                     self.port)
     ack = self.udp_connection.recv()
Exemple #20
0
 def __init__(self, params=None):
     Header.__init__(self, params)
     self.name = "Accept-Control-Request-Headers"
     self.max_headers = 10
     self.headers = [
         "Accept", "Accept-Charset", "Accept-Datetime", "Accept-Encoding",
         "Accept-Language", "Access-Control-Request-Method",
         "Access-Control-Request-Headers"
     ]
     self.value = self.generate_valid_value()
Exemple #21
0
def submit(d):
    header = Header(d["method"], d["path"], d["httpversion"])
    for i in d['headers']:
        header.add_header(i['header_name'], i['header_value'])
    header.build_from_text()
    print(header.payload)
    s = Sender()
    r = Response()
    resp = r.input_text(s.send(d["protocol"], d["hostname"], header.payload))
    return resp
Exemple #22
0
 def __init__(self, params=None):
     Header.__init__(self, params)
     self.name = "Accept-Language"
     self.max_types = 10  # Allow this many types
     self.valid_prefix_values = [
         "ar", "ms", "zh", "lv", "sw", "uz", "fr", "de", "be", "tw", "pt",
         "gl", "oc", "hy", "az", "ba", "kk", "ky", "tk", "tt", "en", "sa",
         "eu", "sl", "sr", "nn", "eo", "bg", "rm", "kw", "pl", "ru", "el",
         "vo", "es", "ca"
     ]
     self.valid_subtag_values = [
         "aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as", "av", "ay",
         "az", "ba", "be", "bg", "bh", "bi", "bm", "bn", "bo", "br", "bs",
         "ca", "ce", "ch", "co", "cr", "cs", "cu", "cv", "cy", "da", "de",
         "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "fa", "ff",
         "fi", "fj", "fo", "fr", "fy", "ga", "gd", "gl", "gn", "gu", "gv",
         "ha", "he", "hi", "ho", "hr", "ht", "hu", "hy", "hz", "ia", "id",
         "ie", "ig", "ii", "ik", "in", "io", "is", "it", "iu", "iw", "ja",
         "ji", "jv", "jw", "ka", "kg", "ki", "kj", "kk", "kl", "km", "kn",
         "ko", "kr", "ks", "ku", "kv", "kw", "ky", "la", "lb", "lg", "li",
         "ln", "lo", "lt", "lu", "lv", "mg", "mh", "mi", "mk", "ml", "mn",
         "mo", "mr", "ms", "mt", "my", "na", "nb", "nd", "ne", "ng", "nl",
         "nn", "no", "nr", "nv", "ny", "oc", "oj", "om", "or", "os", "pa",
         "pi", "pl", "ps", "pt", "qu", "rm", "rn", "ro", "ru", "rw", "sa",
         "sc", "sd", "se", "sg", "sh", "si", "sk", "sl", "sm", "sn", "so",
         "sq", "sr", "ss", "st", "su", "sv", "sw", "ta", "te", "tg", "th",
         "ti", "tk", "tl", "tn", "to", "tr", "ts", "tt", "tw", "ty", "ug",
         "uk", "ur", "uz", "ve", "vi", "vo", "wa", "wo", "xh", "yi", "yo",
         "za", "zh", "zu", "AA", "AC", "AD", "AE", "AF", "AG", "AI", "AL",
         "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
         "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM",
         "BN", "BO", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BY", "BZ",
         "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
         "CO", "CP", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DD",
         "DE", "DG", "DJ", "DK", "DM", "DO", "DZ", "EA", "EC", "EE", "EG",
         "EH", "ER", "ES", "ET", "EU", "EZ", "FI", "FJ", "FK", "FM", "FO",
         "FR", "FX", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL",
         "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK",
         "HM", "HN", "HR", "HT", "HU", "IC", "ID", "IE", "IL", "IM", "IN",
         "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG",
         "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB",
         "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC",
         "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP",
         "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
         "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NT", "NU",
         "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN",
         "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW",
         "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL",
         "SM", "SN", "SO", "SR", "SS", "ST", "SU", "SV", "SX", "SY", "SZ",
         "TA", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN",
         "TO", "TP", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "UN",
         "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF",
         "WS", "YD", "YE", "YT", "YU", "ZA", "ZM", "ZR", "ZW", "ZZ"
     ]
     self.value = self.generate_valid_value()
Exemple #23
0
def generate_h(struct: Struct):
    header = Header()
    header.set_header_guard(
        "__{uname}_{proj}_DB_ENTITY_STRUCT_{name}_H".format(
            name=struct.name.upper(),
            proj=proj_name.upper(),
            uname=os.getlogin()))
    header.add_pragma("once")
    header.add_local_include("db/orm/entity.h")
    header.add_struct(struct)
    return str(header)
Exemple #24
0
    def place_call(self, sender_address):
        # get sender sock object
        dest = peers[sender_address]

        # send call request header
        header = Header(TYPE_CALL_REQUEST, self.MYIP)

        # send header
        s = header.serialize()
        dest.send(len(s))
        dest.send(s)
Exemple #25
0
def list_beacons():
    if "credentials" not in flask.session:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    credentials = client.OAuth2Credentials.from_json(flask.session["credentials"])

    if credentials.access_token_expired:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    else:
        header = Header(credentials.access_token)
        auth_request = session.get(config.LIST_BEACONS, headers=header.__str__())

        return render_template("beacons.jinja", beacons=json.loads(auth_request.content))
Exemple #26
0
class SongListScreen(Screen):

    def __init__(self):
        super(SongListScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('song list')
        layout = self.get_layout_manager()

        self.header = Header('All Songs')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.right_arrow = RightArrow()

        songs = Song.objects.filter(approved=True).order_by('title')
        self.songs = ScrollingText(map(BlinkingText, songs),
                                   items_on_screen=settings.SONG_LIST_ITEMS)
        self.songs.set_width(self.get_width() -
                             (self.left_arrow.get_width() +
                              self.right_arrow.get_width()))
        self.songs.set_height(self.get_height() - self.header.get_height())

        layout.add(self.songs,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_END)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)

    def on_second(self):
        """
        """
        pass

    def on_press(self, actor, event):
        """
        """
        self.songs.on_press(actor, event)
        if event.keyval == clutter.keysyms.Left:
            self.get_parent().remove_screen(self)
        elif event.keyval == clutter.keysyms.Right:
            self.get_parent().new_screen(
                SongDetailScreen(self.songs.selected.obj)
                )
Exemple #27
0
    def send(self, msg, msg_code, dest):
        header = Header(msg_code, self.MYIP)

        # send header
        s = header.serialize()
        dest.send(len(s))
        dest.send(s)

        # send msg
        msg = str(msg)
        dest.send(len(msg))
        dest.send(msg)
Exemple #28
0
    def main(self):
        self.header = Header('PY03')

        for ext in ['hdl', 'asm', 'vm', 'jack', 'py']:
            ext_file_set = FileSet('test', ext)

            while ext_file_set.hasMoreFiles():
                filename = ext_file_set.nextFile()
                basename = ext_file_set.baseName()

                self.create_bak_file(basename, filename)
                self.add_header(filename)
Exemple #29
0
class ArtistListScreen(Screen):

    def __init__(self):
        super(ArtistListScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('artist list')
        layout = self.get_layout_manager()

        self.header = Header('All Artists')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.right_arrow = RightArrow()

        # Filter to all artists that have songs.
        artists = Artist.objects.filter(song__isnull=False
                                        ).distinct().order_by('name')
        artists = artists.filter(song__approved=True
                                 ).distinct().order_by('name')
        self.artists = ScrollingText(map(BlinkingText, artists),
                                     items_on_screen=settings.ARTIST_LIST_ITEMS)
        self.artists.set_width(self.get_width() -
                               (self.left_arrow.get_width() +
                                self.right_arrow.get_width()))
        self.artists.set_height(self.get_height() - self.header.get_height())

        layout.add(self.artists,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_END)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)

    def on_press(self, actor, event):
        """
        """
        self.artists.on_press(actor, event)
        if event.keyval == clutter.keysyms.Left:
            self.get_parent().remove_screen(self)
        elif event.keyval == clutter.keysyms.Right:
            self.get_parent().new_screen(
                ArtistDetailScreen(self.artists.selected.obj)
                )
Exemple #30
0
    def default(self):
        doc = dominate.document(title='Watcher')
        doc.attributes['lang'] = 'en'

        with doc.head:
            Head.insert()
            link(rel='stylesheet',
                 href=core.URL_BASE + '/static/css/import_library.css?v=04.04')
            link(rel='stylesheet',
                 href=core.URL_BASE +
                 '/static/css/{}import_library.css?v=04.04'.format(
                     core.CONFIG['Server']['theme']))
            script(type='text/javascript',
                   src=core.URL_BASE +
                   '/static/js/import_library/main.js?v=04.07')

        with doc:
            Header.insert_header(current=None)
            with div(id='content'):
                h1('Import Library')
                with div(id='import_sources'):
                    with div():
                        with a(href=core.URL_BASE +
                               '/import_library/couchpotato'):
                            img(src=core.URL_BASE +
                                '/static/images/couchpotato.png',
                                alt='CouchPotato',
                                cls='import_source_icon')
                            br()
                            span('CouchPotato')
                    with div():
                        with a(href=core.URL_BASE + '/import_library/kodi'):
                            img(src=core.URL_BASE + '/static/images/kodi.png',
                                alt='Kodi',
                                cls='import_source_icon')
                            br()
                            span('Kodi')
                    with div():
                        with a(href=core.URL_BASE + '/import_library/plex'):
                            img(src=core.URL_BASE + '/static/images/plex.png',
                                alt='Plex',
                                cls='import_source_icon')
                            br()
                            span('Plex')
                    with div():
                        with a(href=core.URL_BASE +
                               '/import_library/directory'):
                            i(cls='fa fa-folder import_source_icon')
                            br()
                            span('Directory')
        return doc.render()
Exemple #31
0
    def __init__(self, code, filename, seq_num, s_port, d_port):

        if code == 1:
            Header.__init__(self, seq_num, s_port, d_port, 0, syn=True)
        else:
            Header.__init__(self,
                            seq_num,
                            s_port,
                            d_port,
                            0,
                            write=True,
                            syn=True)

        self.data = bitstring.Bits(filename.encode('utf-8'))
Exemple #32
0
 def receive_loop(self):
     msg_received = False
     while msg_received is False:
         data = self.udp_server.recv()
         packet = data[0]
         host = data[1][0]
         header = Header.parse(packet[:Header.size()])
         data = packet[Header.size():]
         self.data_len = len(data)
         if header.syn:
             self._handshake(header, host)
         else:
             msg_received = self._check_packet(data, header, host)
     msg = [x for x in msg_received if x is not None]
     return ''.join(msg)
Exemple #33
0
def beacon_unregistration_status():
    if "credentials" not in flask.session:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    credentials = client.OAuth2Credentials.from_json(flask.session["credentials"])

    if credentials.access_token_expired:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    else:
        beacon_name = request.form.get("name")
        header = Header(credentials.access_token)
        url = config.BEACON + beacon_name + config.DEACTIVATE
        response = requests.post(url, headers=header.__str__())
        status = config.ERROR if response.status_code is 400 else config.SUCCESS

        return render_template("unregistration_status.jinja", status=status)
Exemple #34
0
    def _parse(self, value):
        firstline, headers, body = value.split('\r\n\r\n', 1)
        a, b, c = firstline.split('', 2)
        try:  # try as response
            self.response, self.responsetext, self.protocol = int(
                b), c, a  # throws error if b is not int.
        except:  # probably a request
            self.method, self.uri, self.protocol = a, URI(b), c

        for h in headers.split('\r\n'):
            if h.startswith(r'[ \t]'):
                pass
                # parse the header line
                # str.21
                try:
                    name, values = Header.createHeaders(h)
                    if name not in self:  # doesn't already exist
                        self[name] = values if len(values) > 1 else values[0]
                    elif name not in Message._single:  # valid multiple-instance header
                        if not isinstance(self[name], list):
                            self[name] = self[name]
                        self[name] += values
                except:
                    continue

        bodyLen = int(
            self['Content-Length'].value) if 'Content-Length' in self else 0
        if body:
            self.body = body
        if self.body != None and bodyLen != len(body):
            raise ValueError('Invalid content-length %d!=%d')
        for h in ['To', 'From', 'CSeq', 'Call-ID']:
            if h not in self:
                raise ValueError('Mandatory header %s missing')
Exemple #35
0
    def test_footer_links(self):
        links = (
            # MEN
            'View All Men',
            #'New Arrivals',
            'Shirts',
            'Tees, Knits and Polos',
            #'Pants & Denim',
            'Blazers',
            # WOMEN
        )

        head = (
            'Men',
            # 'New Arrivals',
            'Shirts',
            'Tees, Knits and Polos',
            # 'Pants & Denim',
            'Blazers',
        )

        LoginPage(self.browser).open()
        for link, heads in zip(links, head):
            Link(self.browser, 'Men').hover()
            Link(self.browser, link).click()
            self.assertTrue(Header(self.browser, heads).is_visible)
Exemple #36
0
    def __init__(self):
        HtmlPage.__init__(self, 'VReports Index')
        self.header = Header(self.title)

        self.style_sheets.extend([
            'css/vreports.css',
            ])
Exemple #37
0
    def _parse_file_headers(self, data):
        headers = list()
        d_idx = 0

        for h_idx in range(6):
            h_prefix = data[d_idx]
            d_idx += 1

            # first byte is number of values
            cnt = ord(h_prefix)

            f_header = Header(h_idx, h_prefix, "")
            for v_idx in range(cnt):
                v_prefix = data[d_idx]
                d_idx += 1

                # first byte is length of value
                length = ord(v_prefix)
                v_data = data[d_idx:d_idx+length]
                d_idx += length

                h_value = HeaderValue(v_prefix, "", v_data)
                f_header.values.append(h_value)

            headers.append(f_header)

        return headers, d_idx
Exemple #38
0
    def __init__(self):
        self.root = Tk()
        self.root.title("IRCTC TRAIN")
        self.root.minsize(800, 600)
        self.root.maxsize(800, 600)
        self.root.configure(background="#222")
        # # self.l = Label(self.root,text="LABEL ROOT").pack()
        # Trainroute(self.root)
        # # self.f1.pack()
        self.hdr = Header(self.root)
        self.hdr.pack(side=TOP)

        self.bdy = Body(self.root)
        self.bdy.pack(side=TOP)

        self.hdr.send_body(self.bdy)
Exemple #39
0
    def __init__(self):
        super(SongListScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('song list')
        layout = self.get_layout_manager()

        self.header = Header('All Songs')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.right_arrow = RightArrow()

        songs = Song.objects.filter(approved=True).order_by('title')
        self.songs = ScrollingText(map(BlinkingText, songs),
                                   items_on_screen=settings.SONG_LIST_ITEMS)
        self.songs.set_width(self.get_width() -
                             (self.left_arrow.get_width() +
                              self.right_arrow.get_width()))
        self.songs.set_height(self.get_height() - self.header.get_height())

        layout.add(self.songs,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_END)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)
Exemple #40
0
 def _receivedResponse(self, r, uri):
     '''Received a SIP response r (Message) from the uri (URI).'''
     if not r.Via: raise ValueError('No Via header in received response')
     try:
         branch = r.first('Via').branch
     except AttributeError:
         branch = ''
     method = r.CSeq.method
     t = self.findTransaction(Transaction.createId(branch, method))
     if not t:
         if method == 'INVITE' and r.is2xx:  # success of INVITE
             d = self.findDialog(r)
             if not d:  # no dialog or transaction for success response of INVITE.
                 raise ValueError(
                     'No transaction or dialog for 2xx of INVITE')
             else:
                 d.receivedResponse(None, r)
         else:
             if _debug:
                 print('transaction id %r not found' %
                       (Transaction.createId(branch, method), )
                       )  # do not print the full transactions table
             if method == 'INVITE' and r.isfinal:  # final failure response for INVITE, send ACK to same transport
                 # TODO: check if this following is as per the standard
                 m = Message.createRequest('ACK', str(r.To.value.uri))
                 m['Call-ID'], m.From, m.To, m.Via, m.CSeq = r[
                     'Call-ID'], r.From, r.To, r.first('Via'), Header(
                         str(r.CSeq.number) + ' ACK', 'CSeq')
                 self.send(m, uri.hostPort)
             raise ValueError('No transaction for response')
     else:
         t.receivedResponse(r)
Exemple #41
0
class Http(object):
    def __init__(self):
        self.header = Header('GET', '/', 'HTTP/1.1')
        self.body = Body()

    def build_header(self):
        self.header = Header('GET', '/', 'HTTP/1.1')
        self.header.add_header('Host', 'www.mbsd.jp')
        #self.header.add_header('Accept-Encoding', 'gzip, deflate')
        self.header.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0')
        self.header.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
        self.header.add_header('Connection', 'close')
        self.header.build_from_text()
        #print(self.header.payload)
    
    def get_header(self):
        return self.header.payload
Exemple #42
0
 def build_header(self):
     self.header = Header('GET', '/', 'HTTP/1.1')
     self.header.add_header('Host', 'www.mbsd.jp')
     #self.header.add_header('Accept-Encoding', 'gzip, deflate')
     self.header.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0')
     self.header.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
     self.header.add_header('Connection', 'close')
     self.header.build_from_text()
Exemple #43
0
class NoData(HtmlPage):

    def __init__(self):
        HtmlPage.__init__(self, 'VReports Index')
        self.header = Header(self.title)

        self.style_sheets.extend([
            'css/vreports.css',
            ])

    def getHtmlContent(self):
        '''Return the entire HTML content of the page.
           (Without HTTP Header)
        '''
        return div(self.header.getHeader() + \
                       self.body())
    def body(self):
        href='https://github.com/dlink/vreports/blob/master/README.md'
        readme_link = a('README', href=href)

        href='https://github.com/dlink/vreports'
        source_link = a(href, href=href)


        text = [h1('Welcome to VRreports'),
                'No report config directory specified. You pass report name ' \
                    'in as a parameter like this: "vreports?r=books".',
                'See %s' % readme_link,
                'Source code available: %s' % source_link,
                h2('Here are some Examples'),
                self.examples()]

        style = 'margin: 50px 300px;'

        return div(big('\n'.join(map(p, text))),
                   style=style
                   )

    def examples(self):
        examples_dir = os.path.dirname(os.path.realpath(__file__))\
            .replace('/web', '/examples')

        examples = []
        for d in os.listdir(examples_dir):
            # check see it is a directory with a main.yaml in it:
            try:
                if 'main.yaml' in  os.listdir('%s/%s' % (examples_dir, d)):
                    link = '/%s/?r=%s' % (self.urlbase, d)
                    data = a(d, href=link)
                    examples.append(data)
            except Exception, e:
                continue
            
        return div(p('\n'.join(map(li, examples))))
Exemple #44
0
    def __init__(self, artist):
        super(ArtistDetailScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('artist detail %s' % artist.name)
        layout = self.get_layout_manager()

        photo = artist.random_photo()
        self.background = BackgroundImages(artist)
        #self.background = clutter.Texture(settings.MEDIA_ROOT + "/" + photo.photo.name)
        self.background.set_opacity(30)
        layout.add(self.background,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_END)
        self.background.lower_bottom()

        self.header = Header('Artist Details')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()

        songs = artist.song_set.filter(approved=True).order_by('title')
        self.songs = None
        if len(songs) > 0:
            self.right_arrow = RightArrow()
            self.songs = ScrollingText(
                map(BlinkingText, songs),
                items_on_screen=settings.SONG_LIST_ITEMS
                )
            self.songs.set_width(self.get_width() -
                                 (self.left_arrow.get_width() +
                                  self.right_arrow.get_width()))
            self.songs.set_height(self.get_height() - self.header.get_height())
            layout.add(self.songs,
                       clutter.BIN_ALIGNMENT_CENTER,
                       clutter.BIN_ALIGNMENT_END)
            layout.add(self.right_arrow,
                       clutter.BIN_ALIGNMENT_END,
                       clutter.BIN_ALIGNMENT_CENTER)

        else:
            text = clutter.Text('Router Bold 70', 'No songs available.')
            text.set_color(clutter.Color(200, 200, 200, 0xff))
            layout.add(text,
                       clutter.BIN_ALIGNMENT_CENTER,
                       clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)
Exemple #45
0
  def main(self):
    self.header = Header('PY03')

    for ext in ['hdl', 'asm', 'vm', 'jack', 'py']:
      ext_file_set = FileSet('test', ext)

      while ext_file_set.hasMoreFiles():
        filename = ext_file_set.nextFile()
        basename = ext_file_set.baseName()

        self.create_bak_file(basename, filename)
        self.add_header(filename)
Exemple #46
0
class Main:
  def main(self):
    self.header = Header('PY03')

    for ext in ['hdl', 'asm', 'vm', 'jack', 'py']:
      ext_file_set = FileSet('test', ext)

      while ext_file_set.hasMoreFiles():
        filename = ext_file_set.nextFile()
        basename = ext_file_set.baseName()

        self.create_bak_file(basename, filename)
        self.add_header(filename)

  def create_bak_file(self, basename, filename):
    with open(os.path.join(basename, filename)) as file:
      print file.read().splitlines()[0]


  def add_header(self, filename):
    print self.header.gen(filename)
Exemple #47
0
class BasePage(HtmlPage):
    '''Base Page for VReports'''

    def __init__(self, report_name='Base Report'):
        HtmlPage.__init__(self, report_name)
        self.report_name = report_name

        self.menu = Menu()
        self.header = Header(self.title)

        progpath = os.path.dirname(sys.argv[0])
        def versionize(file):
            timestamp = os.path.getmtime('%s/../web/%s' % (progpath, file))
            return '%s?v=%s' % (file, timestamp)

        self.javascript_src = [
            "//code.jquery.com/jquery-1.10.2.js",
            "//code.jquery.com/ui/1.11.1/jquery-ui.js",
            versionize('js/vreports.js'),
            ]
        self.style_sheets.extend(
            ['http://code.jquery.com/ui/1.10.2/themes/smoothness/' \
                 'jquery-ui.css',
             versionize('css/vreports.css'),
             ])

    def process(self):
        HtmlPage.process(self)

    def getHtmlContent(self):
        '''Return the entire HTML content of the page.
           (Without HTTP Header)
        '''
        return div(
            self.header.getHeader() + \
            div(
              self.menu.getMenu(self.report_name) + \
              self.menu.getLeftNav() + \
              span(
                self.getReportDesc() + \
                self.getReport(),
                id='report'
              ),
              id='content-container'),
            id='page-container')

    def getReportDesc(self):
        report_name = span(self.report_name, id='report-name')
        return div(report_name, id='report-header')

    def getReport(self):
        raise Exception('You must override getReport()')
Exemple #48
0
    def __init__(self, process_map, extra_header):
        self.lock = True
        self.logger = logging.getLogger(__name__)
        conf = Config()
        root = conf.config_directory["ROOT"]

        requested_file = root + process_map["FILE"]
        self.status = self.__get_status(requested_file)
        self.header = Header(self.status)
        self.process_map = process_map
        self.body = ""
        for key, value in extra_header.iteritems():
            self.header.set_extra(key, value)
Exemple #49
0
    def __init__(self, song):
        super(SongDetailScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        # Immediately store song information
        self.song = song
        self.set_name('song detail %s' % self.song.title)
        layout = self.get_layout_manager()

        self.header = Header('Song Details')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.play = PlaySymbol()

        self.box = clutter.Box(clutter.BoxLayout())
        box_layout = self.box.get_layout_manager()
        box_layout.set_vertical(True)
        box_layout.set_spacing(20)
        text = clutter.Text(settings.SONG_TITLE_FONT, self.song.title)
        text.set_line_alignment(ALIGN_CENTER)
        text.set_line_wrap(True)
        text.set_color(clutter.Color(230, 230, 230, 0xff))
        self.box.add(text)
        text = clutter.Text(
            settings.SONG_ARTIST_FONT, "by %s" % self.song.artist.name
            )
        text.set_line_alignment(ALIGN_CENTER)
        text.set_line_wrap(True)
        text.set_color(clutter.Color(210, 210, 210, 0xff))
        self.box.add(text)
        self.box.set_width(self.get_width() -
                           (self.left_arrow.get_width() +
                            self.play.get_width()))


        layout.add(self.box,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_CENTER,)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.play,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)
Exemple #50
0
 def loadTargetHeaders(self):
     """Load the target headers and populate the self.headers dictionary"""
     self.headers = {}
     # Get paths to built-in targets
     paths = [(t, self.builtinTargetsPath + t + os.sep) for t in os.listdir(self.builtinTargetsPath)]
     if self.externalTargetsPath:
         # Get paths to external targets
         paths += [(t, self.externalTargetsPath + t + os.sep) for t in os.listdir(self.externalTargetsPath)]
     # Look in subdirectories only for the header file
     for path in paths:
         try:
             if not os.path.isfile(path[1]) and os.access(path[1] + 'header.html', os.R_OK):
                 header = Header.factory(*path, builtinPath = self.builtinTargetsPath)
                 self.headers[header.id] = header
         except:
             pass
Exemple #51
0
def beacon_registration_status():
    if "credentials" not in flask.session:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    credentials = client.OAuth2Credentials.from_json(flask.session["credentials"])

    if credentials.access_token_expired:
        return flask.redirect(flask.url_for("portal.oauth2callback"))
    else:
        beacon = Beacon(request.form.get("advid"))
        beacon.status = request.form.get("status")
        beacon.beacon_type = request.form.get("type")

        request_body = beacon.registration_request_body()
        header = Header(credentials.access_token)
        response = requests.post(config.REGISTER_BEACONS, data=json.dumps(request_body), headers=header.__str__())

        return render_template("registration_status.jinja", status=json.loads(response.content))
Exemple #52
0
    def __init__(self, config={}):
        QAbstractScrollArea.__init__(self)
        self.setFocusPolicy(Qt.NoFocus)

        self._ui_model = None
        self._updater = None

        # Widgets
        self.setViewport(View())

        self._corner = QWidget()
        self._corner.setStyleSheet('QWidget { background-color: #000 }')

        self._ruler = Ruler()
        self._header = Header()

        # Config
        self._config = None
        self._set_config(config)

        # Layout
        g = QGridLayout()
        g.setSpacing(0)
        g.setMargin(0)
        g.addWidget(self._corner, 0, 0)
        g.addWidget(self._ruler, 1, 0)
        g.addWidget(self._header, 0, 1)
        g.addWidget(self.viewport(), 1, 1)
        self.setLayout(g)

        self.viewport().setFocusProxy(None)

        self.setVerticalScrollBar(LongScrollBar())
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        QObject.connect(
                self.viewport(),
                SIGNAL('heightChanged()'),
                self._update_scrollbars)
        QObject.connect(
                self.viewport(),
                SIGNAL('followCursor(QString, int)'),
                self._follow_cursor)
Exemple #53
0
    def __init__(self, path):

        with open(path, "rb") as f:
            self.src = f.read()

        self.header = Header(self.src)
        
        self.offsetData = 12 + 16 * self.header.numTables

        
        self.tables = OrderedDict()
        for i in range(self.header.numTables):
            idx = 12 + 16 * i
            t = Table(self.src, idx)
            self.tables[t.tag] = t
            
            if t.tag == "loca":
                print binascii.b2a_hex(t.data[-3])
                

        # sort tables with offset
#        self.tables.sort(key=lambda x: x.offset)

        # get global properties
        head = self.tables["head"]
        self.checkSumAdjustment = struct.unpack("!L", head.data[8:12])[0]
        head.data = head.data[:8] + "\0\0\0\0" + head.data[12:]
        
        # byte length of loca values
        loca = self.tables["loca"]
        if (ord(head.data[-1]) & 0xFF) >> 4 == 0:
            loca_format = "H"
            loca_size = 2
        else:
            loca_format = "L"
            loca_size = 4

        self.numGlyphs = struct.unpack("!H", self.tables["maxp"].data[4:6])[0]

        print "loca_format: ", loca_format
        print "len(self.loca.data): ", len(loca.data)
        print "numGlyphs: ", self.numGlyphs
        glyf_offsets = struct.unpack("!" + str(self.numGlyphs + 1) + loca_format, loca.data)
        print "len(glyf_offsets): ", len(glyf_offsets)
Exemple #54
0
    def __init__(self, report_name='Base Report'):
        HtmlPage.__init__(self, report_name)
        self.report_name = report_name

        self.menu = Menu()
        self.header = Header(self.title)

        progpath = os.path.dirname(sys.argv[0])
        def versionize(file):
            timestamp = os.path.getmtime('%s/../web/%s' % (progpath, file))
            return '%s?v=%s' % (file, timestamp)

        self.javascript_src = [
            "//code.jquery.com/jquery-1.10.2.js",
            "//code.jquery.com/ui/1.11.1/jquery-ui.js",
            versionize('js/vreports.js'),
            ]
        self.style_sheets.extend(
            ['http://code.jquery.com/ui/1.10.2/themes/smoothness/' \
                 'jquery-ui.css',
             versionize('css/vreports.css'),
             ])
Exemple #55
0
    def __init__(self):
        super(ArtistListScreen, self).__init__(clutter.BinLayout(
            clutter.BIN_ALIGNMENT_CENTER,
            clutter.BIN_ALIGNMENT_CENTER))
        self.set_name('artist list')
        layout = self.get_layout_manager()

        self.header = Header('All Artists')
        self.header.set_width(self.get_width())
        layout.add(self.header,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_START)

        self.left_arrow = LeftArrow()
        self.right_arrow = RightArrow()

        # Filter to all artists that have songs.
        artists = Artist.objects.filter(song__isnull=False
                                        ).distinct().order_by('name')
        artists = artists.filter(song__approved=True
                                 ).distinct().order_by('name')
        self.artists = ScrollingText(map(BlinkingText, artists),
                                     items_on_screen=settings.ARTIST_LIST_ITEMS)
        self.artists.set_width(self.get_width() -
                               (self.left_arrow.get_width() +
                                self.right_arrow.get_width()))
        self.artists.set_height(self.get_height() - self.header.get_height())

        layout.add(self.artists,
                   clutter.BIN_ALIGNMENT_CENTER,
                   clutter.BIN_ALIGNMENT_END)

        layout.add(self.left_arrow,
                   clutter.BIN_ALIGNMENT_START,
                   clutter.BIN_ALIGNMENT_CENTER)

        layout.add(self.right_arrow,
                   clutter.BIN_ALIGNMENT_END,
                   clutter.BIN_ALIGNMENT_CENTER)
    def __init__(self, parent, requester, numdays=7):
        super(WeekView, self).__init__(parent, requester)
        super(Gtk.VBox, self).__init__()

        self.numdays = numdays
        self.min_day_width = 60
        self.grid = Grid(1, self.numdays)
        numweeks = int(self.numdays/7)
        self.week = WeekSpan(numweeks)

        # Header
        self.header = Header(self.numdays)
        self.header.set_size_request(-1, 35)
        self.pack_start(self.header, False, False, 0)

        # Scrolled Window
        self.scroll = Gtk.ScrolledWindow(None, None)
        self.scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        self.scroll.add_events(Gdk.EventMask.SCROLL_MASK)
        self.scroll.connect("scroll-event", self.on_scroll)
        self.pack_start(self.scroll, True, True, 0)
        self.vadjustment = self.scroll.get_vadjustment()
        self.vadjustment.connect('changed', self.on_vadjustment_changed)

        # AllDayTasks widget
        self.all_day_tasks = AllDayTasks(self, cols=self.numdays)
        self.scroll.add_with_viewport(self.all_day_tasks)

        # drag-and-drop support
        self.drag_offset = None
        self.drag_action = None
        self.is_dragging = False

        # handle the AllDayTasks DnD events
        self.all_day_tasks.connect("button-press-event", self.dnd_start)
        self.all_day_tasks.connect("motion-notify-event", self.motion_notify)
        self.all_day_tasks.connect("button-release-event", self.dnd_stop)

        self.connect("size-allocate", self.on_size_allocate)
    def __init__(self, parent, requester, numdays=7):
        super(MonthView, self).__init__(parent, requester)
        super(Gtk.VBox, self).__init__()

        self.numdays = numdays
        self.min_day_width = 60
        self.min_week_height = 80
        self.font_size = 7
        self.fixed = None

        # Header
        self.header = Header(self.numdays)
        self.header.set_size_request(-1, 35)
        self.pack_start(self.header, False, False, 0)

        # Scrolled Window
        self.scroll = Gtk.ScrolledWindow(None, None)
        self.scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
        self.scroll.add_events(Gdk.EventMask.SCROLL_MASK)
        self.scroll.connect("scroll-event", self.on_scroll)
        self.pack_start(self.scroll, True, True, 0)

        # AllDayTasks widget
        self.all_day_tasks = AllDayTasks(self, cols=self.numdays)
        # self.pack_start(self.all_day_tasks, True, True, 0)
        self.scroll.add_with_viewport(self.all_day_tasks)

        # drag-and-drop support
        self.drag_offset = None
        self.drag_action = None
        self.is_dragging = False

        # handle the AllDayTasks DnD events
        self.all_day_tasks.connect("button-press-event", self.dnd_start)
        self.all_day_tasks.connect("motion-notify-event", self.motion_notify)
        self.all_day_tasks.connect("button-release-event", self.dnd_stop)
Exemple #58
0
 def testSetData(self):
     header1 = NetHeader()
     header2 = NetHeader()
     #
     header1.setData(32567, 9875235)
     buffer_bytes = bytearray(100)
     buffer_bytes[:] = header1.getBytes()
     #
     header2.getBytes()[:] = buffer_bytes
     header2.unpackBuffer()
     #
     self.assertEqual(header1.getMessageSizeB(),
                      header2.getMessageSizeB(),
                      "MessageSize do not match")
     #
     self.assertEqual(header1.getRequestId(),
                      header2.getRequestId(),
                      "RequestId do not match")
Exemple #59
0
class TTF:

    def __init__(self, path):

        with open(path, "rb") as f:
            self.src = f.read()

        self.header = Header(self.src)
        
        self.offsetData = 12 + 16 * self.header.numTables

        
        self.tables = OrderedDict()
        for i in range(self.header.numTables):
            idx = 12 + 16 * i
            t = Table(self.src, idx)
            self.tables[t.tag] = t
            
            if t.tag == "loca":
                print binascii.b2a_hex(t.data[-3])
                

        # sort tables with offset
#        self.tables.sort(key=lambda x: x.offset)

        # get global properties
        head = self.tables["head"]
        self.checkSumAdjustment = struct.unpack("!L", head.data[8:12])[0]
        head.data = head.data[:8] + "\0\0\0\0" + head.data[12:]
        
        # byte length of loca values
        loca = self.tables["loca"]
        if (ord(head.data[-1]) & 0xFF) >> 4 == 0:
            loca_format = "H"
            loca_size = 2
        else:
            loca_format = "L"
            loca_size = 4

        self.numGlyphs = struct.unpack("!H", self.tables["maxp"].data[4:6])[0]

        print "loca_format: ", loca_format
        print "len(self.loca.data): ", len(loca.data)
        print "numGlyphs: ", self.numGlyphs
        glyf_offsets = struct.unpack("!" + str(self.numGlyphs + 1) + loca_format, loca.data)
        print "len(glyf_offsets): ", len(glyf_offsets)

        
    # check checksum for all table
    def checkTables(self):
        for k,t in self.tables.items():
            tmp = t.data
            if k == "head":
                tmp = tmp[:8] + "\0\0\0\0" + tmp[12:]
            if t.checkSum == calcSum(tmp):
                print k, ": ok"
            else:
                print k, ": ng"

        

    # dump table for debug
    def dumpTable(self, name):
        if not(name in self.tables):
            return
        with open(name + "_data", "wb") as f:
            f.write(self.tables[k].data)
                

            
    def outputTTF(self):

        ttf_header = ""
        ttf_table = ""
        ttf_data = ""        

        # make sure tables are sorted by offset
#        self.tables.sort(key=lambda x: x.offset)

        # compute offsets for data
        offset_new = 0

        # offset for ttf_data = len(ttf_header + ttf_table)
        offset_data = 12 + (16 * self.header.numTables)

        # for checkSumAdj
        offset_csa = 0
        totalSum = 0

        
        # FIRST: generate ttf_data, and calculate offset
        offsets = {}

        for k, t in sorted(self.tables.items(), key=lambda x: x[1].offset):
            offsets[k] = offset_new
            ttf_data += t.data

            # insert paddings
            if t.length % 4 != 0:
                ttf_data += "\0" * (4 - (t.length % 4))

            # check the data with src
            left = offset_data + offset_new
            if (self.src[left : left + t.length] == t.data and 
                ttf_data[offset_new : offset_new + t.length] == t.data):
                print k, ": same"
            else:
                print k, ": different"

            # for checkSumAdjustment.
            totalSum += t.checkSum
                
            # update offset, including paddings
            offset_new += (t.length + 3) & 0xFFFFFFFC

            
        
        # SECOND: generate ttf_table
        for k,t in self.tables.items():
            t.offset = offsets[k] + offset_data
            ttf_table += t.outputTTF()


        # THIRD: generate ttf_header
        ttf_header = self.header.outputTTF()


        # now we gotta calculate checkSumAdjustment in head table.
        offset_csa = offsets["head"] + 8
        if ttf_data[offset_csa:offset_csa+4] == "\0\0\0\0":
            print "csa is \\0\\0\\0\\0, it's ok!"

        num_int32 = (12 + (16 * self.header.numTables)) / 4
        totalSum += sum(struct.unpack("!" + str(num_int32) + "L", ttf_header + ttf_table))

        csa_old = self.src[offset_data + offset_csa : offset_data + offset_csa + 4]
        csa = (0xB1B0AFBA - totalSum) & 0xFFFFFFFF
        print "old csa: ", binascii.b2a_hex(csa_old)
        print "new csa: ", binascii.b2a_hex(struct.pack("!L", csa))
        
        ttf_data = ttf_data[:offset_csa] + struct.pack("!L", csa) + ttf_data[(offset_csa+4):]


        head = self.tables["head"]
        left = head.offset + offset_data
        if self.src[left : left + head.length] == head.data:
            print "head: same"
        else:
            print "head: different"
            

        # check values with self.src
        if ttf_header == self.src[:12]:
            print "header: same"
        else:
            print "header: different"

        if ttf_table == self.src[12:12+(16*self.header.numTables)]:
            print "table: same"
        else:
            print "table: different"

        if ttf_data == self.src[12+(16*self.header.numTables):]:
            print "data: same"
        else:
            print "data: different"
            
        s = (ttf_header + ttf_table + ttf_data)        
        if s == self.src:
            print "all same!!!"
        else:
            print "all differ..."
        
        return s


    def glitch(self):
        pass