For any request params that are of type BYTES, replace the file path with the bytes from the file
324849
private boolean replaceFilePathsWithBytes(ModelNode request) throws CommandFormatException, IOException {
        boolean didReplacement = false;
        ModelNode opDesc = new ModelNode();
        opDesc.get("address").set(request.get("address"));
        opDesc.get("operation").set("read-operation-description");
        final String opName = request.get("operation").asString();
        opDesc.get("name").set(opName);
        ModelNode response = execute(opDesc, false).getResponseNode();
        if (response.hasDefined("result", "request-properties")) {
            final ModelNode requestProps = response.get("result", "request-properties");
            for (Property prop : requestProps.asPropertyList()) {
                ModelNode typeDesc = prop.getValue().get("type");
                if (typeDesc.getType() == ModelType.TYPE && typeDesc.asType() == ModelType.BYTES
                        && request.hasDefined(prop.getName())) {
                    String filePath = request.get(prop.getName()).asString();
                    File localFile = new File(filePath);
                    if (!localFile.exists())
                        continue;
                    try {
                        request.get(prop.getName()).set(Util.readBytes(localFile));
                        didReplacement = true;
                    } catch (OperationFormatException e) {
                        throw new CommandFormatException(e);
                    }
                }
            }
        }
        return didReplacement;
    }
1314130
def load_file_to_base64_str(f_path):
    
    path = abs_path(f_path)
    with io.open(path, 'rb') as f:
        f_bytes = f.read()
        base64_str = base64.b64encode(f_bytes).decode("utf-8")
        return base64_str
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;
	});
}
1128935
private byte[] normalize(byte[] path) {
    if (path.length == 0)
      return path;
    byte prevC = 0;
    for (int i = 0; i < path.length; i++) {
      byte c = path[i];
      if (c == '\\')
        return normalize(path, i);
      if (c == (byte) '/' && prevC == '/')
        return normalize(path, i - 1);
      if (c == '\u0000')
        throw new InvalidPathException(this.hdfs.getString(path),
            "Path: nul character not allowed");
      prevC = c;
    }
    return path;
  }
183577
def from_bytes(rawbytes):
        '''
        
        '''
        icmpv6popts = ICMPv6OptionList()

        i = 0
        while i < len(rawbytes):
            opttype = rawbytes[i]
            optnum = ICMPv6OptionNumber(opttype)
            obj = ICMPv6OptionClasses[optnum]()
            eaten = obj.from_bytes(rawbytes[i:])
            i += eaten
            icmpv6popts.append(obj)
        return icmpv6popts
1195501
def _api_request(self, action, data, request_type, headers=None):
        
        if 'file' in data:
            file_data = {'file': open(data['file'], 'rb')}
        else:
            file_data = None

        return self._http_request(action, self._prepare_json_payload(data), request_type, file_data, headers)
106625
def get_stream(path, response_block, params = nil, headers = {}, auth = true)
      request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
    end
939837
def request_path(request):
    """"""
    url = request.get_full_url()
    parts = urlsplit(url)
    path = escape_path(parts.path)
    if not path.startswith("/"):
        # fix bad RFC 2396 absoluteURI
        path = "/" + path
    return path
213463
def wrap_multipart_params(func):
    

    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "multipart/form-data":

            if isinstance(pdict['boundary'], str):
                pdict['boundary'] = pdict['boundary'].encode()

            params = {}
            mp = MultipartParser(BytesIO(request.body), pdict['boundary'])
            for part in mp:
                params[part.name] = {
                    "filename": part.filename,
                    "file": part.file,
                }

            request.params = merge_dicts(getattr(request, "params", None), params)
            request.multipart_params = params

        return func(request, *args, **kwargs)
    return wrapper
765206
function normalizePath(path, keys, params) {
        for (var name in params) {
            var param = params[name];
            if (typeof param == "string" || param instanceof RegExp)
                params[name] = {type: param};
        }

        path = path
            .concat("/?")
            .replace(/\/:([\w.\-_]+)(\*?)/g, function(match, key, wildcard) {
                keys.push(key);
                if (!params[key]) {
                    params[key] = {};
                }
                // url params default to type string and optional=false
                var param = params[key];
                param.type = param.type || "string";
                param.optional = false;

                if (!param.source) param.source = "url";

                if (param.source !== "url")
                    throw new Error(
                        "Url parameters must have 'url' as source but found '" +
                            param.source +
                            "'"
                    );

                if (wildcard) return "(/*)";
                else return "/([^\\/]+)";
            })
            .replace(/([/.])/g, "\\$1")
            .replace(/\*/g, "(.*)");

        return new RegExp("^" + path + "$");
    }
