예제 #1
0
 def __init__(self):
     '''Initialize the super class
     '''
     super().__init__()
     self.inputFileHandler = FileHandler()
     self.outputFileHandler = FileHandler()
     self.timer = QTimer(self)
     self.timer.timeout.connect(self.updateProgressBar)
     self.threadpool = QThreadPool()
     self.failed = False
     print("Multithreading with maximum %d threads" %
           self.threadpool.maxThreadCount())
예제 #2
0
 def __init__(self, averages, ledger, tickers, state):
     self.averages = FileHandler(averages)
     self.ledger = FileHandler(ledger)
     self.tickers = FileHandler(tickers)
     self.api_private_key = base64.b64decode(API_PRIVATE_KEY)
     self.api_public_key = API_PUBLIC_KEY
     self.session = requests.session()
     self.domain = "https://api.kraken.com"
     self.private_path = "/0/private/"
     self.public_path = "/0/public/"
     self.state = state
     self.__init_files()
예제 #3
0
    def __init__(self, oSHIT=None):
        self.oSHIT = oSHIT
        self.config = oSHIT.config
        self.logger = oSHIT.logger

        # make filehandler
        self.file = FileHandler(oSHIT=self.oSHIT)
예제 #4
0
    def look_up_temperature_in_lut(self, data, temperature_index=4, filename="../LMT85_LookUpTableCSV.csv"):
        """Attempts to find a matching value in the LUT. If no matching value is found it chooses whichever value is
        closest

        This function changes the values in the object that is passed to it.
        """
        fh = FileHandler()
        lut_content = fh.readCSV(filename, 'int', False)

        # print(self.search_2d_temperature_tree(lut_content, 1, 716))
        last_length = len(data[0])
        for index, value in enumerate(data):
            if last_length != len(value) or temperature_index > len(value) + 1:
                raise IndexError("Columns are not the same across all rows")
            # Find nearest voltage level
            if isinstance(value, float):
                value = round(value)

            temp = self.search_2d_temperature_tree(lut_content, 1, int(value[temperature_index]))
            # print(f'{lut_content[temp+50][1] - int(value[temperature_index])}')
            if abs(lut_content[temp+50][1] - int(value[temperature_index]) > 5):
                print(f'Searched for: {value[temperature_index]}, Return value: {temp}')
            data[index][temperature_index] = temp

        return data
예제 #5
0
def main():

    # Read in data and extract data arrays
    #logging.info("Reading input files.")

    dbh = DBHandler(options.db_config_filename, options.db_config_name)
    ssh = SmartMetHandler(options.smartmet_config_filename,
                          options.smartmet_config_name,
                          sleep_time=options.requests_throttle_time)
    fh = FileHandler(s3_bucket='fmi-sasse-classification-dataset')
    tracker = Tracker(dbh, ssh)

    starttime = dt.datetime.strptime(options.starttime, "%Y-%m-%dT%H:%M:%S")
    endtime = dt.datetime.strptime(options.endtime, "%Y-%m-%dT%H:%M:%S")

    d = starttime
    ymd = '{}{}{}'.format(d.year, d.month, d.day)
    while d <= endtime:
        logging.info('Processing time: {}'.format(d))
        tracker.run(d)
        d += timedelta(hours=1)
        if ymd != '{}{}{}'.format(d.year, d.month, d.day):
            save_dataset(tracker, d, fh=fh, db=dbh)
        ymd = '{}{}{}'.format(d.year, d.month, d.day)

    #if tracker.dataset is not None and len(tracker.dataset) > 0:
    save_dataset(tracker, d, fh=fh, db=dbh)
예제 #6
0
    def run(self):
        # all file handling
        file = FileHandler(self.path, self.img_path)
        user = ''

        # entry point set
        if len(self.users) > 0:
            link, user = self.getlink()
        else:
            link = START_LINK

        while True:
            self.driver.get(link)

            # нужно доскролливать каждого пользователя до конца
            self.scroll_down(times=20)

            collected_data = self.collect_pictures(self.quality)
            try:
                file.write(collected_data, user=user)
            except Exception as e:
                print(e)
                self.serialize()
                break

            links = self.collect_comment_pages()
            for link in links:
                names = self.extract_names(link)
                self.users |= set(names)

            link, user = self.getlink()
    def __init__(self, task_manager=None):
        self.filehandler = FileHandler(config.project_file)
        self.project_list = self.filehandler.parse_file()
        self.current_project_index = None

        # It is possible for the project manager to perform some basic function
        # without a task manager, but it's not expected most of the time
        self.task_manager = task_manager
예제 #8
0
 def processMessage(self,message,FILE,timeout=350):
     FILE['queue_url'] = self.createUserQueue(FILE)
     DFH = FileHandler(FILE)
     DFH.prepare()
     #for x in range(0,3):
         #try:
          #   message.change_visibility(VisibilityTimeout=timeout)
     DFH.process()
예제 #9
0
 def load(self, filename):
     """
     Set the file that will create the filehandler object
     """
     if path.exists(filename):
         self.filehandler = FileHandler(filename)
         self.filehandler.set_file_type()
         return True
     else:
         return False
