示例#1
0
def read_communities():
    global communities
    if proximatedir == None:
        warning('No Proximate directory\n')
        return

    # Read community meta datas
    for dentry in os.listdir(proximatedir):
        if not dentry.startswith('c_'):
            continue
        if str_to_int(dentry[2:], None) == None:
            continue
        cdir = '%s/%s' %(proximatedir, dentry)
        if not os.path.isdir(cdir):
            continue
        cfile = '%s/profile' %(cdir)

        community = Community()
        try:
            f = open(cfile, 'r')
        except IOError:
            continue
        profile = f.read()
        f.close()
        if community.read_profile(profile):
            communities[community.get('cid')] = community

    defcom = get_ordinary_community(DEFAULT_COMMUNITY_NAME)
    if defcom == None:
        create_community(DEFAULT_COMMUNITY_NAME)
示例#2
0
    def register(self, name, vtype, descr, default=None, validator=None):
        cfgname = get_config_name()
        c = new_config()
        value = None
        if len(c.read(cfgname)) != 0:
            value = get_option(c, CONFIG_SECTION, name, None, None)
        if vtype == str:
            pass
        elif vtype == bool:
            if value != None:
                value = value.upper()
            if value == '0' or value == 'NO' or value == 'FALSE':
                value = False
            elif value == '1' or value == 'YES' or value == 'TRUE':
                value = True
            else:
                value = None
        elif vtype == int:
            if value != None:
                value = str_to_int(value, None)

        if value == None:
            value = default

        s = Setting(name, vtype, descr, value, validator)
        self.settings.append(s)

        for cb in self.new_setting_cb:
            cb(s)
        return s
示例#3
0
def get_stadium_capacity(stadium_table):
    stadium_capacity = []
    for row in stadium_table.find_all('tr'):
        for cell in row.find_all('td', {'align': 'center'}):
            numeric_value = str_to_int(cell.text)
            stadium_capacity.append(numeric_value)
    return stadium_capacity
示例#4
0
    def parse_apartment_div(self, apt_div):
        title_element = apt_div.find("h2")
        title = title_element.find("a").text.strip()
        external_id_string = title_element.find("a").attrs['href']
        external_id = external_id_string.split("/")[3]
        url = title_element.find("a")
        base_url = 'https://www.nekretnine.rs'
        add_url = "".join([base_url, url.attrs['href']])
        image_parent_element = apt_div.find("picture")
        image_element = image_parent_element.find("img")
        image_url = image_element.attrs['src']
        multi_element = apt_div.find("p", {"class": "offer-price"})
        price_string = multi_element.find("span").text
        price = str_to_int(price_string.split(" ")[0])

        region = apt_div.find("p", {"class": "offer-location"}).text.strip()
        data = {
            "add_url": add_url,
            "title": title,
            "price": price,
            "external_id": external_id,
            "image_url": image_url,
            "region": region
        }
        return data
示例#5
0
    def parse_apartment_div(self, apt_div):
        external_id_element = apt_div.find("button", {"class": "fav-cmd"})
        external_id = external_id_element.attrs['data-id']
        title = apt_div.find("h3")
        url = title.find("a")
        base_url = 'https://www.halooglasi.com'
        add_url = "".join([base_url, url.attrs['href']])

        image_parent_element = apt_div.find("figure")
        image_element = image_parent_element.find("img")
        image_url = image_element.attrs['src']

        price = str_to_int(apt_div.find("span").attrs['data-value'])
        region_elements = apt_div.find("ul", {"class": "subtitle-places"})
        region_strings = [
            el.text.strip() for el in region_elements.findAll("li")
        ]
        region = ", ".join(region_strings)
        return {
            "add_url": add_url,
            "title": title.text,
            "price": price,
            "external_id": external_id,
            "image_url": image_url,
            "region": region
        }
示例#6
0
 def entry_focus_out(self, entry, event, s):
     value = entry.get_text()
     if s.vtype == int:
         value = str_to_int(value, None)
         if value == None:
             entry.set_text(str(s.value))
             return
     if value != s.value:
         if not s.set(value):
             entry.set_text(str(s.value))
