def response1_north():
    # Player choses north from first travel movement
    import tools, Ku_Belenor, response1_enter_the_water

    north_file = 'Data\\narration\\Navigation\\response1\\response1_north.txt'
    read_speed = 1

    # read the response1_north text file
    tools.read_file(north_file, read_speed)

    while True:
        # Read players choice
        response = input('what would you like to do?')
        if 'city' in response.lower():
            Ku_Belenor.Ku_belenor()
        elif 'water' in response.lower():
            print('you enter the water')
            response1_enter_the_water.enter_the_water()
            break
        else:
            print(
                "\nI am sorry, I don't understand. Please chose NORTH, CITY, or WATER\n"
            )
        return


# ___________________________________________________________-
# Debug
#response1_north()
Example #2
0
def create_onehot(one_data, vocab_data, max_length):
    vocab_list = tools.read_file(vocab_data)
    vocabulary_word2index = {}  ### word :index
    vocabulary_index2word = {}  ### index :word
    for i, vocab in enumerate(vocab_list):
        vocabulary_word2index[vocab] = i
        vocabulary_index2word[i] = vocab

    if isinstance(one_data, str) and ".txt" in one_data:  ###是字符串,即txt
        one_data_list = tools.read_file(one_data)
        singleTest = False
    else:
        one_data_list = one_data  ### 数组
        singleTest = True
    X = []
    if not singleTest:
        for data in one_data_list:
            content = [vocabulary_word2index.get(e, 0) for e in data]
            X.append(content)
        x_pad = kr.preprocessing.sequence.pad_sequences(
            X, max_length)  #### 对数据进行定长处理
    else:
        content = [vocabulary_word2index.get(e, 0) for e in one_data_list]
        X.append(content)
        x_pad = kr.preprocessing.sequence.pad_sequences(
            X, max_length)  #### 对数据进行定长处理
    return x_pad
Example #3
0
 def test_read_file(self):
     """
     Test the function read_file
     """
     test_tools_file = os.path.abspath(__file__)
     test_directory = os.path.dirname(test_tools_file)
     non_existing_file = os.path.join(test_directory, "nonExistingFile")
     self.assertIsNotNone(tools.read_file(test_tools_file))
     self.assertIsNone(tools.read_file(non_existing_file))
Example #4
0
 def test_read_file(self):
     """
     Test the function read_file
     """
     test_tools_file = os.path.abspath(__file__)
     test_directory = os.path.dirname(test_tools_file)
     non_existing_file = os.path.join(test_directory, "nonExistingFile")
     self.assertIsNotNone(tools.read_file(test_tools_file))
     self.assertIsNone(tools.read_file(non_existing_file))
Example #5
0
    def test_read_file_function(self):
        """
        .- check it is possible to read files
        """

        if os.path.exists(self.dummy_file) is False:
            raise Exception(self.no_file_error_msg)

        # .- read_file
        self.assertIsNotNone(tools.read_file(self.dummy_file))

        read_text = tools.read_file(self.dummy_file)
        self.assertEqual(read_text, self.text)
Example #6
0
def hw_check():
   """ returns the list of hardware attached to the system  """
   command=""" ls /dev/video* """
   cams = os.popen(command).read().rstrip('\n').split('\n')

   command=""" lsusb """
   usbs = os.popen(command).read().rstrip('\n').split('\n')
   try:
#      usb0 = t.read_file('.usb.list')
      usb0 = t.read_file('.usbINL-L0096.list')
      for u in usb0:
         try:
            usbs.remove(u)
         except ValueError:
            pass
#            warning = 'WARNING: no %s found' % (u)
#            WARNINGS.append(warning)
   except IOError:
      warning = 'WARNING: No usb file'
      WARNINGS.append(warning)

   command=""" cat /proc/cpuinfo | grep 'processor' | wc -l """
   num_procesadores = os.popen(command).read().rstrip('\n').split('\n')

   return [cams,usbs,num_procesadores]
Example #7
0
def set_attributes(component_data_dict, parent_function):

    # Call parent_function
    parent_function()

    if component_data_dict["builder_name"] == "configuration":
        # Build this component from outside the chroot
        tools.add_to_dictionary(component_data_dict,
                                key="build_into_chroot",
                                value=False,
                                concat=False)
        tools.add_to_dictionary(component_data_dict,
                                key="run_as_username",
                                value="root",
                                concat=False)

        # Set 'config.GRUB_ROOT_PARTITION_NAME' with stored value in the 'tmp/loop_device.txt'
        # file if present.
        loop_device = os.path.join(
            component_data_dict["lfsbuilder_tmp_directory"], "loop_device.txt")

        if os.path.exists(loop_device) is True:
            component_data_dict["component_substitution_list"].extend([
                config.GRUB_ROOT_PARTITION_NAME,
                tools.read_file(loop_device).replace("/dev/", "")
            ])