113237
def convert(inputformat, outputformat, file_path, callback_url = nil, options = {})
      raise "File path cant be blank" if file_path.nil?
      @convert_request_url = start_conversion(inputformat, outputformat)
      #initiate connection with new response host
      initiate_connection(@convert_request_url)
      upload(build_upload_params(file_path, outputformat, callback_url, options))
    end
844019
def _prepare_request_file_vs_dir(self, request: Request) -> bool:
        '''
        '''
        if self._item_session.url_record.link_type:
            is_file = self._item_session.url_record.link_type == LinkType.file
        elif request.url_info.path.endswith('/'):
            is_file = False
        else:
            is_file = 'unknown'

        if is_file == 'unknown':
            files = yield from self._fetch_parent_path(request)

            if not files:
                return True

            filename = posixpath.basename(request.file_path)

            for file_entry in files:
                if file_entry.name == filename:
                    _logger.debug('Found entry in parent. Type {}',
                                  file_entry.type)
                    is_file = file_entry.type != 'dir'
                    break
            else:
                _logger.debug('Did not find entry. Assume file.')
                return True

            if not is_file:
                request.url = append_slash_to_path_url(request.url_info)
                _logger.debug('Request URL changed to {}. Path={}.',
                              request.url, request.file_path)

        return is_file
311995
function convertToCompressedRequest(req, res, compression) {
        var type = mime.lookup(req.path);
        var charset = mime.charsets.lookup(type);
        var search = req.url.split('?').splice(1).join('?');

        if (search !== "") {
            search = "?" + search;
        }

        req.url = req.path + compression.fileExtension + search;
        res.setHeader("Content-Encoding", compression.encodingName);
        res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : ""));
    }
1309082
def __upload_chunk(self, resource, chunk_size, bytes, bytes_start, bytes_read):
        """"""

        # note: string conversion required here due to open encoding bug in requests-oauthlib.
        headers = {
            'content-type': self.content_type,
            'content-length': str(min([chunk_size, self._file_size - bytes_read])),
            'content-range': "bytes {0}-{1}/{2}".format(
                bytes_start, bytes_read - 1, self._file_size)
        }

        return Request(self._client, 'put', resource,
                       domain=self._DEFAULT_DOMAIN, headers=headers, body=bytes).perform()
469838
function(req, res, next) {
        var initialTime = req.query.time,
            receivedReqTime = new Date().getTime(),
            filename = req.params.filename,
            absolutePathToFile = ontoDir + '/' + filename,
            extension = path.extname(absolutePathToFile),
            contentType = mime.contentType(extension);

        if(contentType) {
            req.mimeType = contentType.replace(/;.*/g, '');
        } else {
            req.mimeType = contentType;
        }

        req.requestDelay =  receivedReqTime - initialTime;

        fs.readFile(absolutePathToFile, function(err, data) {
            if(err) {
                res.status(500).send(err.toString());
            } else {
                req.rawOntology = data.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:');
                next();
            };
        });
    }
1100305
def __upload(self, resource, bytes):
        """"""

        # note: string conversion required here due to open encoding bug in requests-oauthlib.
        headers = {
            'x-ton-expires': http_time(self.options.get('x-ton-expires', self._DEFAULT_EXPIRE)),
            'content-length': str(self._file_size),
            'content-type': self.content_type
        }

        return Request(self._client, 'post', resource,
                       domain=self._DEFAULT_DOMAIN, headers=headers, body=bytes).perform()
1330947
function (mu, uriString, filename) {
        console.info('#green{[convert file]} ' + filename + ' #green{to data uri]}\n');
        return mu.replace(uriString, [
            'data:',
            mime.getType(filename),
            ';base64,',
            fs.readFileSync(filename).toString('base64')
        ].join(''));
    }