Generates and returns a numeric captcha image in base64 format. 
        Saves the correct answer in `session['captcha_answer']`
        Use later as:

        src = captcha.generate()
        <img src="{{src}}">
977368
def generate(self):
                        
        answer = self.rand.randrange(self.max)
        answer = str(answer).zfill(self.digits)        
        image_data = self.image_generator.generate(answer)
        base64_captcha = base64.b64encode(image_data.getvalue()).decode("ascii")
        logging.debug('Generated captcha with answer: ' + answer)
        session['captcha_answer'] = answer
        return base64_captcha
1067321
function base64ToBlob(base64Image, contentType) {
  // http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript

  // Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,'
  base64Image = base64Image.split(',')[1];

  let byteCharacters = atob(base64Image);

  // http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long
  let byteArrays = byteCharacters.match(/[\s\S]{1,512}/g).map( slice => {

    let byteNumbers = slice.split('').map( x => x.charCodeAt(0) );

    return new Uint8Array(byteNumbers);
  });

  let blob = new Blob(byteArrays, { type: contentType || 'image/jpg' /* or 'image/png' */ });

  return blob;
}
906973
function () {
        var mime = this.mime();

        // if there is no mime detected, there is no accurate way to render this thing
        if (!this.mime) {
            return E;
        }

        // we create the body string first from stream and then fallback to body
        return 'data:' + mime._sanitisedContentType + ';base64, ' + ((!_.isNil(this.stream) &&
            util.bufferOrArrayBufferToBase64(this.stream)) || (!_.isNil(this.body) && util.btoa(this.body)) || E);
    }
502866
def _convert_markup_images(self, soup):
        
        # 6. Replace <img> assets with actual image contents
        images = [image for image in soup.find_all('img')
                  if image.attrs.get('assetid') is not None]
        if not images:
            return

        # Get assetid attribute from all images
        asset_ids = [image.attrs.get('assetid') for image in images]
        self._asset_retriever(asset_ids)

        for image in images:
            # Encode each image using base64
            asset = self._asset_retriever[image['assetid']]
            if asset.data is not None:
                encoded64 = base64.b64encode(asset.data).decode()
                image['src'] = 'data:%s;base64,%s' % (
                    asset.content_type, encoded64)
1264547
def upload(options = {})
      payload = {}
      payload[:captchafile] = "base64:#{options[:raw64]}"
      payload[:type] = options[:type] if options[:type].to_i > 0

      if options[:type].to_i == 3
        banner64 = load_captcha(options[:banner])
        raise DeathByCaptcha::InvalidCaptcha if banner64.to_s.empty?

        payload[:banner] = "base64:#{banner64}"
        payload[:banner_text] = options[:banner_text].to_s

      elsif options[:type].to_i == 4
        payload = {
          type: 4,
          token_params: options[:token_params].to_json,
        }
      end

      response = perform('captcha', :post_multipart, payload)
      DeathByCaptcha::Captcha.new(response)
    end
647820
function generator(url) {
	var randomnesss = Crypto.randomBytes(24);
	randomnesss.writeDoubleBE(Date.now(), 0);
	randomnesss.writeUInt32BE(process.pid, 8);

	var output = randomnesss.toString('base64');

	// URL safe
	if (url) {
		output = output.replace(/\//g, '_');
		output = output.replace(/\+/g, '-');
	}

	return output;
}
921882
def generate_captcha
      if EasyCaptcha.cache
        # create cache dir
        FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir)

        # select all generated captchas from cache
        files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png")

        unless files.size < EasyCaptcha.cache_size
          file              = File.open(files.at(Kernel.rand(files.size)))
          session[:captcha] = File.basename(file.path, '.*')

          if file.mtime < EasyCaptcha.cache_expire.ago
            File.unlink(file.path)
            # remove speech version
            File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav"))
          else
            return file.readlines.join
          end
        end
        generated_code = generate_captcha_code
        image = Captcha.new(generated_code).image

        # write captcha for caching
        File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image }

        # write speech file if u create a new captcha image
        EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak?

        # return image
        image
      else
        Captcha.new(generate_captcha_code).image
      end
    end
1116360
def captcha_transmit(self, captcha, uuid):
        """"""

        self.log('Transmitting captcha')

        response = {
            'component': 'hfos.enrol.enrolmanager',
            'action': 'captcha',
            'data': b64encode(captcha['image'].getvalue()).decode('utf-8')
        }
        self.fire(send(uuid, response))
1300964
def serialize(self, image):
        
        pic = mutagen.flac.Picture()
        pic.data = image.data
        pic.type = image.type_index
        pic.mime = image.mime_type
        pic.desc = image.desc or u''

        # Encoding with base64 returns bytes on both Python 2 and 3.
        # Mutagen requires the data to be a Unicode string, so we decode
        # it before passing it along.
        return base64.b64encode(pic.write()).decode('ascii')
