Creates a file handle and optionally attach an io.
 The provided file argument is expected to contain at minimum
 a name, type and parent_id. If it has a mimetype that will be assumed to
 match the mimetype of the io.
438853
def create_entity(file, io = nil, properties = {})
      params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties)
      params[:parentid] = file.parent_id unless file.parent_id.nil?

      if params[:properties]
        params[:properties] = params[:properties].to_json
      end

      file_handle = unless file.id
        response = get('/createFile', params)
        File.from_json(response.body['file'])
      else
        file
      end

      if io
        HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger)
        file_handle.size = io.size
      end

      file_handle
    end
276662
def add_file(self, name, required=False, error=None, extensions=None):
        
        if name is None:
            return
        self.file_arguments.append(dict(
            name=name,
            required=required,
            error=error,
            extensions=extensions))
505521
def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True,
           accept_context=False):
    """"""
    extend = extend if type(extend) == type else type(extend)

    def new_type_handler(function):
        class NewType(extend):
            __slots__ = ()
            _accept_context = accept_context

            if chain and extend != Type:
                if error_text or exception_handlers:
                    if not accept_context:
                        def __call__(self, value):
                            try:
                                value = super(NewType, self).__call__(value)
                                return function(value)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        if extend._accept_context:
                            def __call__(self, value, context):
                                try:
                                    value = super(NewType, self).__call__(value, context)
                                    return function(value, context)
                                except Exception as exception:
                                    for take_exception, rewrite in exception_handlers.items():
                                        if isinstance(exception, take_exception):
                                            if isinstance(rewrite, str):
                                                raise ValueError(rewrite)
                                            else:
                                                raise rewrite(value)
                                    if error_text:
                                        raise ValueError(error_text)
                                    raise exception
                        else:
                            def __call__(self, value, context):
                                try:
                                    value = super(NewType, self).__call__(value)
                                    return function(value, context)
                                except Exception as exception:
                                    for take_exception, rewrite in exception_handlers.items():
                                        if isinstance(exception, take_exception):
                                            if isinstance(rewrite, str):
                                                raise ValueError(rewrite)
                                            else:
                                                raise rewrite(value)
                                    if error_text:
                                        raise ValueError(error_text)
                                    raise exception
                else:
                    if not accept_context:
                        def __call__(self, value):
                            value = super(NewType, self).__call__(value)
                            return function(value)
                    else:
                        if extend._accept_context:
                            def __call__(self, value, context):
                                value = super(NewType, self).__call__(value, context)
                                return function(value, context)
                        else:
                            def __call__(self, value, context):
                                value = super(NewType, self).__call__(value)
                                return function(value, context)
            else:
                if not accept_context:
                    if error_text or exception_handlers:
                        def __call__(self, value):
                            try:
                                return function(value)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        def __call__(self, value):
                            return function(value)
                else:
                    if error_text or exception_handlers:
                        def __call__(self, value, context):
                            try:
                                return function(value, context)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        def __call__(self, value, context):
                            return function(value, context)

        NewType.__doc__ = function.__doc__ if doc is None else doc
        if auto_instance and not (introspect.arguments(NewType.__init__, -1) or
                                  introspect.takes_kwargs(NewType.__init__) or
                                  introspect.takes_args(NewType.__init__)):
            return NewType()
        return NewType

    return new_type_handler
827089
def addAttachment(self, oid, file_path):
        
        if self.hasAttachments == True:
            attachURL = self._url + "/%s/addAttachment" % oid
            params = {'f':'json'}
            parsed = urlparse.urlparse(attachURL)

            files = {'attachment': file_path}
            res = self._post(url=attachURL,
                             param_dict=params,
                             files=files,
                             securityHandler=self._securityHandler,
                             proxy_port=self._proxy_port,
                             proxy_url=self._proxy_url)
            return self._unicode_convert(res)
        else:
            return "Attachments are not supported for this feature service."
1201237
def add_file(self, file_to_add):
        
        from .files import File
        assert isinstance(file_to_add, File), "Files being added must be instances of a subclass of File class"
        file_to_add.node = self
        if file_to_add not in self.files:
            self.files.append(file_to_add)
1310876
def attach(self, id, filename, url):
        
        Attachment = self.client.model('ir.attachment')
        return Attachment.add_attachment_from_url(
            filename, url, '%s,%s' % (self.model_name, id)
        )
990036
private File createAttachFile(int pid) throws IOException {
        String fn = ".attach_pid" + pid;
        String path = "/proc/" + pid + "/cwd/" + fn;
        File f = new File(path);
        try {
            f.createNewFile();
        } catch (IOException x) {
            f = new File(tmpdir, fn);
            f.createNewFile();
        }
        return f;
    }
1146516
def _create_attachment(self, filename, content, mimetype=None):
        """"""
        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(filename)
            if mimetype is None:
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
        basetype, subtype = mimetype.split("/", 1)
        if basetype == "text":
            attachment = SafeMIMEText(
                smart_bytes(content, DEFAULT_CHARSET), subtype, DEFAULT_CHARSET
            )
        else:
            # Encode non-text attachments with base64.
            attachment = MIMEBase(basetype, subtype)
            attachment.set_payload(content)
            encode_base64(attachment)
        if filename:
            attachment.add_header(
                "Content-Disposition", "attachment", filename=filename
            )
        return attachment