Example #8
0
    def test_substitute_in_file(self):
        """
        .- check it is possible to substitute parameters files
        """
        text = "@@LFS_BASE_DIRECTORY@@"

        # .- write file
        tools.write_file(self.dummy_file, text)

        self.assertEqual(tools.read_file(self.dummy_file), text)

        # .- substitute
        tools.substitute_in_file(self.dummy_file, text, config.BASE_DIRECTORY)

        self.assertEqual(tools.read_file(self.dummy_file),
                         config.BASE_DIRECTORY)
Example #9
0
    def _login(self, user=None):
        url = 'http://www.kingsofchaos.com/login.php'
        if not user:
            user = '******'

        pw = tools.read_file('._login.txt')
        values = [['usrname', user], ['peeword', pw]]
        res = self.submit_form(url, values)
Example #10
0
def Wey():
    import os, sys, tools, time, Derith
    path = os.getcwd()
    sys.path.insert(0, path)

    #variables
    Wey_file_path = 'Data\\narration\\Navigation\\Wey\\'
    Wey_intro = 'wey.txt'
    inn_file = 'Wey_inn.txt'
    adventure_market = 'adventure_market.txt'
    adventure_market_again = 'adventure_market_again.txt'
    choices_file = 'wey_choices.txt'
    read_speed = .1
    number_adventure_market = 0

    tools.read_file(Wey_file_path + Wey_intro, read_speed)

    while True:
        tools.read_file(Wey_file_path + choices_file, read_speed)
        response = input("What do you do?")

        if 'inn' in response.lower():
            time.sleep(read_speed)
            tools.read_file(Wey_file_path + inn_file, read_speed)

        elif 'adventure market' in response.lower():
            number_adventure_market = number_adventure_market + 1
            time.sleep(read_speed)
            if number_adventure_market <= 1:
                tools.read_file(Wey_file_path + adventure_market, read_speed)
                tools.player_level_up()
            else:
                tools.read_file(Wey_file_path + adventure_market_again,
                                read_speed)
        elif 'hobble hill' in response.lower():
            print()
        elif 'Derith' in response.lower():
            time.sleep(read_speed)
            print("you ", response)
            Derith.Derith()
        elif "east" in response.lower():
            print()
        else:
            print(" \n\n\t\t I am sorry, I dont understand\n")

    return
Example #11
0
	def get_user_password(self):
		d = {}
		lines = tools.read_file('._login.txt').split('\n')
		for line in lines:
			if line:
				field, value = line.split('=', 1)
				d[field] = value
		return d['username'], d['password']
Example #12
0
def is_letter_found(letter, image_bits_str):
    letter_bits_list_str = tools.read_file('letters_%s.txt' % letter)
    letter_bits_list = letter_bits_list_str.split(',')

    for letter_bits in letter_bits_list:
        letter_bits_sum = sum(map(int, letter_bits))
        image_bits_sum = sum(map(int, image_bits_str))
        if letter_bits_sum == image_bits_sum:
            print 'Sum Match Found'
        if image_bits_str in letter_bits:
            return True
    return False
def enter_the_water():
    import tools

    read_file = 'Data\\narration\\Navigation\\response1\\response1_enter_the_water.txt'
    death_file = 'Data\\narration\\Navigation\\response1\\octopus_fight_death.txt'
    player_file = 'Data\\player_info\\player.txt'
    escape_file = 'Data\\narration\\Navigation\\response1\\octopus_fight_escape.txt'
    player_info = {}
    read_speed = 1

    # read the prompt for the player
    tools.read_file(read_file, read_speed)

    # open the players info file
    with open(player_file, 'r') as player:
        player_contents = player.read()
        player_info = eval(player_contents)

    # check player's dex
    if player_info['Dex'] > 15:
        # update the players statistics
        tools.update_player_stats('Dex', player_info['Dex'] + 1)
        tools.read_file(escape_file, read_speed)
        return

    else:
        tools.read_file(death_file, read_speed)
        tools.end()
        return
Example #14
0
    def test_add_text_to_file_beginning(self):
        """
        .- check we can add text at the beginning of files
        """
        text = "previous"
        test_string = "previous\n{t}".format(t=self.text)

        # .- add text
        tools.add_text_to_file(self.dummy_file, text, at_the_beginning=True)

        # .- read file
        read_text = tools.read_file(self.dummy_file)

        self.assertMultiLineEqual(read_text, test_string)
Example #15
0
    def test_add_text_to_file_end(self):
        """
        .- check we can add text at the end of files
        """
        text = "post"
        test_string = "{t}\npost".format(t=self.text)

        # .- add text
        tools.add_text_to_file(self.dummy_file, text)

        # .- read file
        read_text = tools.read_file(self.dummy_file)

        self.assertMultiLineEqual(read_text, test_string)
Example #16
0
def test():
    f = tools.read_file('letters_A.txt')
    numbers = f.split(',')

    for i in xrange(len(numbers)):
        if i in numbers[i + 1:]:
            print 'Dupe'

    print len(numbers[154]), len(numbers[155])
    print len(numbers)

    l = [0, 1, 0]

    ls = ''.join(map(str, l))
    print ls