示例#7
0
def ip_number(ip):
    fields = ip.split('.')
    if len(fields) != 4:
        return None
    ipnumber = 0
    for f in fields:
        ipnumber <<= 8
        val = str_to_int(f, -1)
        if val < 0 or val > 255:
            return None
        ipnumber += val
    return ipnumber
示例#8
0
    def validate(self):
        if not self.fields or len(self.fields) < 6:
            return False

        # 0. Check field lengths
        if len(self.fields[0]) != 20:
            return False

        if not (len(self.fields[1]) == 0 or len(self.fields[1]) == 20):
            return False

        if len(self.fields[2]) > MAX_CTIME_STR_LENGTH:
            return False

        if len(self.fields[5]) > MAX_MSG_STR_LENGTH:
            return False

        # 1. Check SHA1 sum
        m = hashlib.sha1()
        for f in self.fields[1:]:
            m.update(f)

        if m.digest() != self.fields[0]:
            return False

        # 2. Check addresses
        l = self.get_sender_addr().split(':')
        if len(l) != 2 or l[0] != 'u' or not valid_uid(l[1]):
            return False

        if not valid_addr(self.get_target_addr()):
            return False

        # 3. Check ctime
        l = self.get_ctime()
        if len(l) < 2:
            return False
        timet = str_to_int(l[0], -1)
        seqnumber = str_to_int(l[1], -1)
        return timet >= 0 and seqnumber >= 0
示例#9
0
def benefits_delete_profile():
	""" Receives (through form) the id of the benefit to be deleted. First the
	benefit id is checked and then deleted. Benefit is not truly deleted from database, 
	for it can still be used by other companies. Only the company's registration with
	that benefit is deleted """
	idBenefit = str_to_int(request.form.get("idBenefit"))
	if benefit_exists(idBenefit):
		delete_benefit_profile(idBenefit, session["idCompany"])
		return redirect("/beneficios/lista")
	else: 
		whoops = """Este perfil não existe, por favor selecione outro da lista."""
		benefits_list = CompanyProfile(session["idCompany"]).get_benefits()
		return render_template("benefits_list.html", header = get_header(session), 
								benefits_list = benefits_list, whoops = whoops)
示例#10
0
def is_cpu_reg(reg_name):
    if len(reg_name) < 2 or len(reg_name) > 2:
        return False
    if reg_name == "PC" or reg_name == "SR":
        return True
    elif reg_name.startswith("A") or reg_name.startswith("D"):
        flag,reg_num = utils.str_to_int(reg_name[1:2])
        if not flag:
            return False
        if reg_num >= 0 and reg_num <= 7:
            return True
        else:
            return False
    else:
        return False
示例#11
0
def people_delete_profile():
	""" Receives (through form) the id of the person to be deleted. First the
	person id is checked and then deleted. The person's row in the person table,
	and all other data connected to that person is also deleted. """
	idPerson = str_to_int(request.form.get("idPerson"))
	person_admin = PersonProfile(idPerson).get_admin()
	if person_admin['name'] != "Admin":
		delete_person_profile(idPerson)
		return redirect("/pessoas/lista")
	else: 
		whoops = """Este perfil não pode ser deletado, por favor selecione outra pessoa 
					da lista."""
		people_list = CompanyProfile(session["idCompany"]).get_people()
		return render_template("people_list.html", header = get_header(session), 
								people_list = people_list, whoops = whoops)