예제 #10
0
def main():

    fh = FileHandler()  #s3_bucket='fmi-sasse-classification-dataset')
    viz = Viz()

    data = pd.read_csv(options.test_dataset_file)
    data = data.loc[data['weather_parameter'] == 'WindGust']

    X = data.loc[:, options.feature_params]
    y = data.loc[:, options.label].values.ravel()

    model = fh.load_model(options.save_path)
    evaluate(model, options, data=(X, y), fh=fh, viz=viz)
예제 #11
0
    def __init__(self, CONNECT_ADDR=None, LOCAL_ADDR=None, oSHIT=None):
        # parent constructor (make threads to communicate with transport)
        # also get relevant inherted objects
        super(TestRecvPeer, self).__init__(oSHIT=oSHIT)

        # make filehandler
        self.fileh = FileHandler(self.oSHIT)

        # connect to peer
        self.CONNECT_ADDR = CONNECT_ADDR
        self.LOCAL_ADDR = LOCAL_ADDR
        self.transport = self.connect()

        # start!
        self.start_threads()
def main():

    #if options.dataset_file is None or options.output_file is None:
    dbh = DBHandler(options.db_config_file, options.db_config_name)
    dbh.return_df = False
    fh = FileHandler(s3_bucket=options.bucket)

    with open(options.example_config_file) as f:
        setups = yaml.load(f.read(), Loader=yaml.FullLoader)

    for setup in setups['examples']:

        output_file = '{}/{}-{}.csv'.format(
            setup['output_dir'], setup['starttime'].strftime('%Y%m%dT%H%M%S'),
            setup['endtime'].strftime('%Y%m%dT%H%M%S'))

        # Read in data and extract data arrays
        logging.info("Reading input data for {} - {}...".format(
            setup['starttime'], setup['endtime']))

        features, meta_params, labels, all_params = get_param_names(
            options.param_config_file)

        data = fh.read_data(
            [setup['dataset_file']],
            options,
            return_meta=True,
            starttime=setup['starttime'],  #.strftime('%Y-%m-%dT%H:%M:%S'),
            endtime=setup['endtime'])[0]  #.strftime('%Y-%m-%dT%H:%M:%S'))[0]
        X, y, meta = data

        model = fh.load_model(setup['model_file'])
        scaler = fh.load_model(setup['scaler_file'])

        logging.info('Predicting with {} samples...'.format(len(X)))
        y_pred = model.predict(X)

        df = pd.DataFrame(meta, columns=options.meta_params)
        X_inv = pd.DataFrame(scaler.inverse_transform(X), columns=X.columns)
        df = pd.concat(
            [df.reset_index(drop=True),
             X_inv.reset_index(drop=True)], axis=1)
        df = dbh.get_geom_for_dataset_rows(df)
        df['y_pred'] = y_pred
        df['y'] = y
        fh.df_to_csv(df, output_file)
예제 #13
0
def welcome(message):
    file_handler = FileHandler()
    greeting_sticker = open(greetingImg, 'rb')
    bot.send_sticker(message.chat.id, greeting_sticker)
    # keyboard
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton(messages.random_btn)
    item_weather = types.KeyboardButton(messages.weather_btn)
    markup.add(item1, item_weather)

    chat_id = message.chat.id
    bot_name = bot.get_me().first_name
    user_name = message.from_user.first_name
    mes = messages.greeting.format(user_name, bot_name)
    file_handler.save_user(message.from_user, chat_id)

    message_handler(bot, chat_id, mes, parse_mode='html', reply_markup=markup)
예제 #14
0
def main():

    # Read in data and extract data arrays
    logging.info("Reading input data for {} - {}...".format(
        options.starttime, options.endtime))

    #if options.dataset_file is None or options.output_file is None:
    dbh = DBHandler(options.db_config_filename, options.db_config_name)
    dbh.return_df = False
    fh = FileHandler(s3_bucket=options.bucket)

    starttime = dt.datetime.strptime(options.starttime, "%Y-%m-%dT%H:%M:%S")
    endtime = dt.datetime.strptime(options.endtime, "%Y-%m-%dT%H:%M:%S")

    features, meta_params, labels, all_params = get_param_names(
        options.param_config_filename)

    scaler = fh.load_model(options.scaler_file)

    # TODO change to read from operational data
    data = pd.DataFrame(dbh.get_dataset(all_params), columns=all_params)

    # TODO use original id stored in db. The id is used to assign predicted classes to a storm object (while saving to db)
    # As far as we do not have operational data, dummy ids are used
    data.loc[:, 'id'] = 0

    data = data.loc[data['weather_parameter'] == 'WindGust']

    # Add week
    data['point_in_time'] = pd.to_datetime(data['point_in_time'], utc=True)
    data['week'] = data['point_in_time'].dt.week

    X = data.loc[:, features]
    X = scaler.transform(X)

    model = fh.load_model(options.model_file)

    logging.info('Predicting with {} {} samples...'.format(
        options.model, len(X)))
    y_pred = model.predict(X)

    # Save to db
    logging.info('Saving...')
    dbh.save_classes(data.loc[:, 'id'], y_pred)
    logging.info('done.')
