Generate ``('file', (name, val))`` and
        ``('form', (name, val))`` parts.
542180
def parse_parts(self, file, boundary, content_length):
        
        in_memory = 0

        for ellt, ell in self.parse_lines(file, boundary, content_length):
            if ellt == _begin_file:
                headers, name, filename = ell
                is_file = True
                guard_memory = False
                filename, container = self.start_file_streaming(
                    filename, headers, content_length)
                _write = container.write

            elif ellt == _begin_form:
                headers, name = ell
                is_file = False
                container = []
                _write = container.append
                guard_memory = self.max_form_memory_size is not None

            elif ellt == _cont:
                _write(ell)
                # if we write into memory and there is a memory size limit we
                # count the number of bytes in memory and raise an exception if
                # there is too much data in memory.
                if guard_memory:
                    in_memory += len(ell)
                    if in_memory > self.max_form_memory_size:
                        self.in_memory_threshold_reached(in_memory)

            elif ellt == _end:
                if is_file:
                    container.seek(0)
                    yield ('file',
                           (name, FileStorage(container, filename, name,
                                              headers=headers)))
                else:
                    part_charset = self.get_part_charset(headers)
                    yield ('form',
                           (name, b''.join(container).decode(
                                part_charset, self.errors)))
318904
def generate_form(model, only=None, meta=None):
    
    fields = OrderedDict()
    if meta:
        fields['Meta'] = meta

    for name, column in model.__dict__['columns'].items():
        if only:
            if not name in only:
                continue
        if not isinstance(column, Column):
            continue
        fields[name] = TYPE_MAP[column.type.__class__](
            name, render_kw={'placeholder': name}
        )
    form = type(
        'Add{}Form'.format(model.name.capitalize()),
        (Form,),
        fields
    )
    return form
962635
private function buildEditForm()
    {
        $form = '';
        foreach ($this->fields as $field) {
            $title = addslashes($field->label);
            $label = $field->title;
            if (in_array($field->validation,
                    $this->starred) && $field->type != 'password' && $field->type != 'file' && $field->type != 'photo'
            ) {
                $title .= '*';
            }
            if ($field->type == 'relationship') {
                $label = $field->relationship_name . '_id';
            }
            if ($field->type == 'checkbox') {
                $field->default = '$' . $this->model . '->' . $label . ' == 1';
            }
            $temp = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Templates' . DIRECTORY_SEPARATOR . 'fields' . DIRECTORY_SEPARATOR . $field->type);
            $temp = str_replace([
                'old(\'$LABEL$\')',
                '$LABEL$',
                '$TITLE$',
                '$VALUE$',
                '$STATE$',
                '$SELECT$',
                '$TEXTEDITOR$',
                '$HELPER$',
                '$WIDTH$',
                '$HEIGHT$',
            ], [
                'old(\'$LABEL$\',$' . $this->resource . '->' . $label . ')',
                $label,
                $title,
                $field->type != 'radio' ?
                    $field->value != '' ? ', "' . $field->value . '"' : ''
                    : "'$field->value'",
                $field->default,
                '$' . $field->relationship_name,
                $field->texteditor == 1 ? ' ckeditor' : '',
                $this->helper($field->helper),
                $field->dimension_w,
                $field->dimension_h,
            ], $temp);
            $form .= $temp;
        }
        $this->formFieldsEdit = $form;
    }
493864
def file_parts(self):
        
        file_parts = []
        for part in self.parts:
            try:
                for sub_part in part:
                    if isinstance(sub_part, FileToken):
                        file_parts.append(sub_part)
            except TypeError:
                if isinstance(part, FileToken):
                    file_parts.append(part)
        return file_parts