Example #17
0
def Textcnn_test():
    if FLAGS.vocab_dir is None:
        words = tools.build_vocab(train_data=FLAGS.train_data,
                                  vocab_dir=FLAGS.vocab_dir)  ### 制作词汇表
    else:
        words = tools.read_file(FLAGS.vocab_dir)
    vocab_size = len(words)
    print("Test words : ", vocab_size)
    test_X, test_Y = tools.create_voabulary(train_data=FLAGS.test_data,
                                            vocab_data=FLAGS.vocab_dir,
                                            max_length=config.seq_length)

    input_x = tf.placeholder(tf.int32, [None, config.seq_length],
                             name='input_x')
    input_y = tf.placeholder(tf.float32, [None, config.num_classes],
                             name='input_y')

    model_path = 'checkpoints/TextCNNnet_2019-11-01-15-31-50.ckpt-4000'

    save_path = model_path
    sess_config = tf.ConfigProto(allow_soft_placement=True)
    sess_config.gpu_options.allow_growth = True
    sess = tf.Session(config=sess_config)

    textcnn = TextCNN(config, vocab_size, keep_prob=1.0)
    logits = textcnn.cnn(input_x)  ### (?,10)
    loss = textcnn_loss(logits=logits, label=input_y)
    acc = textcnn_acc(logits=logits, labels=input_y)

    saver = tf.train.Saver()
    saver.restore(sess=sess, save_path=save_path)

    batch_test = tools.batch_iter(test_X, test_Y,
                                  config.batch_size)  ### 生成批次数据
    i = 0
    all_acc = 0
    for x_batch, y_batch in batch_test:
        test_loss, test_acc = sess.run([loss, acc],
                                       feed_dict={
                                           input_x: x_batch,
                                           input_y: y_batch
                                       })
        all_acc = all_acc + test_acc
        i += 1

    print("Average acc : ", (all_acc / i))
Example #18
0
def config_info():
    write_logs('当前配置信息:')
    write_logs('    树莓派ID:%s' % tools.read_file(config.pi_info_file), False)
    write_logs('    阿里云服务器IP:' + config.ali_host, False)
    write_logs('    阿里云服务器web端口号:' + config.ali_web_port, False)
    write_logs('    阿里云服务器tcp端口号:' + str(config.ali_tcp_port), False)
    write_logs('    阿里云服务器域名:%s' % config.ali_url, False)
    write_logs('    摄像头局域网URL:' + config.stream_url, False)
    write_logs('    摄像头本地URL:%s' % config.stream_locate_url, False)
    write_logs('    是否使用摄像头:' + str(config.use_camera), False)
    write_logs('    允许的最大命令长度:%d' % config.max_cmds_length, False)
    write_logs('    一次性发送的图片大小:%d' % config.img_size, False)
    write_logs('    摄像头与树莓派客户端是否是同一个机子:%s' % config.same_machine, False)
    write_logs('    数据文件目录:' + config.file_dir, False)
    write_logs('    存放命令的文件:' + config.cmd_file, False)
    write_logs('    存放树莓派的数据文件:' + config.data_file, False)
    write_logs('    存放客户端日志的文件:' + config.log_file, False)
    write_logs('    是否记录日志:' + str(config.save_log), False)
Example #19
0
    def generate_components_filelist_from_index(self, indexfile, exclude=None):
        """
        Generate a list of components present in 'indexfile',
        usually the chapter's index file.
        """
        components_filelist = []
        directory = os.path.dirname(indexfile)
        # Get component list from chapter index
        file_text = tools.read_file(indexfile)

        for line in file_text.split("\n"):
            # Valid lines includes text 'xi:include' and are not XML comments
            if line.find("xi:include") != -1 and line.find("<!--") == -1:
                line_fields = line.split("\"")
                # line_fields = ['  <xi:include xmlns:xi=',
                #                'http://www.w3.org/2001/XInclude',
                #                ' href=',
                #                'introduction.xml',
                #                '/>']
                component = line_fields[3]

                # Add to components_filelist if 'file.xml' is not any of
                # the given excludes or it is not a XML file
                add = True

                # Do not add it if it is not a XML file
                if component.find(".xml") == -1:
                    add = False

                # Do not add 'component' if excluded
                if (add is True and tools.is_empty_list(exclude) is False):
                    for e in exclude:
                        # Do not add it if match
                        e = "{e}.xml".format(e=e)
                        if component == e:
                            add = False

                # Add it
                if add is True:
                    # Include absolute path
                    components_filelist.append(
                        os.path.join(directory, component))

        return components_filelist