예제 #15
0
def send_user_weather():
    file_handler = FileHandler()
    users = file_handler.get_users()
    weather = Weather()
    if users:
        users_list = list(users.values())
        for user in users_list:
            try:
                if 'location' in user:
                    weather_message = weather.get_weather_message(
                        user['location'])
                    if weather_message['success']:
                        message_handler(bot,
                                        int(user['chatId']),
                                        weather_message['message'],
                                        parse_mode='html')
            except Exception as exception:
                print(repr(exception))
    def run(self):
        size = 1024
        # receive {"url":"", "range-left":"", "range-right":""} from client
        msg = self.client_conn.recv(size)
        if msg:
            msg = msg.decode()
            print("[+] Received Message: {}".format(msg))
            msg = json.loads(msg)

            # TODO: use Multiprocess to download using multithreading

            # TODO: use tracker-config get filepath, proxy, timeouts, retries etc

            # generate a random name for file
            filepath = temp_dir + NameGenerator().generateName(12)

            # use request to download

            Downloader().download(url=msg['url'],
                                  filepath=filepath,
                                  range_left=msg['range-left'],
                                  range_right=msg['range-right'],
                                  proxy=self.proxy)

            # send the downloaded file part to peer-client
            self.sendFilePart(filepath)

            # let peer-client know that file sending is done
            self.client_conn.shutdown(socket.SHUT_RDWR)

            # close connection with peer-client
            self.client_conn.close()
            print("[-] Client Disconnected: {}".format(self.client_addr))

            # delete temp file
            FileHandler().delete_file(filepath)
            print("[-] Temp File Deleted.")
예제 #17
0
파일: gfx.py 프로젝트: coolmanneke/PokePlat
class Graphic(object):
    file = FileHandler()
    data = []
    filename = ""
    filesize = 0

    def __init__(self, config):
        self.config = config

    def init(self, filename):
        self.file.init(os.path.join(self.config.path, filename), 0)
        self.filename = filename
        self.filesize = os.path.getsize(filename)

    def encrypt(self,
                data,
                encryption=ENCRYPTION_NONE,
                key=0,
                mult=0,
                carry=0,
                debug=False):
        dec_data = array.array('H')
        if encryption != ENCRYPTION_NONE:
            enc_data = array.array('H', data)
            if encryption == ENCRYPTION_REVERSE:
                enc_data = enc_data[::-1]
            if key == 0:
                key = enc_data[0]
            if debug:
                print("- key: " + hex(key))
            for val in enc_data:
                val2 = val ^ (key & 0xFFFF)
                dec_data.append(val2)
                val2 = key
                key *= mult  # ENCRYPT_MULT
                key += carry  # ENCRYPT_CARRY
                key &= 0xFFFF
        else:
            enc_data = array.array('H', data)
            for val in enc_data:
                dec_data.append(val)

        if encryption == ENCRYPTION_REVERSE:
            dec_data = dec_data[::-1]
        return dec_data

    def read_png(self,
                 filename,
                 encryption=ENCRYPTION_NONE,
                 output_filename="",
                 mult=0,
                 carry=0,
                 key=0,
                 debug=False):
        if os.path.getsize(filename) == 0:
            if not os.path.exists(os.path.dirname(output_filename)):
                os.makedirs(os.path.dirname(output_filename))
            f = open(output_filename, 'wb')
            f.close()
            return

        f = open(filename, 'r')
        img = png.Reader(f)
        w, h, pixels, metadata = img.read_flat()
        f.close()

        data = []
        hword = 0
        n = 0
        for val in pixels:
            hword |= val << (4 * n)
            n += 1
            if n == 4:
                n = 0
                data.append(hword)
                hword = 0

        if key == 0:
            key = 0
            for val in data:
                key += (val & 0xff)
                key += ((val >> 8) & 0xff)
                key &= 0xffff
            if debug:
                print("- key to encrypt: " + hex(key))

        enc_data = self.encrypt(data, encryption, key, mult, carry, debug)

        write_rgcn(output_filename, enc_data, w, h, debug)

    # returns indexed color values
    def read_rgcn(self,
                  encryption=ENCRYPTION_NONE,
                  width=1,
                  height=1,
                  mult=0,
                  carry=0,
                  debug=False):
        if self.filesize == 0:
            return []

        # RGCN-Header
        # PPRE/ntr/g2d/ncgr.py
        RGCN_MagicID = chr(self.file.ReadByte(0)) + chr(
            self.file.ReadByte(1)) + chr(self.file.ReadByte(2)) + chr(
                self.file.ReadByte(3))
        RGCN_Endian = self.file.ReadHWord(4)
        RGCN_Version = self.file.ReadHWord(6)
        RGCN_Size_ = self.file.ReadWord(8)
        RGCN_HeaderSize = self.file.ReadHWord(0xC)
        RGCN_NumBlocks = self.file.ReadHWord(0xE)
        if (RGCN_MagicID != "RGCN"):
            print(RGCN_MagicID + " " + hex(RGCN_Constant))
            return

        # RAHC-Header
        # PPRE/ntr/g2d/ncgr.py
        RAHC_MagicID = chr(self.file.ReadByte(0x10)) + chr(
            self.file.ReadByte(0x11)) + chr(self.file.ReadByte(0x12)) + chr(
                self.file.ReadByte(0x13))
        if (RAHC_MagicID != "RAHC"):
            return
        RAHC_Size_ = self.file.ReadByte(0x14)
        RAHC_Height = self.file.ReadHWord(0x18)
        RAHC_Width = self.file.ReadHWord(0x1A)
        RAHC_Format = self.file.ReadWord(0x1C)  # FORMAT_16BIT
        RAHC_Depth = self.file.ReadWord(0x20)
        RAHC_Type = self.file.ReadWord(0x24)
        RAHC_DataSize = self.file.ReadWord(0x28)
        RAHC_Offset = self.file.ReadWord(0x2C)

        if RAHC_Width != 0xffff:
            width = RAHC_Width

        if debug:
            print("RGCN-Data:")
            print("- Height: " + str(RAHC_Height))
            print("- Width: " + str(RAHC_Width))
            print("- Format: " + str(RAHC_Format))
            print("- Depth: " + str(RAHC_Depth))
            print("- Type: " + str(RAHC_Type))
            print("- DataSize: " + str(RAHC_DataSize))
            if encryption == ENCRYPTION_NONE:
                print("- Encryption: none")
            elif encryption == ENCRYPTION_REVERSE:
                print("- Encryption: reverse")
            elif encryption == ENCRYPTION_FORWARDS:
                print("- Encryption: forwards")

        data = []
        i = 0
        while i < RAHC_DataSize:
            data.append(self.file.ReadHWord(0x30 + i))
            i += 2

        key = 0
        dec_data = self.encrypt(data, encryption, key, mult, carry, debug)

        if debug:
            sum = 0
            for val in dec_data:
                sum += (val & 0xff)
                sum += ((val >> 8) & 0xff)
            sum &= 0xffff
            print("- keyguess: " + hex(sum))

        # sort the dec_data into rows with length 'width'
        data = []
        data_line = []
        i = 0
        for val in dec_data:
            for n in range(4):
                data_line.append((val >> (4 * n)) & 0xf)  # FORMAT_16BIT
            i += 4
            if (RAHC_Type == TYPE_LINEAR
                    or RAHC_Type == TYPE_LINEAR2) and ((i % (width * 8)) == 0):
                data.append(data_line)
                data_line = []
            elif (RAHC_Type != TYPE_LINEAR) and ((i % 8) == 0):
                data.append(data_line)
                data_line = []

        if RAHC_Type == TYPE_LINEAR2:  #!= TYPE_LINEAR:
            data_temp = data
            data = []
            data_line = []
            for l in range(height):
                for k in range(8):
                    data_line = []
                    for j in range(width):
                        for i in range(8):
                            data_line.append(data_temp[l * 2 * 4 * 8 + j * 8 +
                                                       k][i])
                    data.append(data_line)

        bmp = [[0 for j in range(9)] for i in range(9)]
        return data
