Exemplo n.º 1
0
    def do_compute(self):
        # step 1, get prompt information from web source
        words_hint = TextHelper.find_text_between_tag(self.web_source, "<!-- ", " -->")
        print words_hint
        img_url_short = TextHelper.find_text_between_tag(self.web_source, "<img src=\"", "\" border=")
        ImageHelper.show_image_from_web(WebHelper.join_url(self.url, img_url_short))
        # It shows a same picture with different brightness
        print "brightness"
        prompt_url = WebHelper.join_url(self.url, "brightness")
        print "get new prompt url: %s" % prompt_url

        # step 2, download gz file from web
        prompt_url = WebHelper.get_prompt_url_from_web(prompt_url, "<!-- maybe consider ", " -->")
        local_gz = WebHelper.get_url_page(prompt_url)
        WebHelper.download_with_auth(prompt_url, local_gz)

        # step 3, get png data and show the image
        gz_content = FileHelper.read_gzip_file(local_gz)
        png = T18.get_png_data_from_diff_data(gz_content)

        for i in range(3):
            ImageHelper.show_image_from_data(png[i])

        # from image, we can see "../hex/bin.html", "butter", "fly"  ==> These last two words will be used in next level
        prompt_url = "../hex/bin.html"
        print 'we can see "../hex/bin.html", "butter", "fly" in these image, set new user, password for next level'
        self.result.set_user_password("butter", "fly")

        # step 4, set prompt
        self.set_prompt(prompt_url)

        # step 5, clean zip file
        FileHelper.remove_file(local_gz)
 def test_make_qrcode(self):
     dest = os.path.join(settings.MEDIA_ROOT, 'test_data',
                         'qrcode_test.jpg')
     ImageHelper.make_qrcode('QR Code Test', dest)
     self.assertTrue(os.path.exists(dest))
     os.remove(dest)
     self.assertFalse(os.path.exists(dest))
    def get_property_image_file_url(file_oid, org_file_name, cache_file_name,
                                    water_mark, max_size):
        """ 建物、部屋の画像のURLの取得 """

        CacheFileHelper.__prepare_cache_dir()
        cache_path = os.path.join(settings.CACHE_FILE_DIR, 'buildings',
                                  file_oid)
        cache_path = re.sub(r'\.+' + repr(os.sep), '', cache_path)
        cache_url = urljoin(settings.CACHE_FILE_URL,
                            "./buildings/" + file_oid + "/")
        if not os.path.isdir(cache_path):
            os.makedirs(cache_path)

        cache_file_url = None
        org_file_path = os.path.join(settings.ORIGINAL_FILE_DIR, 'buildings',
                                     file_oid, 'pictures', org_file_name)
        org_file_path = re.sub(r'\.+' + repr(os.sep), '', org_file_path)
        if os.path.isfile(org_file_path):
            cache_file_path = os.path.join(cache_path, cache_file_name)
            cache_file_path = re.sub(r'\.+' + repr(os.sep), '',
                                     cache_file_path)
            cache_file_url = urljoin(cache_url, cache_file_name)
            if not os.path.isfile(cache_file_path):
                ImageHelper.cache_image(org_file_path, cache_file_path,
                                        water_mark, max_size)

        return urljoin(settings.BASE_URL, cache_file_url)
 def test_cache_image(self):
     src_path = os.path.join(settings.MEDIA_ROOT, 'test_data',
                             'sample_picture.jpg')
     cache_test_dir = os.path.join(settings.CACHE_FILE_DIR, 'test_data')
     os.makedirs(cache_test_dir)
     cache_path = os.path.join(cache_test_dir, 'cache_test_picture.jpg')
     ImageHelper.cache_image(src_path, cache_path, 'YWorks',
                             settings.MEDIUM_IMAGE_SIZE)
     self.assertTrue(os.path.exists(cache_path))
     shutil.rmtree(cache_test_dir)