示例#12
0
    def read_config_section(self, c):
        if c.has_section(self.metasection) == False:
            return False
        self.reset_defaults(trusted=False)

        version = self.d['v']

        for (name, ma) in self.metaattributes.items():
            if ma.required and get_option(self.metasection, name) == None:
                warning('Missing required config attribute: %s\n' % name)
                return False

        for (name, value) in c.items(self.metasection):
            ma = self.metaattributes.get(name)
            if ma == None:
                continue
            if ma.public == False:
                warning('Ignoring %s:%s in %s\n' %(name, value, self.metasection))
                continue

            if ma.vtype == str:
                pass
            elif ma.vtype == bool:
                value = value.upper()
                if value == '0' or value == 'NO' or value == 'FALSE':
                    value = False
                elif value == '1' or value == 'YES' or value == 'TRUE':
                    value = True
                else:
                    continue
            elif ma.vtype == int:
                value = str_to_int(value, None)
                if value == None:
                    continue
            else:
                warning('Unknown vtype for %s in %s (type %s)\n' %(name, self.metasection, str(ma.vtype)))
                continue

            if self.set(name, value):
                if name == 'v':
                    version = value

        self.d['v'] = version
        return True
示例#13
0
def people_data_registration():
	""" This function simply registers the additional data for person submitted by calling 
	register_data_to_person() and returns the persons updated profile """
	idPerson = str_to_int(request.form.get("idPerson"))
	ids_datatype = str_list_to_int(request.form.getlist("idDatatype"))
	data_values = request.form.getlist("data_value")
	if len(ids_datatype) > 0 and len(data_values) > 0:
		for i in range(len(data_values)):
			if ids_datatype[i] not in [1, 2, 3]: # reserved data types
				try:
					register_data_to_person(ids_datatype[i], data_values[i], idPerson)
				except:
					update_data_from_person(ids_datatype[i], data_values[i], idPerson)
		return redirect("/pessoas/perfil/{}".format(idPerson))
	else:
		whoops = "Você não terminou o cadastro. Clique no plano selecionado e termine o cadastro."
		profile = PersonProfile(idPerson).get_profile()
		return render_template("people_profile.html", header = get_header(session),
													profile = profile, whoops = whoops)
def get_integer_option(c, section, option, default=None):
    value = get_option(c, section, option)
    if value == None:
        return default
    return str_to_int(value, default)
示例#15
0
def test_str_to_int_float():
    assert str_to_int("52.2") == 52
示例#16
0
def test_str_to_int_commas():
    assert str_to_int("1,100,700.54") == 1100700
示例#17
0
def test_str_to_int():
    assert str_to_int("52") == 52
示例#18
0
def test_str_to_int_comma():
    assert str_to_int("52,2") == 52
示例#19
0
def get_by_key(session_key):
    if not session_key:
        return 0
    return utils.str_to_int(share_redis().hget(key.ONLINE, session_key))
示例#20
0
        if inp_str == "":
            if prev_cmd != "":
                inp_str = prev_cmd
            else:
                continue

        prev_cmd = inp_str

        words = inp_str.split()
        cmd = words[0]

        if cmd == "quit":
            pass
        elif cmd == "step" or cmd == "si":
            if len(words) == 2:
                flag,count = utils.str_to_int(words[1])
                if not flag:
                    print("Invalid instruction count %s" % words[1])
                    continue
            else:
                count = 1
            rt.get_cpu().set_instr_hook_func(instr_hook)
            for i in range(count):
                rt.run()
            rt.get_cpu().set_instr_hook_func(None)
        elif cmd == "until":
            if len(words) < 2:
                print("Missing parameter")
                continue
            flag,addr = utils.str_to_int(words[1])
            if not flag:
