ATTACH REQUEST Section 9.4.1
171396
def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0,
                  TmsiStatus_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x1)  # 0000001
    c = MsNetworkCapability()
    d = AttachTypeAndCiphKeySeqNr()
    f = DrxParameter()
    g = MobileId()
    h = RoutingAreaIdentification()
    i = MsRadioAccessCapability()
    packet = a / b / c / d / f / g / h / i
    if PTmsiSignature_presence is 1:
        j = PTmsiSignature(ieiPTS=0x19)
        packet = packet / j
    if GprsTimer_presence is 1:
        k = GprsTimer(ieiGT=0x17)
        packet = packet / k
    if TmsiStatus_presence is 1:
        l = TmsiStatus(ieiTS=0x9)
        packet = packet / l
    return packet
840081
function request() {
        $url = $this->url.$this->endpoint;
        
        $options = array(
            'http_errors' => false,
            'headers' => array(
                'User-Agent' => 'DiscordBot (https://github.com/CharlotteDunois/Yasmin, '.\CharlotteDunois\Yasmin\Client::VERSION.')'
            )
        );
        
        if(!empty($this->options['auth'])) {
            $options['headers']['Authorization'] = $this->options['auth'];
        } elseif(empty($this->options['noAuth']) && !empty($this->api->client->token)) {
            $options['headers']['Authorization'] = 'Bot '.$this->api->client->token;
        }
        
        if(!empty($this->options['files']) && \is_array($this->options['files'])) {
            $options['multipart'] = array();
            
            foreach($this->options['files'] as $file) {
                if(!isset($file['data']) && !isset($file['path'])) {
                    continue;
                }
                
                $field = ($file['field'] ?? 'file-'.\bin2hex(\random_bytes(3)));
                $options['multipart'][] = array(
                    'name' => $field,
                    'contents' => (isset($file['data']) ? $file['data'] : \fopen($file['path'], 'r')),
                    'filename' => (isset($file['name']) ? $file['name'] : (isset($file['path']) ? \basename($file['path']) : $field.'.jpg'))
                );
            }
            
            if(!empty($this->options['data'])) {
                $options['multipart'][] = array(
                    'name' => 'payload_json',
                    'contents' => \json_encode($this->options['data'], self::$jsonOptions)
                );
            }
        } elseif(!empty($this->options['data'])) {
            $options['json'] = $this->options['data'];
        }
        
        if(!empty($this->options['querystring'])) {
            $options['query'] = \http_build_query($this->options['querystring'], '', '&', \PHP_QUERY_RFC3986);
        }
        
        if(!empty($this->options['auditLogReason'])) {
            $options['headers']['X-Audit-Log-Reason'] = \rawurlencode(\trim($this->options['auditLogReason']));
        }
        
        $request = new \RingCentral\Psr7\Request($this->method, $url);
        $request->requestOptions = $options;
        
        return $request;
    }
1230863
public PaymentMethod attach(Map<String, Object> params) throws StripeException {
    return attach(params, (RequestOptions) null);
  }
26188
def action_add(self):
        

        form = self.request.form
        parent = api.get_parent(self.context)
        attachment_file = form.get('AttachmentFile_file', None)
        AttachmentType = form.get('AttachmentType', '')
        AttachmentKeys = form.get('AttachmentKeys', '')
        ReportOption = form.get('ReportOption', 'r')

        # nothing to do if the attachment file is missing
        if attachment_file is None:
            logger.warn("AttachmentView.action_add_attachment: Attachment file is missing")
            return

        # create attachment
        attachment = self.create_attachment(
            parent,
            attachment_file,
            AttachmentType=AttachmentType,
            AttachmentKeys=AttachmentKeys,
            ReportOption=ReportOption)

        # append the new UID to the end of the current order
        self.set_attachments_order(api.get_uid(attachment))

        # handle analysis attachment
        analysis_uid = form.get("Analysis", None)
        if analysis_uid:
            analysis = api.get_object_by_uid(analysis_uid)
            others = analysis.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())
            analysis.setAttachment(attachments)
            # The metadata for getAttachmentUIDs need to get updated,
            # otherwise the attachments are not displayed
            # https://github.com/senaite/bika.lims/issues/521
            analysis.reindexObject()

        else:
            others = self.context.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())

            self.context.setAttachment(attachments)

        if self.request['HTTP_REFERER'].endswith('manage_results'):
            self.request.response.redirect('{}/manage_results'.format(
                self.context.absolute_url()))
        else:
            self.request.response.redirect(self.context.absolute_url())
825563
def add_attachment(self, issue_key, filename):
        
        log.warning('Adding attachment...')
        headers = {'X-Atlassian-Token': 'no-check'}
        with open(filename, 'rb') as file:
            files = {'file': file}
            url = 'rest/api/2/issue/{}/attachments'.format(issue_key)

            return self.post(url, headers=headers, files=files)