Exemplo n.º 5
0
    def form_valid(self, form):
        if settings.DEMO:
            messages.error(self.request, 'DEMOモードのため追加できません。')
        elif self.request.method == 'POST':
            if self.room:
                picture_type_id = self.request.POST['picture_type']
                picture_type = PictureType.objects.get(pk=picture_type_id)

                file_name = None
                if self.request.FILES['image']:
                    image = Image.open(self.request.FILES['image'])
                    file_name = MediaHelper.get_uuid_filename(
                        self.request.FILES['image'].name)

                    file_path = MediaHelper.get_upload_picture_path(
                        self.room.building, file_name)
                    ImageHelper.save_image(image, file_path,
                                           settings.ORIGINAL_IMAGE_SIZE)

                    thumbnail_path = MediaHelper.get_picture_thumbnail_path(
                        file_path)
                    ImageHelper.save_image(image, thumbnail_path,
                                           settings.THUMBNAIL_IMAGE_SIZE)

                if picture_type and file_name:
                    data = RoomPicture()
                    data.picture_type = picture_type
                    data.file_name = file_name
                    data.cache_name_thumb = MediaHelper.get_uuid_filename(
                        file_name)
                    data.cache_name_s = MediaHelper.get_uuid_filename(
                        file_name)
                    data.cache_name_m = MediaHelper.get_uuid_filename(
                        file_name)
                    data.cache_name_l = MediaHelper.get_uuid_filename(
                        file_name)
                    data.cache_name_org = MediaHelper.get_uuid_filename(
                        file_name)
                    data.building = self.room.building
                    data.room = self.room
                    data.is_publish_web = False
                    data.is_publish_vacancy = True

                    data.created_at = timezone.now()
                    data.created_user = self.user
                    data.updated_at = timezone.now()
                    data.updated_user = self.user

                    data.save()
                    self.room_picture = data
                    messages.success(self.request, '追加しました。')
                else:
                    raise ValueError

        return super().form_valid(form)
Exemplo n.º 6
0
    def do_compute(self):
        # step 1, get picture from web source
        prompt_url = TextHelper.find_text_between_tag(self.web_source, "<img src=\"", "\" border=\"0\"/>")
        cookie_img_url = WebHelper.join_url(self.url, prompt_url)
        ImageHelper.show_image_from_web(cookie_img_url)  # Do you feel familiar with the embed picture? Yes, the level 4
        level_4_start_url, ignore_content = WebHelper.get_final_url_content("http://www.pythonchallenge.com/pc/def/linkedlist.html")
        print "python challenge level 4 start url: " + level_4_start_url

        # step 2, get traverse start url
        cookies, level_4_web_source = WebHelper.get_cookie_content_from_url(level_4_start_url)
        cookie_prompt = ''.join(cookies)  # you+should+have+followed+busynothing...
        print "prompt from start web cookie: " + cookie_prompt
        new_para = TextHelper.find_text_between_tag(cookie_prompt, "have followed ", "...")
        print "get new para from cookie prompt: " + new_para
        origin_start_url = TextHelper.find_text_between_tag(level_4_web_source, "<center>\n<a href=\"", "\">")
        print "get origin start url: " + origin_start_url
        start_url = WebHelper.join_url(level_4_start_url, origin_start_url.replace("nothing", new_para))
        print "replace with new para, get final start url: " + start_url

        # step 3, get traverse start url
        cookies_collect = WebHelper.get_traverse_cookie(start_url, "and the next busynothing is ")
        compressed_message =  ''.join(cookies_collect)
        print "Get compressed message from cookies: " + compressed_message

        # step 4, uncompress message
        message = bz2.decompress(compressed_message)
        print "decompressed messsage: %s" % message
        # decompressed messsage: is it the 26th already? call his father and inform him that "the flowers are \
        # on their way". he'll understand.
        his_father = "Leopold"
        message = TextHelper.find_text_between_tag(message, "call his father and inform him that \"", "\". he'll ")

        # step 5, call his father
        his_father = "Leopold"
        phone_book_url = "http://www.pythonchallenge.com/pc/phonebook.php"
        phone = xmlrpclib.ServerProxy(phone_book_url)
        number = phone.phone(his_father)
        print "%s number is %s" % (his_father, number)  # Leopold number is 555-VIOLIN
        ignore_url, violin_content = WebHelper.get_auth_url_content(WebHelper.join_url(self.url, "violin"))
        print violin_content
        violin_url = TextHelper.find_pattern_in_content(violin_content, "no! i mean yes! but (.*php)")[0]
        print "violin url is %s" % violin_url
        leopold_url = WebHelper.join_url(self.url, violin_url)

        # step 6, send the message
        opener = urllib2.build_opener()
        message = "the flowers are on their way"
        opener.addheaders.append(('Cookie', 'info=' + quote_plus(message)))
        response = opener.open(leopold_url)
        leopold_prompt = response.read()

        # step 7, set next level prompt
        final_prompt = TextHelper.find_text_between_tag(leopold_prompt, "t you dare to forget the ", ".</font>")
        self.set_prompt(final_prompt)