예제 #18
0
파일: gfx.py 프로젝트: coolmanneke/PokePlat
class Palette(object):
    file = FileHandler()
    data = []
    filename = ""

    def __init__(self, config):
        self.config = config

    def init(self, filename):
        self.file.init(os.path.join(self.config.path, filename), 0)
        self.filename = filename

    def read_png(self, filename, output_filename="", emptypal=0, debug=False):
        if os.path.getsize(filename) == 0:
            return

        f = open(filename, 'r')
        img = png.Reader(f)
        w, h, pixels, metadata = img.read_flat()
        palette = img.palette()
        #print("palette: " + str(palette))
        f.close()

        write_rlcn(output_filename, palette, emptypal, debug)

    def read_pal(self, filename, output_filename="", emptypal=0, debug=False):
        if os.path.getsize(filename) == 0:
            return

        f = open(filename, 'r')
        lines = f.readlines()
        f.close()

        palette = []
        for i in range(16):
            colors = lines[3 + i].split(" ")
            col = (int(colors[0], 10), int(colors[1], 10), int(colors[2], 10))
            palette.append(col)

        write_rlcn(output_filename, palette, emptypal, debug)

    def read_rlcn(self, debug=False):
        # RLCN-Header
        # PPRE/ntr/g2d/nclr.py
        RLCN_MagicID = chr(self.file.ReadByte(0x0)) + chr(
            self.file.ReadByte(0x1)) + chr(self.file.ReadByte(0x2)) + chr(
                self.file.ReadByte(0x3))
        if (RLCN_MagicID != "RLCN"):
            print("Expected RLCN, got " + RLCN_MagicID)
            return
        RLCN_Endian = self.file.ReadHWord(0x4)
        RLCN_Version = self.file.ReadHWord(0x6)
        RLCN_Size_ = self.file.ReadWord(0x8)
        RLCN_HeaderSize = self.file.ReadHWord(0xc)
        RLCN_NumBlocks = self.file.ReadHWord(0xe)

        # PLTT-Header
        # PPRE/ntr/g2d/nclr.py
        PLTT_MagicID = chr(self.file.ReadByte(0x10)) + chr(
            self.file.ReadByte(0x11)) + chr(self.file.ReadByte(0x12)) + chr(
                self.file.ReadByte(0x13))
        if (PLTT_MagicID != "TTLP"):
            print("Expected TTLP, got " + PLTT_MagicID)
            return
        PLTT_Size_ = self.file.ReadWord(0x14)
        PLTT_Format = self.file.ReadWord(0x18)
        PLTT_Extended = self.file.ReadWord(0x1c)
        PLTT_Datasize = self.file.ReadWord(0x20)
        PLTT_Offset = self.file.ReadWord(0x24)

        if debug:
            print("RLCN-Data:")
            print("- Format: " + str(PLTT_Format))
            print("- Extended: " + str(PLTT_Extended))

        palette = []
        i = 0
        while i < 16:
            col = (self.file.ReadHWord(0x28 + i * 2))
            colr = col & 0x1f
            colg = (col >> 5) & 0x1f
            colb = (col >> 10) & 0x1f
            palette.append((colr * 8, colg * 8, colb * 8))
            i += 1

        return palette