Example #20
0
    def read_db(self, sql='select * from lagou'):

        try:
            cursor = self.conn.cursor()

            cursor.execute(sql)
            results = cursor.fetchall()

            flag = read_file('./bendi.txt')
            if flag[0] == '':
                start = '0'
            else:
                start = flag[0]

            start = int(start)
            if start >= (len(results) - 1):
                print('执行完毕')
                exit(0)

            for i in range(start, len(results) - 1):
                if i % 8 == 0:
                    time.sleep(2)
                row = results[i]
                link = row[1]
                try:
                    city, brief_info, job_descrip = self.open_sub_url(link, i)

                    jobtitle = row[2]
                    experience = row[3]
                    education = row[4]
                    salary = row[5]
                    company = row[6]
                    result = [
                        jobtitle, experience, education, salary, city, company,
                        brief_info, job_descrip
                    ]
                    self.__sub_memory(result)
                except TypeError as err:
                    print(err)

        except Exception as err:
            print(self.read_db.__name__ + " " + str(err))
Example #21
0
    def __init__(self, vocab_dir):
        self.input_x = tf.placeholder(tf.int32, [None, config.seq_length],
                                      name='input_x')
        self.words = tools.read_file(vocab_dir)
        self.vocab_size = len(self.words)

        self.textcnn = TextCNN(config, self.vocab_size, keep_prob=1.0)
        self.logits = self.textcnn.cnn(self.input_x)
        self.textcnn_pred = tf.argmax(tf.nn.softmax(self.logits), 1)

        saver = tf.train.Saver()
        sess_config = tf.ConfigProto(allow_soft_placement=True)

        sess_config.gpu_options.per_process_gpu_memory_fraction = 0.8
        sess_config.gpu_options.allow_growth = True
        self.sess = tf.Session(config=sess_config)
        model_path = 'checkpoints/model/TextCNNnet_2019-10-17-14-35-50.ckpt-9000'
        saver.restore(sess=self.sess, save_path=model_path)
        print(
            "################ load TextCNN model down! ##########################"
        )
Example #22
0
def parse(base_dir):
    _base = Base()

    for filename in sorted(glob(join_path(base_dir, '*.txt'))):
        read, err = read_file(filename)

        if err:
            sys.exit(err)

        keys = read[0][1:]
        question_text = read[1]
        answers_text = read[2:]

        answers = [Answer(ans, base_dir) for ans in answers_text]
        for i, v in enumerate(keys):
            answers[i].is_true = (v == '1')

        _question = Question(filename, question_text, answers, base_dir)
        _base.questions.append(_question)

    return _base
Example #23
0
def connect_server():
    global cmd_socket, img_socket, connect_socket
    write_logs('\n正在连接服务器 ...')
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.settimeout(config.connect_timeout)
    pi_id = tools.read_file(config.pi_info_file)
    if pi_id is not None:
        udp_socket.sendto(pi_id.encode(),
                          (config.ali_host, config.ali_udp_port))
        try:
            if udp_socket.recv(
                    config.max_cmds_length) == config.ali_cmds['server_ok']:
                write_logs('服务器接受了树莓派的连接请求,正在创建TCP连接 ...')
                cmd_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                cmd_socket.connect((config.ali_host, config.ali_tcp_port))
                write_logs('来自服务器的响应:' +
                           cmd_socket.recv(config.max_cmds_length).decode())
                img_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                img_socket.connect((config.ali_host, config.ali_tcp_port))
                write_logs('来自服务器的响应:' +
                           img_socket.recv(config.max_cmds_length).decode())
                connect_socket = socket.socket(socket.AF_INET,
                                               socket.SOCK_STREAM)
                connect_socket.connect((config.ali_host, config.ali_tcp_port))
                write_logs(
                    '来自服务器的响应:' +
                    connect_socket.recv(config.max_cmds_length).decode())
                config_info()
                write_logs('\n服务器连接成功,等待服务器的命令 ... \n')
            else:
                write_logs('服务器拒绝了树莓派的连接请求!')
                sys.exit()
        except (socket.timeout, TimeoutError):
            write_logs('服务器连接超时!')
            sys.exit()
        except ConnectionResetError:
            write_logs('连接被拒绝!')
            sys.exit()
    else:
        write_logs('错误:树莓派信息获取失败!不能打开文件:' + config.pi_info_file)
    def aplicar_mejor_solucion_desde_archivo(self):
        # if '.tsp' not in self.filename:
        #     print(f'El escenario {self.nombre} no fue generado apartir de un archivo .tsp')
        #     return
        solution_file = self.filename.replace('.tsp', '') + ".opt.tour"

        lines = read_file(solution_file)
        index_for_search = [
            index for index, line in enumerate(lines) if 'TOUR_SECTION' in line
        ][0] + 1

        next_line = lines[index_for_search]
        # if else porque a veces la solucion a parece en una sola linea y a veces en varias
        if sum([str(city) in next_line
                for city in self.solution]) == self.dimension:
            self.solution = list(map(int, next_line.split(' ')))
        else:
            self.solution = list(
                map(int,
                    lines[index_for_search:index_for_search + self.dimension]))
            print(self.solution)
        self.ordenar_solucion()
        print(f'Solucion desde archivo: {self.compute_dist()} m')
    def obtener_desde_archivo_tsp(self, tsp_name):
        tsp_file = tsp_name
        lines = read_file(tsp_file)
        self.nombre = [
            line.replace('NAME: ', '') for line in lines if 'NAME: ' in line
        ][0].strip()
        self.filename = tsp_name
        self.dimension = int([
            line.partition('DIMENSION:')[2] for line in lines
            if 'DIMENSION: ' in line
        ][0])
        index_for_search = [
            index
            for index, line in enumerate(lines) if 'NODE_COORD_SECTION' in line
        ][0] + 1
        cities_data = lines[index_for_search:index_for_search + self.dimension]
        self.problema = {}
        for city in cities_data:
            idx, x, y = map(float, city.split(' '))
            self.problema[int(idx)] = (x, y)

        self.generate_graph()
        self.solution = list(self.problema.keys())
        print(f'Fichero {tsp_name} parseado con exito')