示例#21
0
def read_input(debugging):
    try:
        file = sys.argv[1]
        allocated_time = str_to_int(sys.argv[2])
        heuristic_function = str_to_int(sys.argv[3])
        algorithm: AlgorithmType = AlgorithmType(
            int_to_algorithm_enum(str_to_int(sys.argv[4])))
        sol_file = F_INPUT_DOUBLE_A_STAR_BOARDS
        steps_file = F_INPUT_OPTIMAL_SOLUTIONS
        if heuristic_function not in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
            raise HeuristicFunctionException(
                "Incorrect Heuristic function entered, was: {}".format(
                    heuristic_function))
    except IndexError:
        if debugging == 1:
            # default values for debugging
            file = F_INPUT_GAME_INPUT_FILE
            sol_file = F_INPUT_DOUBLE_A_STAR_BOARDS
            steps_file = F_INPUT_OPTIMAL_SOLUTIONS
            allocated_time = ALLOCATED_TIME
            heuristic_function = HEURISTIC_FUNCTION
            algorithm: AlgorithmType = DEBUGGING_ALGORITHM
            if heuristic_function not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
                raise HeuristicFunctionException(
                    "Incorrect Heuristic function entered, was: {}".format(
                        heuristic_function))
        else:
            red = '31m'
            print(
                display_colored_text(
                    red, "Err: Did you initiate the program correctly?"))
            print(
                display_colored_text(
                    red,
                    "Usage: python [main file name] [input games] [timeout] [heuristic function 1/2/4, or 3(DLS)] [algorithm index 1-4]"
                ))
            print(
                display_colored_text(
                    red, "Example: python game.py ./Data/rh.txt 7 1"))
            yellow = '34m'
            print(
                display_colored_text(
                    yellow,
                    "Notice: heuristic = 1 checks number of cars blocking the red one from exiting"
                ))
            print(
                display_colored_text(
                    yellow,
                    "Notice: heuristic = 2 checks number of cars blocked on the red car row"
                ))
            exit(1)
    except HeuristicFunctionException as e:
        red = '31m'
        print(
            display_colored_text(
                red, "Err: Did you initiate the program correctly?"))
        print(
            display_colored_text(
                red,
                "Usage: python [main file name] [input games] [timeout] [heuristic function 1/2, or 3(DLS)]"
            ))
        print(
            display_colored_text(red,
                                 "Example: python game.py ./Data/rh.txt 7 1"))
        yellow = '34m'
        print(
            display_colored_text(
                yellow,
                "Notice: heuristic = 1 checks number of cars blocking the red one from exiting"
            ))
        print(
            display_colored_text(
                yellow,
                "Notice: heuristic = 2 checks number of cars blocked on the red car row"
            ))
        print(display_colored_text(red, e))
        exit(1)

    with open(file, 'r') as f:
        contents = f.readlines()
    with open(sol_file, 'r') as f:
        sol_contents = f.readlines()
    for i in range(40):
        sol_contents[i] = sol_contents[i].split('\n')[0]
    with open(steps_file, 'r') as f:
        steps_contents = f.readlines()
    list_of_dic = []
    for i in range(40):
        steps_contents[i] = steps_contents[i].split('\n')[0]
        steps_list_per_game = steps_contents[i].split(' ')
        game_hash_map = {}
        step_number = 0
        for step in steps_list_per_game:
            if step == '':
                continue
            game_hash_map[GameAction(step[0], get_direction_by_str(step[1]),
                                     int(step[2]), step_number,
                                     0)] = step_number
            step_number += 1
        list_of_dic.append(game_hash_map)

    input_games = []
    i = contents.index('--- RH-input ---\n')
    for j in range(i + 1, contents.index('--- end RH-input ---\n')):
        input_games.append(contents[j].split('\n')[0])
    return input_games, allocated_time, heuristic_function, algorithm, sol_contents, list_of_dic
示例#22
0
    if len(sys.argv) > 1:
        mfs_img_file = os.path.abspath(sys.argv[1])
    else:
        print('Please specify a MSF image to continue.')
        exit(1)

    with open(mfs_img_file, 'rb') as mfs_file:
        mfs_vol = MFSVolume(mfs_file)
        if mfs_vol.list_files() == 0:
            exit(1)

        file_num = 0
        while file_num == 0:
            print("Please enter file number to extract resource fork from:")
            inp_str = input("> ")
            flag, file_num = utils.str_to_int(inp_str)
            if not flag:
                file_num = 0
            if not mfs_vol.get_fork_size(file_num, 1):
                file_num = 0

        print("Please enter file name to write data to:")
        file_name = input("> ")

        with open(file_name, 'wb') as dst_file:
            data = mfs_vol.read_fork(file_num,
                                     1,
                                     mfs_vol.get_fork_size(file_num, 1),
                                     pos=0)
            dst_file.write(data)