예제 #1
0
def get_data():
    page_data = defaultdict(dict)
    for page in all(api.page.get):
        pagename = page['name']
        for k, v in extract_attributes(page['content']).iteritems():
            page_data[pagename][normalize_key(k)] = normalize_value(v)
    return page_data
예제 #2
0
 def verify(self, entry):
     if self.__isCompiled:
         d1 = self.groupdict(entry)
         line = self.substitute(d1).replace('\\', '')
         d2 = self.groupdict(line)
         tvs = []
         for name in self.regex_dict.keys():
             if d1[name] is None or d2[name] is None:
                 return False
             tvs.append(d1[name] == d2[name])
         return all(tvs)                    
     else:
         raise 'RegTemplate object must be compiled'
예제 #3
0
def determine_fields(valid_tickets: List[List[int]], rules):
    ticket_len = len(valid_tickets[0])
    # Might have to determine what's only available I guessed that would happen
    ticket_mappings = defaultdict(list)
    for rule_name, rule in rules.items():
        for field in range(ticket_len):
            if all([
                    rule[0] <= ticket[field] <= rule[1]
                    or rule[2] <= ticket[field] <= rule[3]
                    for ticket in valid_tickets
            ]):
                ticket_mappings[rule_name].append(field)
    return ticket_mappings
def run():
    global SITE_URL, API_KEY, USERNAME, GEOCODE_SUFFIX

    SITE_URL = raw_input("Enter URL of LocalWiki instance: ").strip()
    API_KEY = raw_input("Enter API key: ").strip()
    USERNAME = raw_input("Enter API username: "******"""What suffix should we use for geocoding?'
E.g. "San Francisco, California" or "Detroit, Michigan": """)

    api = slumber.API(urljoin(SITE_URL, '/api/'))
    geocoder = geocoders.Google()

    for page in all(api.page.get):
        if should_geocode(page['name'], api):
            try:
                place, (lat, lng) = geocoder.geocode(
                    pagename_for_geocoding(page['name']))
            except:
                continue
            add_map(page, lat, lng, api)
예제 #5
0
def part2_brute_force(data):
    """There is a simple solution here but I can't think of it. I know I've seen it before"""
    timestamp, bus_lines = data.splitlines()
    departures = [
        _ for _ in ((t, bus) for t, bus in enumerate(bus_lines.split(","))
                    if bus) if _[1] != 'x'
    ]
    found = False
    # get start counts
    times = [
        _[0] for _ in sorted(departures, key=lambda x: x[1], reverse=True)
    ]
    departures = [
        int(_[1]) for _ in sorted(departures, key=lambda x: x[1], reverse=True)
    ]
    # use largest value
    check_value = departures[0]
    i = 0
    while not found:
        i += 1
        check_value += departures[0]
        if all([(check_value - times[0] + times[t]) % departures[t] == 0
                for t in range(len(times))]):
            return check_value - times[0]
예제 #6
0
for l in lines:
    if l.startswith('debugstop'):
        break
    tkt = list(map(int, l.split(',')))
    # eprint(tkt, 'INVALID' if is_invalid(tkt) else 'ok')

    if is_invalid(tkt):
        continue

    filter_idx(tkt)

# eprint('-'*50)
# for k, v in possible.items():
# 	eprint(k.ljust(25), len(v), v)

assert all(possible.values()), 'filtered too many'

# simplify
found = set()
while any(len(s) > 1 for s in possible.values()):
    for s in possible.values():
        if len(s) == 1:
            v = next(iter(s))
            if v not in found:
                found.add(v)
                ss = s
                break

    for s in possible.values():
        if s is not ss:
            if v in s:
예제 #7
0
data = fin.read().split('\n\n')

fields = [
    'byr',
    'iyr',
    'eyr',
    'hgt',
    'hcl',
    'ecl',
    'pid',
    # 'cid'
]

ok = 0
for x in data:
    if all((f + ':') in x for f in fields):
        ok += 1

advent.print_answer(1, ok)

# byr (Birth Year) - four digits; at least 1920 and at most 2002.
# iyr (Issue Year) - four digits; at least 2010 and at most 2020.
# eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
# hgt (Height) - a number followed by either cm or in:
# If cm, the number must be at least 150 and at most 193.
# If in, the number must be at least 59 and at most 76.
# hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
# ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
# pid (Passport ID) - a nine-digit number, including leading zeroes.
# cid (Country ID) - ignored, missing or not.
예제 #8
0
파일: day23.py 프로젝트: oabm/aoc
			outpkts[addr] = []

	return vm_write


vms = [IntcodeVM(prog) for _ in range(50)]

for i, vm in enumerate(vms):
	vm.read = vmr(i)
	vm.write = vmw(i)

for vm in vms:
	vm.reset()

while not all(idle):
	for vm in vms:
		vm.run(n_in=1, resume=True)
		if all(idle):
			break

last_nat_y = natpkt[1]
advent.submit_answer(1, last_nat_y)


last_nat_y = None
done = False

while not done:
	for vm in vms:
		vm.run(n_in=1, resume=True)
예제 #9
0
    def delete_directory(path, conditions=None):
        if not all([c(path) for c in conditions]):
            return False

        shutil.rmtree(path)
        return True
예제 #10
0
    def delete_file(path, conditions=None):
        if not all([c(path) for c in conditions]):
            return False

        os.remove(path)
        return True