Example #26
0
    def test_read_file(self):
        """
        Test the function read_file
        """
        test_tools_file = os.path.abspath(__file__)
        test_directory = os.path.dirname(test_tools_file)
        non_existing_file = os.path.join(test_directory, "nonExistingFile")

        self.assertIsInstance(tools.read_file(test_tools_file), str)
        self.assertIsNone(tools.read_file(non_existing_file))

        with NamedTemporaryFile('wt') as tmp:
            tmp.write('foo\nbar')
            tmp.flush()
            self.assertIsInstance(tools.read_file(tmp.name), str)
            self.assertEqual(tools.read_file(tmp.name), 'foo\nbar')

        tmp_gz = NamedTemporaryFile().name
        with gzip.open(tmp_gz + '.gz', 'wt') as f:
            f.write('foo\nbar')
            f.flush()
        self.assertIsInstance(tools.read_file(tmp_gz), str)
        self.assertEqual(tools.read_file(tmp_gz), 'foo\nbar')
        os.remove(tmp_gz+ '.gz')
Example #27
0
# By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square
# number: 1296 = 36^2. What is remarkable is that, by using the same digital substitutions, the anagram,
# RACE, also forms a square number: 9216 = 96^2. We shall call CARE (and RACE) a square anagram word
# pair and specify further that leading zeroes are not permitted, neither may a different letter have
# the same digital value as another letter.
#
# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-
# thousand common English words, find all the square anagram word pairs (a palindromic word is NOT
# considered to be an anagram of itself).
#
# What is the largest square number formed by any member of such a pair?
#
# NOTE: All anagrams formed must be contained in the given text file.

from tools import read_file

words = read_file("euler0098_words.txt")

print words
Example #28
0
    def substitute_script_placeholders(self, file_path=None):
        """
        Substitute common '@@LFS_' placeholders in the provided script by 'file_path'.
        Fails if there is any placeholder pending.
        """
        # Run substitution twice to ensure composed placeholders get susbstitute
        substitution_rounds = 2

        # Substitute in buildscript by default
        if file_path is None:
            file_path = self.component_data_dict["buildscript_path"]

        # Generate setenv file path.
        # Remove BASE_DIRECTORY from path if we are not building the 'toolchain'
        setenv_script_path = os.path.realpath(os.path.join(
            self.component_data_dict["setenv_directory"],
            self.component_data_dict["setenv_filename"]))

        if self.component_data_dict["build_into_chroot"] is True:
            # If we are into the chroot, setenv.sh is located at root directory (/setenv.sh)
            # so we remove that part of the 'setenv_script_path' variable
            setenv_script_path = setenv_script_path.replace(config.BASE_DIRECTORY, "")

        # Placeholders to substitute
        substitution_list = ["@@LFS_SETENV_FILE@@",
                             setenv_script_path,

                             "@@LFS_COMPONENT_KEYNAME@@",
                             self.component_data_dict["key_name"],

                             "@@LFS_BUILDER_NAME@@",
                             self.component_data_dict["builder_name"],

                             "@@LFSBUILDER_SRC_DIRECTORY@@",
                             self.component_data_dict["lfsbuilder_src_directory"],

                             "@@LFSBUILDER_TMP_DIRECTORY@@",
                             self.component_data_dict["lfsbuilder_tmp_directory"],

                             "@@LFS_SOURCES_DIRECTORY@@",
                             self.component_data_dict["sources_directory"],

                             "@@LFS_BASE_DIRECTORY@@",
                             config.BASE_DIRECTORY,

                             "@@LFS_VERSION@@",
                             config.LFS_VERSION,

                             "&amp;",
                             "&",

                             "&gt;",
                             ">",

                             "&lt;",
                             "<",

                             "&quot;",
                             "\""]

        # Add component substitution list
        if self.component_data_dict["component_substitution_list"] is not None:
            substitution_list.extend(
                self.component_data_dict["component_substitution_list"]
            )

        # Remove BASE_DIRECTORY if not building 'toolchain'
        if self.component_data_dict["build_into_chroot"] is True:
            substitution_list.extend([config.BASE_DIRECTORY, ""])

        # Substitute
        i = 0
        while i < substitution_rounds:
            tools.substitute_multiple_in_file(file_path, substitution_list)
            # update loop index
            i += 1

        # Check there are not any pending placeholder
        text = tools.read_file(file_path)
        if text.find("@@LFS") != -1:
            printer.error("Found pending placeholder in '{f}'".format(f=file_path))
	def get_translations( self ):
		return tools.read_file( os.path.join( self.get_doc_path(), 'TRANSLATIONS' ) )