예제 #19
0
import discord
import json
import asyncio
from discord.ext import commands
from filehandler import FileHandler
from jsonhandler import JsonHandler

jh = JsonHandler()
fh = FileHandler()


class ReactDropItem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.load_data()

    def load_data(self):
        self.worlditems = fh.load_file('worlditems')
        # self.currency = fh.load_file('currency')
        # self.shops = fh.load_file('shops')
        self.charactersheet = fh.load_file('charactersheet')
        self.characterinventory = fh.load_file('characterinventory')

    def s_c_i_e_ids(self):
        return jh.show_character_inventory_embed_ids()

    def s_c_s_s(self):
        return jh.show_character_sheet_stats()

# Drop inventory items
예제 #20
0
class Graphic(object):
    file = FileHandler()
    data = []
    filename = ""
    filesize = 0

    def __init__(self, config):
        self.config = config

    def init(self, filename):
        self.file.init(os.path.join(self.config.path, filename), 0)
        self.filename = filename
        self.filesize = os.path.getsize(filename)

    def encrypt(self,
                data,
                encryption=ENCRYPTION_NONE,
                key=0,
                mult=0,
                carry=0,
                debug=False):
        dec_data = array.array('H')
        if encryption != ENCRYPTION_NONE:
            enc_data = array.array('H', data)
            if encryption == ENCRYPTION_REVERSE:
                enc_data = enc_data[::-1]
            if key == 0:
                key = enc_data[0]
            if debug:
                print("- key: " + hex(key))
            for val in enc_data:
                val2 = val ^ (key & 0xFFFF)
                dec_data.append(val2)
                val2 = key
                key *= mult  # ENCRYPT_MULT
                key += carry  # ENCRYPT_CARRY
                key &= 0xFFFF
        else:
            enc_data = array.array('H', data)
            for val in enc_data:
                dec_data.append(val)

        if encryption == ENCRYPTION_REVERSE:
            dec_data = dec_data[::-1]
        return dec_data

    def read_png(self,
                 filename,
                 encryption=ENCRYPTION_NONE,
                 output_filename="",
                 mult=0,
                 carry=0,
                 key=0,
                 debug=False):
        if os.path.getsize(filename) == 0:
            if not os.path.exists(os.path.dirname(output_filename)):
                os.makedirs(os.path.dirname(output_filename))
            f = open(output_filename, 'wb')
            f.close()
            return

        f = open(filename, 'r')
        img = png.Reader(f)
        w, h, pixels, metadata = img.read_flat()
        f.close()

        data = []
        hword = 0
        n = 0
        for val in pixels:
            hword |= val << (4 * n)
            n += 1
            if n == 4:
                n = 0
                data.append(hword)
                hword = 0

        if key == 0:
            key = 0
            for val in data:
                #key += ((val>>0) & 0xf)
                #key += ((val>>4) & 0xf)
                #key += ((val>>8) & 0xf)
                #key += ((val>>12) & 0xf)
                #val = val ^ 0xffff
                key += (val & 0xff)
                key += ((val >> 8) & 0xff)
                key &= 0xffff
            if debug:
                print("- key to encrypt: " + hex(key))

        enc_data = self.encrypt(data, encryption, key, mult, carry, debug)

        write_rgcn(output_filename, enc_data, w, h, debug)

    # returns indexed color values
    def read_rgcn(self,
                  encryption=ENCRYPTION_NONE,
                  width=1,
                  height=1,
                  mult=0,
                  carry=0,
                  debug=False):
        if self.filesize == 0:
            return []

        # RGCN-Header
        # PPRE/ntr/g2d/ncgr.py
        RGCN_MagicID = chr(self.file.ReadByte(0)) + chr(
            self.file.ReadByte(1)) + chr(self.file.ReadByte(2)) + chr(
                self.file.ReadByte(3))
        RGCN_Endian = self.file.ReadHWord(4)
        RGCN_Version = self.file.ReadHWord(6)
        RGCN_Size_ = self.file.ReadWord(8)
        RGCN_HeaderSize = self.file.ReadHWord(0xC)
        RGCN_NumBlocks = self.file.ReadHWord(0xE)
        if (RGCN_MagicID != "RGCN"):
            print(RGCN_MagicID + " " + hex(RGCN_Constant))
            return

        # RAHC-Header
        # PPRE/ntr/g2d/ncgr.py
        RAHC_MagicID = chr(self.file.ReadByte(0x10)) + chr(
            self.file.ReadByte(0x11)) + chr(self.file.ReadByte(0x12)) + chr(
                self.file.ReadByte(0x13))
        if (RAHC_MagicID != "RAHC"):
            return
        RAHC_Size_ = self.file.ReadByte(0x14)
        RAHC_Height = self.file.ReadHWord(0x18)
        RAHC_Width = self.file.ReadHWord(0x1A)
        RAHC_Format = self.file.ReadWord(0x1C)
        RAHC_Depth = self.file.ReadWord(0x20)
        RAHC_Type = self.file.ReadWord(0x24)
        RAHC_DataSize = self.file.ReadWord(0x28)
        RAHC_Offset = self.file.ReadWord(0x2C)

        if RAHC_Width != 0xffff:
            width = RAHC_Width

        if debug:
            print("RGCN-Data:")
            print("- Height: " + str(RAHC_Height))
            print("- Width: " + str(RAHC_Width))
            print("- Format: " + str(RAHC_Format))
            print("- Depth: " + str(RAHC_Depth))
            print("- Type: " + str(RAHC_Type))
            print("- DataSize: " + str(RAHC_DataSize))
            if encryption == ENCRYPTION_NONE:
                print("- Encryption: none")
            elif encryption == ENCRYPTION_REVERSE:
                print("- Encryption: reverse")
            elif encryption == ENCRYPTION_FORWARDS:
                print("- Encryption: forwards")

        data = []
        i = 0
        while i < RAHC_DataSize:
            data.append(self.file.ReadHWord(0x30 + i))
            i += 2

        key = 0
        dec_data = self.encrypt(data, encryption, key, mult, carry, debug)

        if debug:
            sum = 0
            for val in dec_data:
                sum += (val & 0xff)
                sum += ((val >> 8) & 0xff)
            sum &= 0xffff
            print("- keyguess: " + hex(sum))

        # sort the dec_data into rows with length 'width'
        data = []
        data_line = []
        i = 0
        for val in dec_data:
            for n in range(4):
                data_line.append((val >> (4 * n)) & 0xf)
            i += 4
            if (RAHC_Type == TYPE_LINEAR
                    or RAHC_Type == TYPE_LINEAR2) and ((i % (width * 8)) == 0):
                data.append(data_line)
                data_line = []
            elif (RAHC_Type != TYPE_LINEAR) and ((i % 8) == 0):
                data.append(data_line)
                data_line = []

        if RAHC_Type != TYPE_LINEAR:
            data_temp = data
            data = []
            data_line = []
            for l in range(height):
                for k in range(8):
                    data_line = []
                    for j in range(width):
                        for i in range(8):
                            data_line.append(data_temp[l * 4 * 8 + j * 8 +
                                                       k][i])
                    data.append(data_line)

        #Tiles = []
        bmp = [[0 for j in range(9)] for i in range(9)]
        #TileX = 0
        #TileY = 0
        #i = 0
        #j = 0
        #line = []
        #y = 0
        #while i < 4*8:#RAHC_TileDataSize:
        #    byte = self.file.ReadByte(0x30+i)
        #    b = byte >> 4
        #    a = byte & 0xf
        #    bmp[y][j] = a
        #    bmp[y][j+1] = b
        #line.append(a)
        #line.append(b)
        #    i += 1
        #    j += 2
        #    if j == 8:
        #        y += 1
        #        j = 0
        #Tiles.append(line)
        #line = []

        #tiled = False
        #height = 20
        #width = 10
        #depth = 3
        #i = 0
        #tiles = []
        #if tiled:
        #    for l in range(height):
        #        row = []
        #        for m in range(width):
        #            col = []
        #            for n in range(8):
        #                tilerow = []
        #                for p in range(4):
        #                    if depth == 0x3:
        #tmp = unpack("B", rawdata[:1])[0]
        #                        tmp = self.file.ReadByte(0x30+i)
        #                        i += 1
        #rawdata = rawdata[1:]
        #                        tilerow.append(tmp&0xf)
        #                        tilerow.append(tmp>>4)
        #                col.append(tilerow)
        #            row.append(col)
        #        tiles.append(row)
        #else:
        #    for l in range(height*8):
        #        row = []
        #        for m in range(width*4):
        #            if depth == 0x3:
        #                #tmp = unpack("B", rawdata[:1])[0]
        #                tmp = self.file.ReadByte(0x30+i)
        #                i += 1
        #rawdata = rawdata[1:]
        #                row.append(tmp&0xf)
        #                row.append(tmp>>4)

        #data = []
        #lenL = len(tiles)
        #for l in range(lenL):
        #    lenM = len(tiles[l])
        #    if tiled:
        #        for n in range(8):
        #            data_line = []
        #            for m in range(lenM):
        #                for p in range(8):
        #                    data_line.append(tiles[l][m][n][p])
        #            data.append(data_line)
        #    else:
        #        for m in range(lenM):
        #data_line.append(tiles[l][m])
        #data_line = []
        #for n in range(8):
        #    for p in range(8):
        #        data_line.append(tiles[l][m][n][p])
        #            data.append([0])
        #data_line = []
        return data
 def setUp(self):
     # Arrange
     self._uut = FileHandler()