71281
def encode_multipart_formdata(self, fields, files, baseName, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + baseName + ' for upload...'))
        fin = self._open(files, 'rb')
        fout = self._open(files + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
587532
private function generateFormData ()
    {
        $files = $this->getConfigFiles ();
        $formDataHolder = [];


        if (!empty($files)) {
            foreach ($files as $file) {

                $file = json_decode (file_get_contents ($file), true);

                if (isset($file['formData']))
                    $formDataHolder = array_merge ($formDataHolder, $file['formData']);
            }
        }

        Cache::forget ('hc-forms');
        Cache::put ('hc-forms', $formDataHolder, Carbon::now ()->addMonth ());
    }
1036875
private function attachFiles(){
        if (count($this->attachments) === 0) {
            return;
        }
        // Get old message parts
        $mimeMessage = $this->message->getBody();
        if (is_string($mimeMessage)) {
            $originalBodyPart = new Mime\Part($mimeMessage);
            $originalBodyPart->type = $mimeMessage != strip_tags($mimeMessage)
                ? Mime\Mime::TYPE_HTML
                : Mime\Mime::TYPE_TEXT;
            // A Mime\Part body will be wraped into a Mime\Message, ensuring we handle a Mime\Message after this point
            $this->setBody($originalBodyPart);
            $mimeMessage = $this->message->getBody();;
        }
        $oldParts = $mimeMessage->getParts();
        // Generate a new Mime\Part for each attachment
        $attachmentParts    = [];
        $info               = new \finfo(FILEINFO_MIME_TYPE);
        foreach ($this->attachments as $key => $attachment) {
            if (! is_file($attachment)) {
                continue; // If checked file is not valid, continue to the next
            }
            // If the key is a string, use it as the attachment name
            $basename = is_string($key) ? $key : basename($attachment);
            $part               = new Mime\Part(fopen($attachment, 'r'));
            $part->id           = $basename;
            $part->filename     = $basename;
            $part->type         = $info->file($attachment);
            $part->encoding     = Mime\Mime::ENCODING_BASE64;
            $part->disposition  = Mime\Mime::DISPOSITION_ATTACHMENT;
            $attachmentParts[]  = $part;
        }
        $body = new Mime\Message();
        $body->setParts(array_merge($oldParts, $attachmentParts));
        $this->message->setBody($body);
    }
916243
def multipart_encode(self, vars):
        ""
        boundary = mimetools.choose_boundary()
        buf = StringIO()
        for key, value in vars.items():
            if not isinstance(value, file):
                buf.write('--%s\r\n' % boundary)
                buf.write('Content-Disposition: form-data; name="%s"' % key)
                buf.write('\r\n\r\n' + value + '\r\n')
            else:
                fd = value
                file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
                filename = os.path.basename(fd.name)
                contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
                buf.write('--%s\r\n' % boundary)
                buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
                buf.write('Content-Type: %s\r\n' % contenttype)
                # buffer += 'Content-Length: %s\r\n' % file_size
                fd.seek(0)
                buf.write('\r\n' + fd.read() + '\r\n')
        buf.write('--' + boundary + '--\r\n\r\n')
        buf = buf.getvalue()
        return boundary, buf
676633
def encode_multipart(data, files):
    
    body = BytesIO()
    boundary = choose_boundary()
    part_boundary = b('--%s\r\n' % boundary)
    writer = codecs.lookup('utf-8')[3]

    if isinstance(data, dict):
        for name, values in data.items():
            if not isinstance(values, (list, tuple, set)):
                # behave like urllib.urlencode(dict, 1)
                values = (values, )
            for value in values:
                body.write(part_boundary)
                writer(body).write('Content-Disposition: form-data; '
                                   'name="%s"\r\n' % name)
                body.write(b'Content-Type: text/plain\r\n\r\n')
                if isinstance(value, int):
                    value = str(value)
                if py3k and isinstance(value, str):
                    writer(body).write(value)
                else:
                    body.write(value)
                body.write(b'\r\n')

    for fieldname, f in files.items():
        if isinstance(f, tuple):
            filename, f = f
        elif hasattr(f, 'name'):
            filename = basename(f.name)
        else:
            filename = None
            raise UrlfetchException("file must has filename")

        if hasattr(f, 'read'):
            value = f.read()
        elif isinstance(f, basestring):
            value = f
        else:
            value = str(f)

        body.write(part_boundary)
        if filename:
            writer(body).write('Content-Disposition: form-data; name="%s"; '
                               'filename="%s"\r\n' % (fieldname, filename))
            body.write(b'Content-Type: application/octet-stream\r\n\r\n')
        else:
            writer(body).write('Content-Disposition: form-data; name="%s"'
                               '\r\n' % name)
            body.write(b'Content-Type: text/plain\r\n\r\n')

        if py3k and isinstance(value, str):
            writer(body).write(value)
        else:
            body.write(value)
        body.write(b'\r\n')

    body.write(b('--' + boundary + '--\r\n'))

    content_type = 'multipart/form-data; boundary=%s' % boundary

    return content_type, body.getvalue()
728712
def get_files_from_textfile(textfile_handler):
    """"""
    for line in textfile_handler:
        line = line.rstrip()
        try:
            (image_name, width) = line.rsplit(',', 1)
            width = int(width)
        except ValueError:
            image_name = line
            width = None
        yield (image_name, width)
1160492
def form_processor(request, page):
    
    form = FormForForm(page.form, RequestContext(request),
                       request.POST or None, request.FILES or None)
    if form.is_valid():
        url = page.get_absolute_url() + "?sent=1"
        if is_spam(request, form, url):
            return redirect(url)
        attachments = []
        for f in form.files.values():
            f.seek(0)
            attachments.append((f.name, f.read()))
        entry = form.save()
        subject = page.form.email_subject
        if not subject:
            subject = "%s - %s" % (page.form.title, entry.entry_time)
        fields = [(v.label, format_value(form.cleaned_data[k]))
                  for (k, v) in form.fields.items()]
        context = {
            "fields": fields,
            "message": page.form.email_message,
            "request": request,
        }
        email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
        email_to = form.email_to()
        if email_to and page.form.send_email:
            send_mail_template(subject, "email/form_response", email_from,
                               email_to, context)
        headers = None
        if email_to:
            # Add the email entered as a Reply-To header
            headers = {'Reply-To': email_to}
        email_copies = split_addresses(page.form.email_copies)
        if email_copies:
            send_mail_template(subject, "email/form_response_copies",
                               email_from, email_copies, context,
                               attachments=attachments, headers=headers)
        form_valid.send(sender=request, form=form, entry=entry)
        return redirect(url)
    form_invalid.send(sender=request, form=form)
    return {"form": form}
569089
def construct_form(self, request):
        
        if not hasattr(self, 'form_class'):
            return None

        if request.method == 'POST':
            form = self.form_class(self.model, request.POST, request.FILES)
        else:
            form = self.form_class(self.model)
        return form
1021072
function(map, form) {
    var bodyParam, el, headerParams, l, len, len1, len2, len3, m, n, o, obj, p, param, params, ref1, ref2, ref3, ref4;
    ref1 = form.serializeArray();
    for (l = 0, len = ref1.length; l < len; l++) {
      o = ref1[l];
      if ((o.value !== null) && jQuery.trim(o.value).length > 0) {
        map[o.name] = o.value;
      }
    }
    bodyParam = new FormData();
    params = 0;
    ref2 = this.model.parameters;
    for (m = 0, len1 = ref2.length; m < len1; m++) {
      param = ref2[m];
      if (param.paramType === 'form' || param['in'] === 'formData') {
        if (param.type.toLowerCase() !== 'file' && map[param.name] !== void 0) {
          bodyParam.append(param.name, map[param.name]);
        }
      }
    }
    headerParams = {};
    ref3 = this.model.parameters;
    for (n = 0, len2 = ref3.length; n < len2; n++) {
      param = ref3[n];
      if (param.paramType === 'header') {
        headerParams[param.name] = map[param.name];
      }
    }
    ref4 = form.find('input[type~="file"]');
    for (p = 0, len3 = ref4.length; p < len3; p++) {
      el = ref4[p];
      if (typeof el.files[0] !== 'undefined') {
        bodyParam.append($(el).attr('name'), el.files[0]);
        params += 1;
      }
    }
    this.invocationUrl = this.model.supportHeaderParams() ? (headerParams = this.model.getHeaderParams(map), delete headerParams['Content-Type'], this.model.urlify(map, false)) : this.model.urlify(map, true);
    $('.request_url', $(this.el)).html('<pre></pre>');
    $('.request_url pre', $(this.el)).text(this.invocationUrl);
    obj = {
      type: this.model.method,
      url: this.invocationUrl,
      headers: headerParams,
      data: bodyParam,
      dataType: 'json',
      contentType: false,
      processData: false,
      error: (function(_this) {
        return function(data) {
          return _this.showErrorStatus(_this.wrap(data), _this);
        };
      })(this),
      success: (function(_this) {
        return function(data) {
          return _this.showResponse(data, _this);
        };
      })(this),
      complete: (function(_this) {
        return function(data) {
          return _this.showCompleteStatus(_this.wrap(data), _this);
        };
      })(this)
    };
    if (window.authorizations) {
      window.authorizations.apply(obj);
    }
    jQuery.ajax(obj);
    return false;
    // end of file-upload nastiness
  }
637659
def generate(self, more_content=None, all_members=False):
        # type: (Any, str, bool, bool) -> None
        
        directive = getattr(self, 'directivetype', self.objtype)

        # parse components out of name
        (file, _, namepath) = self.name.rpartition(':')
        (contract_name, _, fullname) = namepath.partition('.')
        (name, _, paramtypes) = fullname.partition('(')

        # normalize components
        name = name.strip() or None

        if directive in ('contract', 'interface', 'library') and name is None:
            name = contract_name
            contract_name = None

        paramtypes = ','.join(ptype.strip() for ptype in paramtypes.split(','))
        paramtypes = re.sub(r'\s+', ' ', paramtypes)
        if paramtypes.endswith(')'):
            paramtypes = paramtypes[:-1]

        # build query
        expressions = [
            SolidityObject.objtype == directive,
            SolidityObject.name == name,
        ]

        if file:
            expressions.append(SolidityObject.file == file)
        if contract_name:
            expressions.append(SolidityObject.contract_name == contract_name)
        if paramtypes:
            expressions.append(SolidityObject.paramtypes == paramtypes)

        # get associated object
        query = SolidityObject.select().where(*expressions)
        sol_objects = tuple(query)
        if len(sol_objects) == 0:
            logger.warning('{} {} could not be found via query:\n{}'.format(
                directive, self.name, ',\n'.join(
                    '  ' + str(expr.lhs.column_name) +
                    str(expr.op) + ('' if expr.rhs is None else expr.rhs)
                    for expr in expressions
                )))
            return
        elif len(sol_objects) > 1:
            logger.warning('multiple candidates for {} {} found:\n{}'.format(
                directive, self.name,
                '\n'.join('  ' + obj.signature for obj in sol_objects)))

        self.object = sol_objects[0]

        # begin rendering output
        sourcename = self.get_sourcename()

        # make sure that the result starts with an empty line.  This is
        # necessary for some situations where another directive preprocesses
        # reST and no starting newline is present
        self.add_line('', sourcename)

        # generate the directive header and options, if applicable
        self.add_directive_header()

        # make sure content is indented
        # TODO: consider adding a source unit directive
        self.indent += self.content_indent

        # add all content (from docstrings, attribute docs etc.)
        self.add_content(more_content)

        # document members, if possible
        if directive in ('contract', 'interface', 'library'):
            self.add_line('', sourcename)
            self.document_members(all_members)
301148
def parseArgs():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="the file you want to split")
    parser.add_argument("out1", help="the name of the first file you want to output")
    parser.add_argument("out2", help="the name of the second file you want to output")
    return parser.parse_args()