Example #30
0
# Player choses the path from first travel movement
import tools

welcome_file = 'Data\\narration\\Navigation\\dereth\\welcome_to_derith.txt'
choices_file = 'Data\\narration\\Navigation\\dereth\\derith_choices.txt'
burned_buildings_file = 'Data\\narration\\Navigation\\dereth\\derith_burned_buildings.txt'
court_file = 'Data\\narration\\Navigation\\dereth\\derith_court.txt'
inn_file = 'Data\\narration\\Navigation\\dereth\\derith_inn.txt'
theater_file = 'Data\\narration\\Navigation\\dereth\\derith_theater.txt'
all_knowing_ones_file = 'Data\\narration\\Navigation\\dereth\\derith_all_knowing_ones.txt'

# read the "welcome to derith" file to the player
tools.read_file(welcome_file, 1.5)

while True:

    # read the choices available to the player and record the players choice
    tools.read_file(choices_file, 1)
    response = input('What will you do?')

    # If the player chooses to investigate the burned buildings
    if 'burned buildings' in response.lower():
        tools.read_file(burned_buildings_file, 1.5)

    # if a player chooses to go into the court
    elif 'court' in response.lower():
        # open and read the court file
        tools.read_file(court_file, 1.5)

    # If player goes into the inn
    elif 'inn' in response.lower():
	def get_license( self ):
		return tools.read_file( os.path.join( self.get_doc_path(), 'LICENSE' ) )
	def get_authors( self ):
		return tools.read_file( os.path.join( self.get_doc_path(), 'AUTHORS' ) )
Example #33
0
 def get_authors(self):
     return tools.read_file(os.path.join(self.get_doc_path(), 'AUTHORS'))
import numpy as np
import tools as tl
import time

bl_size = 32
src = 'source/park.png'
dst = 'fig'
processor = 'gpu'

start = time.time()
img = tl.read_file(src)
img = tl.pad(img, bl_size)
shape = np.shape(img)
block = tl.break_block(img, bl_size)
predict, mode_predict = tl.inpainting(block, bl_size, processor = processor)
time_total = time.time() - start
print 'predict size:	', np.shape(predict)
print 'block size:	', np.shape(predict[0])
print 'max:	', np.max(predict)
print 'min:	', np.min(predict)
print time_total
predict = tl.group_block(predict, bl_size, shape)
#predict = np.uint8(predict * (255.0 / np.max(predict)))
#predict = np.uint8(predict)
#plt.imshow(predict, cmap = cm.Greys_r)

np.save(dst, predict)

print 'Done'

Example #35
0
 def get_license(self):
     return tools.read_file(os.path.join(self.get_doc_path(), 'LICENSE'))