969662
public static OAuthRequest attachFile(File file, OAuthRequest request) throws IOException {
        String boundary = generateBoundaryString();
        request.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        request.addBodyParameter("file", file.getName());

        StringBuilder boundaryMessage = new StringBuilder("--");
        boundaryMessage.append(boundary)
                .append("\r\n")
                .append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(file.getName())
                .append("\"\r\n")
                .append("Content-Type: ").append("application/x-unknown")
                .append("\r\n\r\n");

        String endBoundary = "\r\n--" + boundary + "--\r\n";

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        buffer.write(boundaryMessage.toString().getBytes(CHARSET_NAME));
        buffer.write(Files.readFile(file));
        buffer.write(endBoundary.getBytes(CHARSET_NAME));
        request.addPayload(buffer.toByteArray());
        buffer.close();

        return request;
    }
771223
def addAttachment(self, filepath):
        

        proj_id = self.contextId

        fa = self.rtc_obj.getFiledAgainst(self.filedAgainst,
                                          projectarea_id=proj_id)
        fa_id = fa.url.split("/")[-1]

        headers = copy.deepcopy(self.rtc_obj.headers)
        if headers.__contains__("Content-Type"):
            headers.__delitem__("Content-Type")

        filename = os.path.basename(filepath)
        fileh = open(filepath, "rb")
        files = {"attach": (filename, fileh, "application/octet-stream")}

        params = {"projectId": proj_id,
                  "multiple": "true",
                  "category": fa_id}
        req_url = "".join([self.rtc_obj.url,
                           "/service/com.ibm.team.workitem.service.",
                           "internal.rest.IAttachmentRestService/"])
        resp = self.post(req_url,
                         verify=False,
                         headers=headers,
                         proxies=self.rtc_obj.proxies,
                         params=params,
                         files=files)
        raw_data = xmltodict.parse(resp.content)
        json_body = json.loads(raw_data["html"]["body"]["textarea"])
        attachment_info = json_body["files"][0]
        return self._add_attachment_link(attachment_info)
468735
private void addAttachment(Multipart multipart, Attachment attachment) throws AttachmentResourceHandlerException {
		MimeBodyPart part = new MimeBodyPart();
		try {
			part.setFileName(attachment.getResource().getName());
			part.setDisposition(attachment.getDisposition());
			part.setDescription(attachment.getDescription());
			part.setContentID(attachment.getContentId());
			attachmentHandler.setData(part, attachment.getResource(), attachment);
			multipart.addBodyPart(part);
		} catch (MessagingException e) {
			throw new AttachmentResourceHandlerException("Failed to attach " + attachment.getResource().getName(), attachment, e);
		}
	}
1041370
def on_attach_request(self, py_db, request):
        '''
        
        '''
        self.api.set_enable_thread_notifications(py_db, True)
        self._set_debug_options(py_db, request.arguments.kwargs)
        response = pydevd_base_schema.build_response(request)
        return NetCommand(CMD_RETURN, 0, response, is_json=True)
263160
def __ConfigureMultipartRequest(self, http_request):
        """"""
        # This is a multipart/related upload.
        msg_root = mime_multipart.MIMEMultipart('related')
        # msg_root should not write out its own headers
        setattr(msg_root, '_write_headers', lambda self: None)

        # attach the body as one part
        msg = mime_nonmultipart.MIMENonMultipart(
            *http_request.headers['content-type'].split('/'))
        msg.set_payload(http_request.body)
        msg_root.attach(msg)

        # attach the media as the second part
        msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/'))
        msg['Content-Transfer-Encoding'] = 'binary'
        msg.set_payload(self.stream.read())
        msg_root.attach(msg)

        # NOTE: We encode the body, but can't use
        #       `email.message.Message.as_string` because it prepends
        #       `> ` to `From ` lines.
        fp = six.BytesIO()
        if six.PY3:
            generator_class = MultipartBytesGenerator
        else:
            generator_class = email_generator.Generator
        g = generator_class(fp, mangle_from_=False)
        g.flatten(msg_root, unixfrom=False)
        http_request.body = fp.getvalue()

        multipart_boundary = msg_root.get_boundary()
        http_request.headers['content-type'] = (
            'multipart/related; boundary=%r' % multipart_boundary)
        if isinstance(multipart_boundary, six.text_type):
            multipart_boundary = multipart_boundary.encode('ascii')

        body_components = http_request.body.split(multipart_boundary)
        headers, _, _ = body_components[-2].partition(b'\n\n')
        body_components[-2] = b'\n\n'.join([headers, b'<media body>\n\n--'])
        http_request.loggable_body = multipart_boundary.join(body_components)
1246867
def attach_storage(self, server, storage, storage_type, address):
        
        body = {'storage_device': {}}
        if storage:
            body['storage_device']['storage'] = str(storage)

        if storage_type:
            body['storage_device']['type'] = storage_type

        if address:
            body['storage_device']['address'] = address

        url = '/server/{0}/storage/attach'.format(server)
        res = self.post_request(url, body)
        return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self)
1040629
def insert_request_to_batch(self, request):
        '''
        
        '''
        self.validate_request_table(request)
        self.validate_request_partition_key(request)
        self.validate_request_row_key(request)
        self.batch_requests.append(request)
1221867
def attach(options = {})
      options = Aws::Util.deep_merge(options,
        auto_scaling_group_name: @group_name,
        instance_ids: [@id]
      )
      resp = @client.attach_instances(options)
      resp.data
    end