예제 #22
0
# -*- coding: utf-8 -*-

import os
import sys
from ctypes import c_int8
import operator
from new import classobj
import configuration
from filehandler import FileHandler
from lists.pokemonnamelist import PokemonNameList
from lists.movenamelist import MoveNameList
from lists.itemnamelist import ItemNameList

file_trainer = FileHandler()
file_pkmns = FileHandler()


def GetPokemonName(species):
    if species <= 493:
        return PokemonNameList[species].upper()
    else:
        return PokemonNameList[0].upper()


def GetMoveName(move):
    if move <= 467:
        return MoveNameList[move].upper()
    else:
        return MoveNameList[0].upper()

예제 #23
0
 def __init__(self):
     self.filehandler = FileHandler(config.task_file)
     self.task_list = self.filehandler.parse_file()
     self.current_task_index = 0
예제 #24
0
    def __init__(self):

        # Declare class variables
        self.encodings = [
            ["Default", None],
            ["ASCII", "ascii"],
            ["ISO-8859-1", "latin_1"],
            ["ISO-8859-2", "iso8859_2"],
            ["ISO-8859-3", "iso8859_3"],
            ["ISO-8859-4", "iso8859_4"],
            ["ISO-8859-5", "iso8859_5"],
            ["ISO-8859-6", "iso8859_6"],
            ["ISO-8859-7", "iso8859_7"],
            ["ISO-8859-8", "iso8859_8"],
            ["ISO-8859-9", "iso8859_9"],
            ["ISO-8859-10", "iso8859_10"],
            ["ISO-8859-13", "iso8859_13"],
            ["ISO-8859-14", "iso8859_14"],
            ["ISO-8859-15", "iso8859_15"],
            ["KOI8-R", "koi8_r"],
            ["KOI8-U", "koi8_u"],
            ["UTF-8 with BOM", "utf_8_sig"],
            ["UTF-8 without BOM", "utf_8"],
            ["UTF-16BE", "utf_16_be"],
            ["UTF-16LE", "utf_16_le"],
            ["UTF-32BE", "utf_32_be"],
            ["UTF-32LE", "utf_32_le"],
            ["Windows-1250", "cp1250"],
            ["Windows-1251", "cp1251"],
            ["Windows-1252", "cp1252"],
            ["Windows-1253", "cp1253"],
            ["Windows-1254", "cp1254"],
            ["Windows-1255", "cp1255"],
            ["Windows-1256", "cp1256"],
            ["Windows-1257", "cp1257"],
            ["Windows-1258", "cp1258"]
        ]
        self.path = "" # Path for fix
        self.filelist = [] # File list for fix
        self.filetypes = ["srt", "txt"] # Accepted file types
        self.typefilter = "All supported files (*.srt *.txt)"
        self.typefilter += ";;SubRip subtitle file (*.srt)"
        self.typefilter += ";;Text file (*.txt)"

        # Create class instances
        self.data = DataHandler()
        self.file = FileHandler(self.filetypes)
        self.string = StringHandler()

        # Initialize top level window widget
        QtGui.QMainWindow.__init__(self)

        # This is always the same
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect signals, menu and toolbar
        self.ui.actionNewDatabase.triggered.connect(self.newDatabase)
        self.ui.actionOpenDatabase.triggered.connect(self.openDatabaseMsgBox)
        self.ui.actionAddFiles.triggered.connect(self.fAddFiles)
        self.ui.actionAddFolder.triggered.connect(self.fAddFolder)
        self.ui.actionRemoveFiles.triggered.connect(self.fRemoveFiles)
        self.ui.actionClearList.triggered.connect(self.fClearList)
        self.ui.actionStart.triggered.connect(self.fStart)
        self.ui.actionQuit.triggered.connect(self.quitApplication)
        self.ui.actionAbout.triggered.connect(self.aboutMessage)

        # Connect signals, buttons
        self.ui.btnFStart.clicked.connect(self.fStart)
        self.ui.btnFAddFiles.clicked.connect(self.fAddFiles)
        self.ui.btnFAddFolder.clicked.connect(self.fAddFolder)
        self.ui.btnFRemoveFiles.clicked.connect(self.fRemoveFiles)
        self.ui.btnFClearList.clicked.connect(self.fClearList)
        self.ui.btnLDeleteRow.clicked.connect(self.lDeleteRow)
        self.ui.btnLInsertRow.clicked.connect(self.lInsertRow)
        self.ui.btnLUpdateRow.clicked.connect(self.lUpdateRow)
        self.ui.txtCSearch.returnPressed.connect(self.refreshCCorrections)
        self.ui.btnCDeleteRow.clicked.connect(self.cDeleteRow)
        self.ui.btnCInsertRow.clicked.connect(self.cInsertRow)
        self.ui.btnCUpdateRow.clicked.connect(self.cUpdateRow)
        self.ui.btnLClearLog.clicked.connect(self.lClearLog)

        # Connect signals, comboboxes
        self.ui.cboCCorrectionMode.activated.connect(self.refreshCCorrections)
        self.ui.cboCList.activated.connect(self.refreshCCorrections)

        # Connect signals, tables
        self.ui.tblCCorrections.currentCellChanged[(int,int,int,int)].connect(\
            self.selectCorrection)

        # Drag-and-drop events for file list
        self.ui.tblFFileList.dragEnterEvent = self.dragEnterEvent
        self.ui.tblFFileList.dragMoveEvent = self.dragEnterEvent
        self.ui.tblFFileList.dropEvent = self.dropEvent

        # Loop and set encodings to settings combobox
        for item in self.encodings:
            self.ui.cboSFileEncoding.addItem(item[0])

        # Select the first tab from the tab widgets
        self.ui.tabMain.setCurrentIndex(0)

        # Icons
        self.setWindowIcon(QtGui.QIcon("icon.png"))

        self.ui.actionNewDatabase.setIcon(QtGui.QIcon("new_database.png"))
        self.ui.actionOpenDatabase.setIcon(QtGui.QIcon("open_database.png"))
        self.ui.actionAddFiles.setIcon(QtGui.QIcon("add_files.png"))
        self.ui.actionAddFolder.setIcon(QtGui.QIcon("add_folder.png"))
        self.ui.actionRemoveFiles.setIcon(QtGui.QIcon("remove.png"))
        self.ui.actionClearList.setIcon(QtGui.QIcon("clear.png"))
        self.ui.actionStart.setIcon(QtGui.QIcon("start.png"))
        self.ui.actionQuit.setIcon(QtGui.QIcon("quit.png"))
        self.ui.actionAbout.setIcon(QtGui.QIcon("about.png"))

        self.ui.tabMain.setTabIcon(0, QtGui.QIcon("fix.png"))
        self.ui.tabMain.setTabIcon(1, QtGui.QIcon("lists.png"))
        self.ui.tabMain.setTabIcon(2, QtGui.QIcon("corrections.png"))
        self.ui.tabMain.setTabIcon(3, QtGui.QIcon("log.png"))
        self.ui.tabMain.setTabIcon(4, QtGui.QIcon("settings.png"))

        self.ui.btnFAddFiles.setIcon(QtGui.QIcon("add_files.png"))
        self.ui.btnFAddFolder.setIcon(QtGui.QIcon("add_folder.png"))
        self.ui.btnFRemoveFiles.setIcon(QtGui.QIcon("remove.png"))
        self.ui.btnFClearList.setIcon(QtGui.QIcon("clear.png"))
        self.ui.btnFStart.setIcon(QtGui.QIcon("start.png"))

        self.ui.btnLDeleteRow.setIcon(QtGui.QIcon("delete_row.png"))
        self.ui.btnLInsertRow.setIcon(QtGui.QIcon("insert_row.png"))
        self.ui.btnLUpdateRow.setIcon(QtGui.QIcon("update_row.png"))
        self.ui.btnCDeleteRow.setIcon(QtGui.QIcon("delete_row.png"))
        self.ui.btnCInsertRow.setIcon(QtGui.QIcon("insert_row.png"))
        self.ui.btnCUpdateRow.setIcon(QtGui.QIcon("update_row.png"))

        self.ui.btnLClearLog.setIcon(QtGui.QIcon("clear.png"))

        # Check if command line arguments has files in it
        if sys.argv[1:]:
            self.loopItems(sys.argv[1:])

        # Load settings
        self.loadSettings()