def remove_info_tables():
    # TODO: use the info data to infer what pages to run this on
    for page in all(api.page.get):
        pagename = page['name']
예제 #12
0
pot = [sum(map(abs, m)) for m in moons]
kin = [sum(map(abs, m)) for m in vels]
tot = sum(p * k for p, k in zip(pot, kin))

advent.submit_answer(1, tot)

moons = [[-7, 17, -11], [9, 12, 5], [-9, 0, -4], [4, 6, 0]]

vels = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

history = [set() for _ in range(3)]
periods = [0] * 3
found = [False] * 3
steps = 0

while not all(found):
    # if steps % 10000 == 0:
    # 	print(steps, periods)

    for dim in range(3):
        x = tuple((m[dim], v[dim]) for m, v in zip(moons, vels))

        if not found[dim] and x in history[dim]:
            periods[dim] = steps
            found[dim] = True
        else:
            history[dim].add(x)

    accels = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

    for i in range(4):
예제 #13
0
def main(user, validateString):
        retVal = option()
        #Upload
        if retVal == 1:
            dialog = xbmcgui.Dialog()
            dp = xbmcgui.DialogProgress()
            dp.create("TLBB Backup","Archiving backup ...",'', 'Please Wait')

            backup_name      =  searchKeywordBox('Please Enter Keyword')
            if backup_name == "":
                backup_name      =  searchKeywordBox('Please Enter Keyword')
                if backup_name == "":
                    return
            backup_password  =  searchKeywordBox('Please Enter password')
            if backup_password == "":
                backup_password  =  searchKeywordBox('Please Enter password')
                if backup_password == "":
                        return

            folder  =  xbmc.translatePath(os.path.join('special://home',''))
            if backup.is_exist(user, validateString, backup_name):
	        ans = dialog.yesno("TLBB Backup","Backup with same name already exist Want to overwrite?")
                if ans:
                    #Ask only two times for wrong password
                    for count in 1, 2:
               	        ret_val = backup.upload_wrapper(dp, user, validateString, backup_name,backup_password,1)
			utils.DBG(ret_val)
                        if ret_val == utils.WRONG_PASSWORD:
                            dialog.ok("Wrong password","Please re enter password...")
                            backup_password  =  searchKeywordBox('Please Enter password')
                        if backup_password == "":
                            dialog.ok("LBB Backup","Blank password","Please retry")
                            break
                        if ret_val in [utils.UPLOAD_PROGRESS_FAILED, utils.UPLOAD_FILE_WRITE_FAILED, utils.UPLOAD_INVALID_FILE, utils.UPLOAD_FAILED]:
                            dialog.ok("LBB Backup","Keyword: " + backup_name ,"Upload Failed")
                            break
                        if ret_val == "ok" :
                            dialog.ok("TLBB Backup","Keyword: " + backup_name ,"Backup uploaded successfully")
                            break
                else:
                    dialog.ok("TLBB Backup","Keyword: " + backup_name ,"Failed")
            else :
                try:
                    ret_val = backup.upload_wrapper(dp, user, validateString, backup_name,backup_password,0)
                    utils.DBG(ret_val)
                    errorList = [utils.UPLOAD_PROGRESS_FAILED, utils.UPLOAD_FILE_WRITE_FAILED, utils.UPLOAD_INVALID_FILE, utils.UPLOAD_FAILED]
                    if ret_val in errorList:
                        dialog.ok("LBB Backup","Keyword: " + backup_name ,"Upload Failed")
                    else if ret_val == "ok":
                        dialog.ok("TLBB Backup","Keyword: " + backup_name ,"Backup uploaded successfully")
                    else:
                        dialog.ok("LBB Backup","Keyword: " + backup_name ,"Upload Failed...")
                except Exception as e:
                    print e

        #Download
        if retVal == 0:
            dialog = xbmcgui.Dialog()      
            dp = xbmcgui.DialogProgress()
            dp.create("TLBB Restore","Downloading ",'', 'Please Wait')
            keyword      =  searchKeywordBox("Please Enter Keyword")
            if backup.is_exist(user, validateString, backup_name):
	            url ='http://backups.thelittleblackbox.com/'+keyword + '.tar.gz'
	            path         =  xbmc.translatePath(os.path.join('special://home/addons','packages'))
	            lib          =  os.path.join(path, keyword+'.tar.gz')
	            addonfolder  =  xbmc.translatePath(os.path.join('special://home',''))
	            
	            downloader.download(url,lib)
	            
	            dp.update(0,"", "Extracting Zip Please Wait")
	            
		    utils.all(lib,addonfolder,dp)
		    print "######################Jadav: Copying guisettings.xml ##############################"
	            guisetting_path = xbmc.translatePath(os.path.join('special://profile','guisettings.xml'))
	            guisetting_tlbb_path = xbmc.translatePath(os.path.join('special://profile','guisettings_tlbb.xml'))
		    shutil.copyfile(guisetting_path, guisetting_tlbb_path)
	            xbmc.executebuiltin('UpdateLocalAddons')
	            xbmc.executebuiltin( 'UpdateAddonRepos' )
		    os.remove(lib)
	            ret = dialog.yesno("All Done", "[COLOR yellow]Please be patient to complete installation we will restart XBMC. Brought To You By TLBB[/COLOR]")
                    if ret:
                        subprocess.call(["reboot"])
            else:
                dialog.ok("TLBB Restore","Invalid Keyword: No backup with given name exist")