750608
function request(
	host,
	method,
	path,
	params,
	query,
	headers,
	options,
	file,
	cb,
	debug
) {
	if (!options) options = {};

	// Remove leading/trailing slash from the path/host so that we can join
	// the two together no matter which way the user chose to provide them.
	if (path[0] === FSLASH) {
		path = path.slice(1);
	}
	if (host[host.length - 1] === FSLASH) {
		host = host.slice(0, host.length - 1);
	}

	var url = host + FSLASH + path;

	var req = superagent[method](url);

	var bar;
	var prev_loaded = 0;
	if (!options.withoutCredentials) req.withCredentials();

	if (!file) {
		// Clean up extra parameters that may have gotten in here
		// if the request came from the CLI module. This is hacky; move elsewhere
		if (params) {
			delete params._;
			delete params.$0;
			req.send(params);
		}
		if (query) {
			delete query._;
			delete query.$0;
			req.query(objectToQueryString(query));
		}
	} else {
		//for file upload params are sent as query params
		req.accept('application/json');
		req.timeout(600000);
		if (query.workspaceFileName && global.paperspace_cli && !query.json) {
			req.on('progress', function _progress(e) {
				if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', {
					complete: '=',
					incomplete: ' ',
					width: 40,
					total: e.total,
				});
				var chunkSize = e.loaded - prev_loaded;
				prev_loaded = e.loaded;
				bar.tick(chunkSize);
			});
		}
		req.attach('file', file);
		delete query._;
		delete query.$0;
		if (query.json) delete query.json;
		req.query(objectToQueryString(query));
	}

	if (headers) {
		for (var headerKey in headers) {
			req.set(headerKey, headers[headerKey]);
		}
	}

	// TODO: Add nicer debug utils? Use the 'debug' module?
	if (debug) {
		console.log(method, url, params, query, headers);
	}

	return req.end(function _requestCallback(err, res) {
		// if content is gzipped, then body is empty object, and content is in 'text'
		var body;
		if (res && res.text) {
			try {
				body = JSON.parse(res.text);
			} catch (parseErr) {
				//console.error(res.text);
				//console.error(parseErr);
				//console.error('res: ' + res)
				//body = {};
				res.body = { message: res.text };
			}
		} else if (res && res.body) { // res.body is expected to be text/json
			body = res.body;
		} else body = {};

		// only return body in callback
		if (cb) return cb(err, body);

		// no callback provided; return the body
		return body;
	});
}
3785
def attach
      unless addon_name = args.shift
        error("Usage: heroku addons:attach ADDON_NAME\nMust specify add-on resource to attach.")
      end
      addon = resolve_addon!(addon_name)

      requires_preauth

      attachment_name = options[:as]

      msg = attachment_name ?
        "Attaching #{addon['name']} as #{attachment_name} to #{app}" :
        "Attaching #{addon['name']} to #{app}"

      display("#{msg}... ", false)

      response = api.request(
        :body     => json_encode({
          "app"     => {"name" => app},
          "addon"   => {"name" => addon['name']},
          "confirm" => options[:confirm],
          "name"    => attachment_name
        }),
        :expects  => [201, 422],
        :headers  => { "Accept" => "application/vnd.heroku+json; version=3" },
        :method   => :post,
        :path     => "/addon-attachments"
      )

      case response.status
      when 201
        display("done")
        action("Setting #{response.body["name"]} vars and restarting #{app}") do
          @status = api.get_release(app, 'current').body['name']
        end
      when 422 # add-on resource not found or cannot be attached
        display("failed")
        output_with_bang(response.body["message"])
        output_with_bang("List available resources with `heroku addons`.")
        output_with_bang("Provision a new add-on resource with `heroku addons:create ADDON_PLAN`.")
      end
    end
1248157
def attach(doc_id, doc_rev, attachment_name, data, opts=nil)

      if opts.nil?
        opts = data
        data = attachment_name
        attachment_name = doc_rev
        doc_rev = doc_id['_rev']
        doc_id = doc_id['_id']
      end

      attachment_name = attachment_name.gsub(/\//, '%2F')

      ct = opts[:content_type]

      raise(ArgumentError.new(
        ":content_type option must be specified"
      )) unless ct

      opts[:cache] = false

      path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")

      if @http.variant == :patron

        # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting
        # attachements
        # this is a fallback to net/http

        require 'net/http'

        http = Net::HTTP.new(@http.host, @http.port)

        req = Net::HTTP::Put.new(path)
        req['User-Agent'] =
          "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)"
        req['Content-Type'] =
          opts[:content_type]
        req['Accept'] =
          'application/json'
        req.body = data

        res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) })

        return @http.send(:respond, :put, path, nil, opts, nil, res)
      end

      @http.put(path, data, opts)
    end
641273
async def _send_generic_template(self, request: Request, stack: Stack):
        

        gt = stack.get_layer(GenericTemplate)
        payload = await gt.serialize(request)

        msg = {
            'attachment': {
                'type': 'template',
                'payload': payload
            }
        }

        await self._add_qr(stack, msg, request)
        await self._send(request, msg, stack)