예제 #25
0
 def __init__(self):
     self.cp = CommandParser()
     self.fh = FileHandler()
     self._init_callbacks()
     self._loop()
예제 #26
0
            #new_server_thread.daemon = True
            new_server_thread.start()


if __name__ == '__main__':

    try:
        peerClientConfig = PeerClientConfigHandler()
        peerClientConfig.parseConfig()

        tracker_host = peerClientConfig.getTrackerHost()
        tracker_port = peerClientConfig.getTrackerPort()
        tracker_server_address = (tracker_host, tracker_port)
        temp_dir = peerClientConfig.getTempDirPath()

        filehandle = FileHandler()
        filehandle.create_dir(temp_dir)

        # check if download url supplied
        if (len(sys.argv) < 2):
            print("No Download URL! Exiting ...")
            sys.exit(0)
        url = sys.argv[1]
        client = ThreadedPeerClient(url)
        # port used by peer-client to communicate with tracker
        bind_port = peerClientConfig.getClientTrackerBindPort()

        # fetch the list of active servers
        client.fetchPeersList(tracker_server_address, bind_port)

        # if servers doesn't exist, use simple download
# -*- coding: utf-8 -*-

import os
import sys
from ctypes import c_int8
import operator
from new import classobj
import configuration
from filehandler import FileHandler
from lists.pokemonnamelist import PokemonNameList
from lists.movenamelist import MoveNameList
from lists.itemnamelist import ItemNameList
from lists.naturenamelist import NatureNameList