def Ku_belenor():
    import os, sys, tools, time, Derith
    path = os.getcwd()
    sys.path.insert(0, path)

    # Variables
    read_speed = 1.5
    directory = 'Data\\narration\\Navigation\\ku_belenor\\'
    Telmundel_intro = directory + 'elvish_District\\Telmundel_intro.txt'
    if_elf = directory + 'elvish_District\\if_elf.txt'
    if_dwarf = directory + 'elvish_District\\if_dwarf.txt'
    Telmundel_continues = directory + 'elvish_District\\Telmundel_continues.txt'
    seaman_jim = directory + 'fish_markets\\seaman_jim.txt'
    govoners_file = directory + 'govoners_palace\\govonor.txt'
    slums_intro = directory + 'slums\\slums.intro.txt'
    if_rogue = directory + 'slums\\if_rogue.txt'
    intro_file = 'ku_belenor_intro.txt'
    choices_file = 'Ku_Belenor_choices.txt'
    inn_file = directory + 'Inn\\Inn_Intro.txt'
    if_hurt = directory + 'Inn\\if_hurt.txt'
    inn_conclusion = directory + 'Inn\\Inn_conclusion.txt'
    all_knowing_ones_file = directory + 'All_Knowing_Ones_booth\\brother_Ku_Belenor.txt'

    # Read the Ku Belenor intro
    tools.read_file(directory + intro_file, read_speed)

    # give the player an option to pick
    while True:
        tools.read_file(directory + choices_file, read_speed)
        print("\n")
        response = input("What will you do?")

        if 'elvish district' in response.lower():
            tools.read_file(Telmundel_intro, read_speed)
            race = tools.get_player_stat('Race')
            time.sleep(read_speed)
            # if the player is an elf, reward them
            if race == 'elf':
                tools.read_file(if_elf, read_speed)
                time.sleep(read_speed)
                tools.player_level_up()
            elif race == 'dwarf':
                tools.read_file(if_dwarf, read_speed)
            else:
                None
            time.sleep(read_speed)
            tools.read_file(Telmundel_continues, read_speed)

        elif 'fish market' in response.lower():
            time.sleep(read_speed)
            tools.read_file(seaman_jim, read_speed)

        elif 'governors palace' in response.lower():
            time.sleep(read_speed)
            tools.read_file(govoners_file, read_speed)

        elif 'slums' in response.lower():
            time.sleep(read_speed)
            tools.read_file(slums_intro, read_speed)
            if tools.get_player_stat('player_class') == 'rogue':
                tools.read_file(if_rogue, read_speed)
            else:
                time.sleep(read_speed)
                print("you find nothing of value")

        elif 'all knowing ones' in response.lower():
            time.sleep(read_speed)
            tools.read_file(all_knowing_ones_file, read_speed)

        elif 'inn' in response.lower():
            time.sleep(read_speed)
            tools.read_file(inn_file, read_speed)

            # If a players health is less than half full the barkeep will offer a health option
            if tools.player_hurt() == True:
                tools.read_file(if_hurt, read_speed)
                time.sleep(read_speed)
                tools.restore_player_hp()
            else:
                None

            tools.read_file(inn_conclusion, read_speed)
        elif 'derith' in response.lower():
            Derith.Derith()
        else:
            print('\n I am sorry, I did not understand you. \n')

        time.sleep(read_speed)
        print("\nyou return to the city\n")