318825
private synchronized void prepareFile() throws IOException{
		outputFile = new File(getFileName());
		if(outputFile.exists()) 
			outputFile.delete();
		if(outputFile.isDirectory())
			throw new IOException("I/O Error on creating file: File is a directory!");
		outputFile.createNewFile();
		if(!outputFile.canWrite())
			throw new IOException("I/O Error on creating file: Unable to write into file!");
	}
822040
protected <P extends ParsedResume> P addFileThenHandleParseResume(Class<? extends FileEntity> type, Integer entityId,
                                                                    MultipartFile multipartFile, String externalId, FileParams fileParams, ResumeFileParseParams params) {
        FileWrapper fileWrapper = handleAddFileWithMultipartFile(type, entityId, multipartFile, externalId, fileParams, true);
        P parsedResume = this.handleParseResumeFile(multipartFile, params);
        if (!parsedResume.isError()) {
            parsedResume.setFileWrapper(fileWrapper);
        }

        return parsedResume;

    }
209660
def create_transient_document(file_name, mime_type, file_handle)
      transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type)
      transient_document_response.fetch("transientDocumentId")
    end
510571
def make_stream(
    name,  # type: Text
    bin_file,  # type: RawIOBase
    mode="r",  # type: Text
    buffering=-1,  # type: int
    encoding=None,  # type: Optional[Text]
    errors=None,  # type: Optional[Text]
    newline="",  # type: Optional[Text]
    line_buffering=False,  # type: bool
    **kwargs  # type: Any
):
    # type: (...) -> IO
    
    reading = "r" in mode
    writing = "w" in mode
    appending = "a" in mode
    binary = "b" in mode
    if "+" in mode:
        reading = True
        writing = True

    encoding = None if binary else (encoding or "utf-8")

    io_object = RawWrapper(bin_file, mode=mode, name=name)  # type: io.IOBase
    if buffering >= 0:
        if reading and writing:
            io_object = io.BufferedRandom(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )
        elif reading:
            io_object = io.BufferedReader(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )
        elif writing or appending:
            io_object = io.BufferedWriter(
                typing.cast(io.RawIOBase, io_object),
                buffering or io.DEFAULT_BUFFER_SIZE,
            )

    if not binary:
        io_object = io.TextIOWrapper(
            io_object,
            encoding=encoding,
            errors=errors,
            newline=newline,
            line_buffering=line_buffering,
        )

    return io_object
914977
def uploadFileToIM (self, directory, filename, title):
        
        self.logger.debug("uploadFileToIM(" + "{},{},{})".format(directory, filename, title))
        parameters = {'data-filename-placement':'inside',
                      'title':str(filename),
                      'filename':str(filename),
                      'type':'file',
                      'name':'files',
                      'id':'fileToUpload',
                      'multiple':''
                      }
        file_dict = {'files':(str(filename), open(directory + filename, 'rb'), 'application/x-rpm')}
        m = MultipartEncoder(fields=file_dict)
        
        temp_username = self._username
        temp_password = self._password
        temp_im_api_url = self._im_api_url
        temp_im_session = requests.Session()
        temp_im_session.mount('https://', TLS1Adapter())
        temp_im_verify_ssl = self._im_verify_ssl

        resp = temp_im_session.post(
            "{}/{}".format(temp_im_api_url,"types/InstallationPackage/instances/uploadPackage"),
            auth=HTTPBasicAuth(temp_username, temp_password),
            #headers = m.content_type,
            files = file_dict,
            verify = False,
            data = parameters
            )
        self.logger.info("Uploaded: " + "{}".format(filename))
        self.logger.debug("HTTP Response: " + "{}".format(resp.status_code))
1216829
def to_file(type, name)
      file = File.expand_path(options['path'])
      resource_class = parse_type(type)
      client_setup
      resource = resource_class.find_by(@client, name: name).first
      fail_nice "#{resource_class.name.split('::').last} '#{name}' not found" unless resource
      resource.to_file(file, options['format'])
      puts "Output to #{file}"
    rescue SystemCallError => e
      fail_nice "Failed to create file! (You may need to create the necessary directories). Message: #{e}"
    end
89275
def create_small_file(upload_context):
    
    data_service = upload_context.make_data_service()
    parent_data, path_data, remote_file_id = upload_context.params

    # The small file will fit into one chunk so read into memory and hash it.
    chunk = path_data.read_whole_file()
    hash_data = path_data.get_hash()

    # Talk to data service uploading chunk and creating the file.
    upload_operations = FileUploadOperations(data_service, upload_context)
    upload_id, url_info = upload_operations.create_upload_and_chunk_url(
        upload_context.project_id, path_data, hash_data, storage_provider_id=upload_context.config.storage_provider_id)
    upload_operations.send_file_external(url_info, chunk)
    return upload_operations.finish_upload(upload_id, hash_data, parent_data, remote_file_id)
22826
def file_add_types(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/addTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
1349478
def file_to_attachment(filename, filehandler=None):
    
    if filehandler:
        return {'_name': filename,
                'content': base64.b64encode(filehandler.read())
        }
    with open(filename, 'rb') as _file:
        return {'_name': filename,
                'content': base64.b64encode(_file.read())
        }