input_file = FileHandler()


def GetPokemonName(species):
    if species <= 493:
        return PokemonNameList[species].upper()
    else:
        return hex(species)


def GetMoveName(move):
    if move <= 467:
        return MoveNameList[move].upper()
    else:
        return MoveNameList[0]

예제 #28
0
파일: main.py 프로젝트: devdrik/robo-arm
ser = serial.Serial(serialPort, 115200, timeout=1)
ser.flush()

servos = [
    Dynamixel(0, ser),
    Dynamixel(1, ser),
    Dynamixel(2, ser),
    Dynamixel(3, ser),
    Dynamixel(4, ser)
]
kinematics = InverseKinematics()
robo = Robo(servos, kinematics)

moves = RoboMoves(robo, kinematics)
fileHandler = FileHandler()
actionHandler = ActionHandler(robo, fileHandler)
cli = RoboCLI(actionHandler, robo)


def moveWithCV(showMovie=False):
    ip = ImageProcessor()
    vid = VideoStream(src=0).start()
    time.sleep(2.0)
    while True:
        frame = vid.read()
        if frame is None:
            break
        frame = imutils.resize(frame, width=600)
        if showMovie:
            if ip.contour is not None:
예제 #29
0
 def __init__(self):
     self.owm = pyowm.OWM(W_TOKEN, language="EN")
     self.file_handler = FileHandler()
예제 #30
0
 def setup_file_handler(self):
     self.handler = FileHandler()
     self.file_queue = Queue()
     self.proc = Process(target = self.handler.handler_queue, args = (self.file_queue,))
     self.proc.start()