Example #37
0
        Experiment.execute_compute(args.command)
        sys.exit()

    if "execute-controller" in args.commands:
        Experiment.execute_controller(args.command)
        sys.exit()

    if "execute-blocks" in args.commands:
        Experiment.execute_blocks(args.command)
        sys.exit()

    is_training = True
    if args.training_experiment_id > 0:
        is_training = False

    script_volume_clock_calc = tools.read_file("script_volume_clock_calc.py")
    script_volume_performance_meter_clock_calc = tools.read_file("script_volume_performance_meter_clock_calc.py")

    e = Experiment(
        is_shutdown=is_shutdown,
        debug_server_ip=args.debug_server_ip,
        debug_run_only_one_server=args.debug_run_only_one_server,
        add_new_experiment=args.new,
        print_output_if_have_error=args.print_output_if_have_error,
        print_output=args.print_output,
        config=json.dumps({
            "max_number_vols": args.max_number_vols,
            "learning_algorithm": args.learning_algorithm,
            "restart_controller_compute_bad_volume_count_threshold": 60,
            "number_of_servers_to_start_simulation": 40,
Example #38
0
# config mysql
# directory create init.d
tools.make_dir('init.d',os.path.join(mysql_path,'etc'))

# mysql_install_db
installdb_path = os.path.join(base['tar_base'],tools.filter(mysql_package),'scripts')
installdb_file = install_path + '/mysql_install_db'
installdb_options = """
--user=%s \
--defaults-file=%s \
--datadir=%s \
--basedir=%s
""" % (user_name,os.path.join(mysql_path,'etc') + '/my.cnf', os.path.join(mysql_path,'data'),mysql_path)
os.chmod(installdb_file, stat.S_IEXEC)
os.system('%s %s' % (installdb_file, installdb_options))

# mysql startup scripts and conf
for file in ['my.cnf','mysql.server']:
	temp_content = tools.read_file(cwd + '/' + file)
	if 'cnf' in file:
		temp_file = os.path.join(mysql_path, 'etc') + '/' + file
	elif 'server' in file:
		temp_file = os.path.join(mysql_path, 'etc','init.d') + '/' + file
	tools.write_file(temp_file, temp_content)
	os.chmod(temp_file,stat.S_IRWXU + stat.S_IRWXG)


# config
os.system('chown -R %s.%s %s' % (base['user_name'], base['user_name'], mysql_path))
os.system('chmod -R 755 %s' % mysql_path)
def get_archive():
    return apply_template(
        my_template=read_file("templates/comm_template.pyt"),
        fields=FIELDS,
        class_name="Archive",
    )
Example #40
0
 def get_translations(self):
     return tools.read_file(
         os.path.join(self.get_doc_path(), 'TRANSLATIONS'))
Example #41
0
--user=%s \
--group=%s \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-pcre=%s \
--with-openssl=%s \
--with-zlib=%s
""" % (nginx_path,nginx_path,base['user_name'],base['user_name'],pcre_path,openssl_path,zlib_path)

# configure
tools.pak_configure(base['soft_name'],tools.filter(nginx_package),base['soft_path'],base['tar_path'],options)

# change the Makefile to tend to adjust the init
makefile_fix = os.path.join(base['tar_path'],nginx_package,'/objs')
makefile = tools.read_file('makefile_fix' + '/Makefile')
result_1 = re.sub(r'./configure','./configure --prefix=/opt/lnmp/app/init',makefile)
result = re.sub(r'./configure --prefix=/opt/lnmp/app/init --disable-shared','./configure --prefix=/opt/lnmp/app/init',result_1)
tools.write_file(makefile_fix,result)

# make
tools.pak_make(tools.filter(nginx_package),base['tar_path'])

# config
for dir in ['sites-enabled','sites-available']:
	tools.make_dir(dir,os.path.join(nginx_path,'conf'))
tools.make_dir('bin',nginx_path)


for file in ['nginx.conf','nginx.sh','herouser_virtualhost']:
	temp_content = tools.read_file(cwd + '/' + file)
Example #42
0
import numpy as np
import tools as tl
import time

bl_size = 8
src = 'source/park.png'
dst = 'fig'
processor = 'gpu'

start = time.time()
img = tl.read_file(src)
img = tl.pad(img, bl_size)
shape = np.shape(img)
block = tl.break_block(img, bl_size)
predict, mode_predict = tl.inpainting(block, bl_size, processor=processor)
time_total = time.time() - start
print 'predict size:	', np.shape(predict)
print 'block size:	', np.shape(predict[0])
print 'max:	', np.max(predict)
print 'min:	', np.min(predict)
print time_total
predict = tl.group_block(predict, bl_size, shape)
#predict = np.uint8(predict * (255.0 / np.max(predict)))
#predict = np.uint8(predict)
#plt.imshow(predict, cmap = cm.Greys_r)

np.save(dst, predict)

print 'Done'
Example #43
0
def Derith():
    # Player choses the path from first travel movement
    import tools, Ku_Belenor

    Derith_file_path = 'Data\\narration\\Navigation\\dereth\\'
    welcome_file = Derith_file_path + 'welcome_to_derith.txt'
    choices_file = Derith_file_path + 'derith_choices.txt'
    burned_buildings_file = Derith_file_path + 'derith_burned_buildings.txt'
    court_file = Derith_file_path + 'derith_court.txt'
    inn_file = Derith_file_path + 'derith_inn.txt'
    theater_file = Derith_file_path + 'derith_theater.txt'
    all_knowing_ones_file = Derith_file_path + 'derith_all_knowing_ones.txt'
    read_speed = 1

    # read the "welcome to derith" file to the player
    tools.read_file(welcome_file, read_speed)

    while True:

        # read the choices available to the player and record the players choice
        tools.read_file(choices_file, read_speed)
        response = input('What will you do?')

        # If the player chooses to investigate the burned buildings
        if 'burned buildings' in response.lower():
            tools.read_file(burned_buildings_file, read_speed)
        # if a player chooses to go into the court
        elif 'court' in response.lower():
            # open and read the court file
            tools.read_file(court_file, read_speed)
        # If player goes into the inn
        elif 'inn' in response.lower():
            tools.read_file(inn_file, read_speed)
            tools.restore_player_hp()
        # if a player goes into the theater
        elif 'theater' in response.lower():
            tools.read_file(theater_file, read_speed)
        # if a player speaks to the all knowing ones booth
        elif 'all knowing ones' in response.lower():
            tools.read_file(all_knowing_ones_file, read_speed)
        # if a player choses to go to Ku Belenor
        elif 'ku belenor' in response.lower():
            print('\n You leave Derith and head north to Ku Belenor')
            Ku_Belenor.Ku_belenor()
        # if a player choses to go to Fay
        elif 'fay' in response.lower():
            print()
        # if a player choses to go to Wey
        elif 'way' in response.lower():
            print('You', response)
        # if a player does not enter a valid response
        else:
            print(
                'Im sorry, I dont understand what you want.'
                '\n Please choose: BURNED BUILDINGS, COURT, INN, THEATER, ALL KNOWING ONES, KU BELENOR, FEY, WAY'
            )
    return


# -----------------------------------------------------------------------
# DEBUG
#Derith()
Example #44
0
            utl.append([i, int(t)])
    return Node(nr, sorted(utl, key=lambda x:(x[1], x[0])))

def find(nodes_nrs, node_nr):
    for n in nodes_nrs,:
        if n == node_nr:
            return n
    return None
    
def is_loop(t):
    for n in mst:
        if n.nr == t:
            return True
    return False

data = read_file("euler0107_network.txt")

g = []
g_tot = 0
for i in range(0,len(data)):
    g.append(handle_node(i, data[i]))
for n in g:
    for e in n.edges:
        g_tot += e[1]
        n.connected_to.append(g[e[0]])
g_tot /= 2
# init tree
mst = []
mst.append(g[0])
g[0].in_mst = True
# done init
def get_publication():
    return apply_template(
        read_file("templates/comm_template.pyt"),
        fields=FIELDS,
        class_name="Publication",
    )