1297310
def img2code(self, key, img):
        """"""

        code_template = \
            "wx.ImageFromData({width}, {height}, " + \
            "bz2.decompress(base64.b64decode('{data}'))).ConvertToBitmap()"

        code_alpha_template = \
            "wx.ImageFromDataWithAlpha({width}, {height}, " + \
            "bz2.decompress(base64.b64decode('{data}')), " + \
            "bz2.decompress(base64.b64decode('{alpha}'))).ConvertToBitmap()"

        data = base64.b64encode(bz2.compress(img.GetData(), 9))

        if img.HasAlpha():
            alpha = base64.b64encode(bz2.compress(img.GetAlphaData(), 9))
            code_str = code_alpha_template.format(
                width=img.GetWidth(), height=img.GetHeight(),
                data=data, alpha=alpha)
        else:
            code_str = code_template.format(width=img.GetWidth(),
                                            height=img.GetHeight(), data=data)

        return code_str
62494
def validate(self, form_key="captcha", value=None):
        
        if not self.enabled:
            return True

        session_value = session.get('captcha_answer', None)
        if not session_value:
            return False
        
        if not value and form_key in request.form:
            value = request.form[form_key].strip()

        # invalidate the answer to stop new tries on the same challenge.
        session['captcha_answer'] = None
        return value and value == session_value
435645
def ruokuai_captcha_handler(self, params, image_url):
        

        headers = {
            'Connection': 'Keep-Alive',
            'Expect': '100-continue',
            'User-Agent': 'ben',
        }
        image_data = requests.get(image_url).content
        files = {'image': ('check_code.png', image_data)}
        r = requests.post(
            'http://api.ruokuai.com/create.json',
            data=params,
            files=files,
            headers=headers
        )
        verify_code_dict = r.json()
        if verify_code_dict:
            if 'Error' in verify_code_dict.keys():
                print (verify_code_dict['Error'])
                return ''
            verify_code = verify_code_dict.get('Result', '')
        else:
            print ('rk failed ', verify_code_dict)
            return ''

        return verify_code
780832
function createImage(svgHtml) {
        let img = new Image();

        img.src = `${config.imageSourceBase}${ b64EncodeUnicode(svgHtml) }`;

        return img;
    }
586880
def encoded_image(image, options = {})
      target_format = options[:format] || default_render_format

      unless target_format.in?(Alchemy::Picture.allowed_filetypes)
        raise WrongImageFormatError.new(self, target_format)
      end

      options = {
        flatten: target_format != 'gif' && image_file_format == 'gif'
      }.merge(options)

      encoding_options = []

      if target_format =~ /jpe?g/
        quality = options[:quality] || Config.get(:output_image_jpg_quality)
        encoding_options << "-quality #{quality}"
      end

      if options[:flatten]
        encoding_options << '-flatten'
      end

      convertion_needed = target_format != image_file_format || encoding_options.present?

      if has_convertible_format? && convertion_needed
        image = image.encode(target_format, encoding_options.join(' '))
      end

      image
    end
653480
def plaintext(self, result):
        
        from PIL import Image

        ascii_chars = ['#', 'A', '@', '%', 'S', '+', '<', '*', ':', ',', '.']

        def image_to_ascii(image):
            image_as_ascii = []
            all_pixels = list(image.getdata())
            for pixel_value in all_pixels:
                index = pixel_value / 25 # 0 - 10
                image_as_ascii.append(ascii_chars[index])
            return image_as_ascii   

        img = Image.open(result)
        width, heigth = img.size
        new_width = 80 
        new_heigth = int((heigth * new_width) / width)
        new_image = img.resize((new_width, new_heigth))
        new_image = new_image.convert("L") # convert to grayscale

        # now that we have a grayscale image with some fixed width we have to convert every pixel
        # to the appropriate ascii character from "ascii_chars"
        img_as_ascii = image_to_ascii(new_image)
        img_as_ascii = ''.join(ch for ch in img_as_ascii)
        out = []
        for c in range(0, len(img_as_ascii), new_width):
            out.append(img_as_ascii[c:c+new_width])

        return "\n".join(out)
285843
def pickle_encode(session_dict):
    ""
    pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
    return base64.encodestring(pickled + get_query_hash(pickled).encode())
367396
def create_html(api_key, attrs):
    ''''''
    gif = get_gif(api_key, attrs['gif_id'])

    if 'alt' not in attrs.keys():
        attrs['alt'] = 'source: {}'.format(gif['data']['source'])

    html_out = '<a href="{}">'.format(gif['data']['url'])
    html_out += '<img src="{}" alt="{}">'.format(
        gif['data']['images']['original']['url'],
        attrs['alt'])
    html_out += '</a>'

    return html_out