Exemplo n.º 7
0
    def do_compute(self):
        # step 1, get information from web source
        web_message = TextHelper.find_text_between_tag(self.web_source,
                                                       '"gold"/>\n', '\n')
        print web_message
        print TextHelper.find_text_between_tag(self.web_source, '"> <!-- ',
                                               '-->')
        print 'Prompt us to send email to leopold!\n'
        leopold_email_address = '*****@*****.**'
        leo_mail = Email(None, leopold_email_address, 'Apology', 'Sorry!')
        EmailHelper.send_mail(leo_mail)
        try:
            leo_response = EmailHelper.get_latest_email(leopold_email_address)
            if leo_response is not None:
                print "Response email content: %s" % leo_response.get_payload()
        except error:
            print "This may be timeout from out of mainland china!"
            print "You can check from web to get this email content."
        print ''' Email content:
        # Never mind that.
        #
        # Have you found my broken zip?
        #
        # md5: bbb8b499a0eef99b52c7f13f4e78c24b
        #
        # Can you believe what one mistake can lead to?'''

        # step 2, decode mybroken.zip
        zip_file = 'mybroken.zip'
        repair_file = 'repair.zip'
        local_dir = 'repair'
        md5 = 'bbb8b499a0eef99b52c7f13f4e78c24b'
        data = array.array('c', open(zip_file, 'rb').read())
        if not T26.fix(data, md5):
            print "Can not fix %s!" % zip_file
        FileHelper.save_to_zip_file(data, repair_file)
        FileHelper.unzip_to_directory(repair_file, local_dir)

        # step 3, set prompt words
        ImageHelper.show_from_file(local_dir + "/mybroken.gif")
        prompt_words = 'speed' + string.split(web_message, ' ')[-1]
        print "Get words %s from picture!" % prompt_words
        self.set_prompt(prompt_words)

        # step 4, clean unused file
        FileHelper.remove_file(repair_file)
        FileHelper.remove_folder(local_dir)
        FileHelper.remove_file('readme.txt')
        FileHelper.remove_file(zip_file)