1157370
function generate(tmpl, src, variables) {
        variables = variables || {};
        variables.FILES = {};
        for (var i = 0; i < src.length; i++) {
            var content = JSON.stringify(grunt.file.read(src[i]));
            variables.FILES[src[i]] = content;
        }
        var template = grunt.file.read(tmpl);
        return substitute(template, variables);
    }
821052
def make_streams(name, value, boundary, encoding):
    """"""

    filename = None
    mime = None

    # user passed in a special dict.
    if isinstance(value, collections.Mapping) and "name" in value and "value" in value:
        filename = value["name"]
        try:
            mime = value["mime"]
        except KeyError:
            pass
        value = value["value"]

    if not filename:
        filename = getattr(value, "name", None)
        if filename:
            filename = os.path.split(filename)[1]

    mime = mime or "application/octet-stream"

    name, filename, mime = [escape_header(v) for v in (name, filename, mime)]

    stream = BytesIO()
    stream.write("--{}\r\n".format(boundary).encode(encoding))
    if not filename:
        stream.write(
            'Content-Disposition: form-data; name="{}"\r\n'.format(name).encode(
                encoding
            )
        )
    else:
        stream.write(
            'Content-Disposition: form-data; name="{}"; filename="{}"\r\n'.format(
                name, filename
            ).encode(encoding)
        )
        if mime:
            stream.write("Content-Type: {}\r\n".format(mime).encode(encoding))
    stream.write(b"\r\n")

    if hasattr(value, "read"):
        stream.seek(0)
        return stream, value, BytesIO("\r\n".encode(encoding))

    # not a file-like object, encode headers and value in one go
    value = value if isinstance(value, (str, bytes)) else json.dumps(value)
    if isinstance(value, bytes):
        stream.write(value)
    else:
        stream.write(value.encode(encoding))
    stream.write(b"\r\n")
    stream.seek(0)
    return (stream,)