Attach a remote file to activity with was generated by relationship.
        :param data_service: DataServiceApi: service used to attach relationship
        :param file_details: dict: response from DukeDS POST to /files/ containing current_version id
480178
def run(self, data_service, file_details):
        
        file_version_id = file_details['current_version']['id']
        data_service.create_was_generated_by_relation(self.activity.id, KindType.file_str, file_version_id)
        used_entity_id = self._lookup_used_entity_id(file_details)
        data_service.create_was_derived_from_relation(used_entity_id, KindType.file_str,
                                                      file_version_id, KindType.file_str)
77530
def attach_file_to_idea(self, filename, *args, **kwargs):
        
        kwargs.update({'file': {'attachment': open(filename, 'rb')}})
        return bind_api(
            api=self,
            path='/ideas/{ideaId}/attach',
            method='POST',
            payload_type='idea',
            allowed_param=['ideaId']
        )(*args, **kwargs)
321706
def addDataset(self):
        
        self._openRepo()
        dataset = datasets.Dataset(self._args.datasetName)
        dataset.setDescription(self._args.description)
        dataset.setAttributes(json.loads(self._args.attributes))
        self._updateRepo(self._repo.insertDataset, dataset)
1129600
def _get_attachment_data(self, id, filename):
        
        uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename])
        return uri, {}, 'get', None, None, False
76400
def tablib_export_action(modeladmin, request, queryset, file_type="xls"):
    

    dataset = SimpleDataset(queryset, headers=None)
    filename = '{0}.{1}'.format(
        smart_str(modeladmin.model._meta.verbose_name_plural), file_type)

    response_kwargs = {
        'content_type': get_content_type(file_type)
    }

    response = HttpResponse(getattr(dataset, file_type), **response_kwargs)
    response['Content-Disposition'] = 'attachment; filename={0}'.format(
        filename)
    return response
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
183835
def send_file(service, file, fileName=None, password=None, ignoreVersion=False):

    if checkServerVersion(service, ignoreVersion=ignoreVersion) == False:
        print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m')

    ''' '''
    fileName = fileName if fileName != None else os.path.basename(file.name)

    print('Encrypting data from "' + fileName + '"')
    keys = secretKeys()
    encData = encrypt_file(file, keys)
    encMeta = encrypt_metadata(keys, fileName)

    print('Uploading "' + fileName + '"')
    secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys)

    if password != None:
        print('Setting password')
        sendclient.password.set_password(secretUrl, owner_token, password)

    return secretUrl, fileId, owner_token
1170619
def upload_datafile(self, project_owner, project_id, file_obj,
                        chunk_size=CHUNK_SIZE, force_chunked=False):
        

        simple_upload_url = 'users/%s/projects/%s/datasets/upload' % (
            project_owner, project_id
        )
        chunked_upload_url = 'users/%s/projects/%s/datasets/chunked_upload' % (
            project_owner, project_id
        )

        return self.upload_file(simple_upload_url, chunked_upload_url,
                                file_obj, chunk_size=chunk_size,
                                force_chunked=force_chunked)
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
519535
def _fetch_remote_file(service_url, params=None, use_http_post=False):
    
    if not params:
        params = {}

    request_url, response = _fetch_remote(service_url, params, use_http_post)
    dummy, params = cgi.parse_header(
            response.headers.get('Content-Disposition', ''))
    fn = params['filename']

    return (response.headers.get('content-type'),
            fn, response.read(), response.geturl())
324287
def _set_manifest_data(self, files_list):
        
        if files_list:
            data = ",".join(files_list)
            self.s3.put_object(Bucket=self.sitename,
                               Key=self.manifest_file,
                               Body=data,
                               ACL='private')
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;

    }
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)
782843
def upload_attachment(storage, attachment, raise_exceptions)
      begin
        # attachment is already a file or we need to open the file from disk
        unless attachment.respond_to?(:path) && attachment.respond_to?(:read)
          raise "file does not exist: #{attachment}" unless File.exists?(attachment)
          attachment = File.open(attachment, 'rb')
        end

        # there are two different upload methods: AWS S3 and ITRP local storage
        key_template = "#{storage[:upload_path]}#{FILENAME_TEMPLATE}"
        key = key_template.gsub(FILENAME_TEMPLATE, File.basename(attachment.path))
        upload_method = storage[:provider] == AWS_PROVIDER ? :aws_upload : :itrp_upload
        send(upload_method, storage, key_template, key, attachment)

        # return the values for the note_attachments param
        {key: key, filesize: File.size(attachment.path)}
      rescue ::Exception => e
        report_error("Attachment upload failed: #{e.message}", raise_exceptions)
        nil
      end
    end
889574
def connect(service_account, credentials_file_path, api_version='v2'):
    

    # Create an httplib2.Http object to handle our HTTP requests an
    # authorize it with the Credentials. Note that the first parameter,
    # service_account_name, is the Email address created for the Service
    # account. It must be the email address associated with the key that
    # was created.
    scope = 'https://www.googleapis.com/auth/androidpublisher'
    credentials = ServiceAccountCredentials.from_p12_keyfile(service_account, credentials_file_path, scopes=scope)
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('androidpublisher', api_version, http=http, cache_discovery=False)

    return service
718242
def _attach_files(self, files_info):
        

        if not files_info.empty:
            if (len(files_info.index.unique()) != len(files_info)):
                estr = 'WARNING! Duplicate datetimes in provided file '
                estr = '{:s}information.\nKeeping one of each '.format(estr)
                estr = '{:s}of the duplicates, dropping the rest.'.format(estr)
                print(estr)
                print(files_info.index.get_duplicates())

                idx = np.unique(files_info.index, return_index=True)
                files_info = files_info.ix[idx[1]]
                #raise ValueError('List of files must have unique datetimes.')

            self.files = files_info.sort_index()
            date = files_info.index[0]
            self.start_date = pds.datetime(date.year, date.month, date.day)
            date = files_info.index[-1]
            self.stop_date = pds.datetime(date.year, date.month, date.day)
        else:
            self.start_date = None
            self.stop_date = None
            # convert to object type
            # necessary if Series is empty, enables == checks with strings
            self.files = files_info.astype(np.dtype('O'))
1186994
@Override
   public void newEmbeddedRelationship(
            final Project project,
            final JavaResource resource,
            final String fieldName,
            final String fieldType) throws FileNotFoundException
   {
      JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
      JavaClassSource entityClass = getJavaClassFrom(resource);
      JavaClassSource fieldEntityClass;
      if (areTypesSame(fieldType, entityClass.getCanonicalName()))
      {
         fieldEntityClass = entityClass;
      }
      else
      {
         fieldEntityClass = findEntity(project, fieldType);
         entityClass.addImport(fieldEntityClass);
      }

      addFieldTo(entityClass, fieldEntityClass.getName(), fieldName,
               Embedded.class.getName());
      java.saveJavaSource(entityClass);
   }