Exemplo n.º 8
0
    def do_compute(self):
        # step 1, get prompt information from web source
        print TextHelper.find_text_between_tag(self.web_source, '<!-- ', '-->')
        wav_suffix = 'wav'
        print "Above prompt words ask us to replace the suffix of jpg to %s" % wav_suffix
        wave_img_url = WebHelper.join_url(
            self.url,
            TextHelper.find_text_between_tag(self.web_source, '<img src="',
                                             '">'))
        print "wave image web url is %s" % wave_img_url
        ImageHelper.show_image_from_web(
            WebHelper.join_url(self.url, wave_img_url), self.user,
            self.password)
        print "This picture prompt us: there is 25 block, we need to combine them"

        # step 2, download waves
        wave_url = WebHelper.change_suffix_url(wave_img_url, wav_suffix)
        print "After change suffix: %s" % wave_url
        local_directory = 't25'
        FileHelper.mkdir(local_directory)
        waves = []
        for i in range(25):
            store_path = FileHelper.join_path(local_directory,
                                              WebHelper.get_url_page(wave_url))
            WebHelper.download_with_auth(wave_url, store_path, self.user,
                                         self.password)
            waves.append(wave.open(store_path))
            wave_url = WebHelper.url_add(wave_url)

        # step 3, Create combine image from waves
        img = Image.new('RGB', (300, 300), 'black')
        frames = waves[0].getnframes()
        print "Totally waves: %d" % len(waves)
        for i in range(len(waves)):
            tmp_img = Image.frombytes('RGB', (60, 60),
                                      waves[i].readframes(frames))
            current_pos = (60 * (i % 5), 60 * (i // 5))
            print "Put image to position%s" % str(current_pos)
            img.paste(tmp_img, current_pos)
        img.show()  # It shows a words 'decent'

        # step 4, set prompt words
        prompt_word = 'decent'
        print "Get prompt words from combined picture: %s" % prompt_word
        self.set_prompt(prompt_word)

        # step 5, clean unused file
        FileHelper.remove_folder(local_directory)
Exemplo n.º 9
0
    def do_compute(self):
        # step 1, get information from web source
        print TextHelper.find_text_between_tag(self.web_source, '<title>',
                                               '</title>')
        print "words above indicate us to explore the maze from top to bottom"

        maze_prompt = TextHelper.find_text_between_tag(self.web_source,
                                                       '<img src="', '">')
        maze_img = ImageHelper.create_image_from_web(
            WebHelper.join_url(self.url, maze_prompt), self.user,
            self.password)
        width, height = maze_img.size

        print "Find entrance in the top"
        for i in range(width):
            if maze_img.getpixel((i, 0))[2] == 0:
                entrance = (i, 0)
                print "(width=%d, height=0), pixel=(%s)" % (
                    i, maze_img.getpixel(entrance))
                break

        print "Find export at the bottom"
        for i in range(width):
            if maze_img.getpixel((i, height - 1))[2] == 0:
                export = (i, height - 1)
                print "(width=%d, height=%d), pixel=(%s)" % (
                    i, height - 1, maze_img.getpixel(export))

        # step 2, get out of the maze
        queue = T24.go_maze(maze_img, entrance, export)

        # step 3, get information from path
        zip_file = 'maze.zip'
        open('maze.zip', 'wb').write(''.join(
            [chr(maze_img.getpixel(pos[0])[0]) for pos in queue[1::2]]))
        FileHelper.unzip_to_directory(zip_file, '.')

        # step 4, get prompt information from picture
        maze_jpg = 'maze.jpg'
        ImageHelper.show_from_file(maze_jpg)
        prompt_words = 'lake'
        print "Get %s in the picture" % prompt_words
        self.set_prompt(prompt_words)

        # step 5, clean unused files
        FileHelper.remove_file(maze_jpg)
        FileHelper.remove_file(zip_file)
Exemplo n.º 10
0
    def do_compute(self):
        # step 1, get information from web source
        bell_url = TextHelper.find_text_between_tag(self.web_source,
                                                    '<a href="', '">')
        bell_url = WebHelper.join_url(self.url, bell_url)
        print "Find some url: %s" % bell_url
        zigzag_jpg = TextHelper.find_text_between_tag(self.web_source,
                                                      '<img src="', '"> <!--')
        zigzag_jpg = WebHelper.join_url(self.url, zigzag_jpg)
        print "Find a picture: %s" % zigzag_jpg
        gif_prompt = TextHelper.find_text_between_tag(self.web_source,
                                                      'did you say ', '? -->')
        gif_url = WebHelper.change_suffix_url(zigzag_jpg, gif_prompt)
        print "Get a gif picture: %s" % gif_url

        # step 2, deal with gif
        img = ImageHelper.create_image_from_web(gif_url, self.user,
                                                self.password)
        img_content = img.tobytes()
        img_plt = img.palette.getdata()[1][::3]
        trans = string.maketrans("".join([chr(i) for i in range(256)]),
                                 img_plt)
        img_tran = img_content.translate(trans)
        diff = ["", ""]
        img = Image.new("1", img.size, 0)
        for i in range(1, len(img_content)):
            if img_content[i] != img_tran[i - 1]:
                diff[0] += img_content[i]
                diff[1] += img_tran[i - 1]
                img.putpixel(((i - 1) % img.size[0], (i - 1) / img.size[0]), 1)
        img.show(
        )  # two words shows in picture: 'not', 'word', between is an key
        text = bz2.decompress(diff[0])
        auth = set()
        for i in text.split():
            if not keyword.iskeyword(i):
                auth.add(i)
        # print repeat, switch, ../ring/bell
        auth = list(auth)
        print auth
        for item in auth:
            if 'html' in item:
                next_level_url = WebHelper.join_url(self.url, item)
                auth.remove(item)
        try:
            content_ignore = WebHelper.get_auth_web_source(
                next_level_url, auth[0], auth[1])
            self.result.set_user_password(auth[0], auth[1])
            print "Set next level user, password = (%s, %s)" % (auth[0],
                                                                auth[1])
        except HTTPError:
            self.result.set_user_password(auth[1], auth[0])
            print "Set next level user, password = (%s, %s)" % (auth[1],
                                                                auth[0])

        # step 3, set next level url
        self.set_next_level_url(next_level_url)
Exemplo n.º 11
0
    def do_compute(self):
        # step 1, get prompt information from web source
        gif_prompt = TextHelper.find_text_between_tag(self.web_source,
                                                      '<!-- or maybe ',
                                                      ' would be more')
        gif_url = WebHelper.join_url(self.url, gif_prompt)
        print "Get gif url: %s" % gif_url

        ImageHelper.show_image_from_web(gif_url, self.user, self.password)
        local_image = WebHelper.get_url_page(gif_url)
        WebHelper.download_with_auth(gif_url, local_image, self.user,
                                     self.password)
        ImageHelper.show_from_file(local_image)

        # step 2, get Image draw
        img = Image.open(local_image)
        prompt_img = Image.new("RGB", (500, 200))
        draw = ImageDraw.Draw(prompt_img)
        cx, cy = 0, 100
        for frame in range(img.n_frames):
            img.seek(frame)
            left, upper, right, lower = img.getbbox()
            dx = left - 100
            dy = upper - 100

            if dx == dy == 0:
                cx += 50
                cy = 100

            cx += dx
            cy += dy

            draw.point([cx, cy])
        prompt_img.show()  # shows 'bonus'

        # step 3, set prompt
        prompt_words = 'bonus'
        print "get prompt words from image %s" % prompt_words
        self.set_prompt(prompt_words)

        # step 4, clean unused files
        FileHelper.remove_file(local_image)
Exemplo n.º 12
0
    def do_compute(self):
        # step 1, get question from web source
        words_prompt = TextHelper.find_text_between_tag(
            self.web_source, "<title>", "</title>")
        print words_prompt  # ask us who is this person?

        # step 2, get image from web
        prompt_url = TextHelper.find_text_between_tag(self.web_source,
                                                      "<img src=\"", "\"><br>")
        img_url = WebHelper.join_url(self.url, prompt_url)
        url_ignore, img_data = WebHelper.get_auth_url_content(img_url)
        ImageHelper.show_image_from_web(
            img_url)  # a calendar shows a date January, 26, 1XX6
        month = 1
        day = 26

        # step 3, calculate possible date
        possible_year = filter(lambda y: isleap(y) and 0 == weekday(y, 1, 26),
                               range(1006, 2000, 10))
        print possible_year

        # step 4, get the date with more prompt information
        words_prompt = TextHelper.find_text_between_tag(
            self.web_source, "<!-- todo: ", " -->")
        print words_prompt  # prompt us the date after January, 26 is some day special for memory
        day += 1

        words_prompt = TextHelper.find_text_between_tag(
            self.web_source, "<center>\n<!-- ", " -->")
        print words_prompt  # prompt us choose the second youngest
        year = possible_year[-2]

        print "The day special for flower is " + str(year) + "/" + str(
            month) + "/" + str(day)
        # some body may know but I don't know this day is the birthday of mozart
        # https://en.wikipedia.org/wiki/January_27#Births

        # step 5, set prompt for the next leve
        self.set_prompt("mozart")
Exemplo n.º 13
0
    def do_compute(self):
        # step 1, get information from web source
        png_url = TextHelper.find_text_between_tag(self.web_source, '<img src="', '" border="')
        png_url = WebHelper.join_url(self.url, png_url)
        print "Get png from web url: %s" % png_url
        bell_png = ImageHelper.create_image_from_web(png_url, self.user, self.password)
        green = bell_png.split()[1]
        message = ""
        for a, b in T28.paired(green.getdata()):
            diff = abs(a - b)
            if diff != 42:
                message += chr(diff)
        print 'Prompt Message: %s' % message   # whodunnit().split()[0] ?

        # step 2, set prompt
        prompt = self.whodunnit().split()[0]
        self.set_prompt(prompt.lower())
Exemplo n.º 14
0
    def do_compute(self):
        # step 1. get information from web source
        print TextHelper.find_text_between_tag(self.web_source, '<!--\n',
                                               '\n-->')
        beer_url = TextHelper.find_text_between_tag(self.web_source,
                                                    '<img src="',
                                                    '" border="0"')
        beer_url = WebHelper.join_url(self.url, beer_url)
        print beer_url
        beer_url = WebHelper.url_add(beer_url)
        beer_url = WebHelper.change_suffix_url(beer_url, 'png')

        # step 2. try out this picture
        beer_img = ImageHelper.create_image_from_web(beer_url, self.user,
                                                     self.password)
        data = list(beer_img.getdata())
        local_dir = 'img_data'
        FileHelper.mkdir(local_dir)
        print len(data)
        count = 0
        while len(data) > 0:
            if self.is_int_sqrt(len(data)) and len(data) > 0:
                count += 1
                size = int(math.sqrt(len(data)))
                print "data length = %i, sqrt value = %i" % (len(data), size)
                new_img = Image.new('RGB', (size, size))
                new_img.putdata(data)
                new_img.save(os.path.join(local_dir, 'img_%i.png' % count))
            max_value = max(data)
            data = [x for x in data if x != max_value]

        # step 3, Get hint from these pictures
        print "check png under %s, you will find many characters!" % local_dir
        prompt = 'gremlins'
        print "but only characters %s are in square" % str(list(prompt))
        self.set_prompt(prompt)
        FileHelper.remove_folder(local_dir)
Exemplo n.º 15
0
    def do_compute(self):
        # step 1, get information from web source
        question = TextHelper.find_text_between_tag(self.web_source, '<title>',
                                                    '</title>')
        print "The title asked us: %s" % question
        answer = ("kohsamui", "thailand")
        self.result.set_user_password(answer[0], answer[1])
        print "Set next level user, password = (%s, %s)" % answer
        print "Search google by this photograph, you can find the place: %s, %s" % answer
        prompt = TextHelper.find_text_between_tag(self.web_source, '<a href="',
                                                  '"><img src')
        new_url = WebHelper.join_url(self.url, prompt)
        print "Get prompt jpg url: %s" % new_url
        new_web_content = WebHelper.get_auth_web_source2(new_url, answer)
        print TextHelper.find_text_between_tag(new_web_content,
                                               '<font color="gold">',
                                               '</font>')
        mandelbrot_gif = TextHelper.find_text_between_tag(
            new_web_content, '<img src="', '" border="0">')
        mandelbrot_gif = WebHelper.join_url(new_url, mandelbrot_gif)
        print "Get new gif picture: %s" % mandelbrot_gif
        print TextHelper.find_text_between_tag(new_web_content,
                                               'border="0">\n', '\n	</img>')

        # step 2, parse mandelbrot gif
        left, top, width, height, iteration = 0.34, 0.57, 0.036, 0.027, 128
        img = ImageHelper.create_image_from_web(mandelbrot_gif, answer[0],
                                                answer[1])
        print "Get image size: %s, %s" % img.size
        w, h = img.size
        x_step, y_step = width / w, height / h
        result = []
        for y in range(h - 1, -1, -1):
            for x in range(w):
                c = complex(left + x * x_step, top + y * y_step)
                z = 0 + 0j
                for i in range(iteration):
                    z = z * z + c
                    if abs(z) > 2:
                        break
                result.append(i)
        new_img = img.copy()
        new_img.putdata(result)
        new_img.show()

        # step 3, show diff about these two picture
        diff = [(a - b) for a, b in zip(img.getdata(), new_img.getdata())
                if a != b]
        print len(diff)
        print set(diff)

        plot = Image.new('L', (23, 73))
        plot.putdata([(i < 16) and 255 or 0 for i in diff])
        plot.resize((230, 730)).show()
        prompt = 'arecibo'
        print "Oh, God dammit! Who knows this is a message humanity send to the starts from %s telescope" % prompt

        # step 4, set next challenge url
        next_level_url = WebHelper.join_url(mandelbrot_gif, prompt)
        next_level_url = WebHelper.change_suffix_url(next_level_url, 'html')
        self.set_next_level_url(next_level_url)