Copies the resource referenced in Resource#url
 to the local cache.

 If the resource is successully cached locally and the
 signature is verified the size of the resource is retured.

 If the signature is not verified then false is returned.
773393
def cache_resource(dest_dir=@local_cache_dir, options={})
      unless dest_dir
        raise ArgumentError, "Must specify destination directory when creating resource", caller
      end
      self.local_cache_dir=dest_dir
      @size = update_cache(@url, @local_path, options)
      if options[:include_pack_gz]
        @relative_local_path_pack_gz = "#{@relative_local_path}.pack.gz"
        @local_path_pack_gz = "#{dest_dir}/#{@relative_local_path_pack_gz}"
        @size_pack_gz = update_cache(@url_pack_gz, @local_path_pack_gz, options)
      end
      @signature_verified ? @size : @signature_verified
    end
544420
public static boolean doesResourceExist(final Resource res) {
        if (res != null) {
            try {
                IOUtils.read(res.getInputStream(), new byte[1]);
                return res.contentLength() > 0;
            } catch (final FileNotFoundException e) {
                LOGGER.trace(e.getMessage());
                return false;
            } catch (final Exception e) {
                LOGGER.trace(e.getMessage(), e);
                return false;
            }
        }
        return false;
    }
367900
def resource_size(self, resource_name): # pylint: disable=R0201
        
        cached_size = self.get_cached_resource_size(resource_name)
        if cached_size is not None:
            return cached_size["size"]

        # Not cached or cache timeout exceeded. Get the actual size and record
        # it in the cache.
        actual_size = self.get_actual_resource_size(resource_name)
        self.set_cached_resource_size(resource_name, actual_size)
        return actual_size
35577
static void copyResources(URL resourceUrl, File targetPath) throws IOException, URISyntaxException {
        if (resourceUrl == null) {
            return;
        }

        URLConnection urlConnection = resourceUrl.openConnection();

        /**
         * Copy resources either from inside jar or from project folder.
         */
        if (urlConnection instanceof JarURLConnection) {
            copyJarResourceToPath((JarURLConnection) urlConnection, targetPath);
        } else if (VFS_PROTOCOL.equals(resourceUrl.getProtocol())) {
            VirtualFile virtualFileOrFolder = VFS.getChild(resourceUrl.toURI());
            copyFromWarToFolder(virtualFileOrFolder, targetPath);
        } else {
            File file = new File(resourceUrl.getPath());
            if (file.isDirectory()) {
                for (File resourceFile : FileUtils.listFiles(file, null, true)) {
                    int index = resourceFile.getPath().lastIndexOf(targetPath.getName()) + targetPath.getName().length();
                    File targetFile = new File(targetPath, resourceFile.getPath().substring(index));
                    if (!targetFile.exists() || targetFile.length() != resourceFile.length()) {
                        if (resourceFile.isFile()) {
                            FileUtils.copyFile(resourceFile, targetFile);
                        }
                    }
                }
            } else {
                if (!targetPath.exists() || targetPath.length() != file.length()) {
                    FileUtils.copyFile(file, targetPath);
                }
            }
        }
    }
585922
private static void copyToLocal(Metadata src, Path dst) throws IOException {
    FileChannel dstCh = FileChannel.open(
        dst, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
    ReadableByteChannel srcCh = FileSystems.open(src.resourceId());
    long srcSize = src.sizeBytes();
    long copied = 0;
    do {
      copied += dstCh.transferFrom(srcCh, copied, srcSize - copied);
    } while (copied < srcSize);
    dstCh.close();
    srcCh.close();
    Preconditions.checkState(copied == srcSize);
  }
1087701
public static void copyResource(Resource.Readable readable,
                                    Resource.Writable writable) throws IOException {
        readable.useReader(reader -> writable.useWriter(writer -> IOUtils.copy(reader, writer)));
    }
955254
public void cache(String identifier, Object resource) {
		verifyState();

		if (!cacheLocked.get()) {
			resourceCache.get().put(identifier, resource);
		}
	}
1256508
function it_retains_the_original_state_of_the_instance_duplicated_with_new_query()
    {
        $original_uri = (string) $this->getWrappedObject();

        $new_query = $this->withQuery("garply");

        $this->__toString()->shouldReturn($original_uri);
    }
1185685
def _heighten(self, resource):
        
        original_width, original_height = resource.size

        target_height = self.value
        target_width = int((float(target_height) / original_height) * original_width)

        resource = resource.resize((target_width, target_height), Image.ANTIALIAS)

        return resource
531821
def _copy(self):
    """"""
    copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port,
                     self.uri.path, self.uri.query.copy())
    new_request = HttpRequest(uri=copied_uri, method=self.method,
                              headers=self.headers.copy())
    new_request._body_parts = self._body_parts[:]
    return new_request
558887
protected EncodedResource populateResourceIntoEntity(RequestDetails theRequest, IBaseResource theResource, ResourceTable theEntity, boolean theUpdateHash) {
		if (theEntity.getResourceType() == null) {
			theEntity.setResourceType(toResourceName(theResource));
		}

		if (theResource != null) {
			List<BaseResourceReferenceDt> refs = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, BaseResourceReferenceDt.class);
			for (BaseResourceReferenceDt nextRef : refs) {
				if (nextRef.getReference().isEmpty() == false) {
					if (nextRef.getReference().hasVersionIdPart()) {
						nextRef.setReference(nextRef.getReference().toUnqualifiedVersionless());
					}
				}
			}
		}

		byte[] bytes;
		ResourceEncodingEnum encoding;
		boolean changed = false;

		if (theEntity.getDeleted() == null) {

			encoding = myConfig.getResourceEncoding();
			Set<String> excludeElements = ResourceMetaParams.EXCLUDE_ELEMENTS_IN_ENCODED;
			theEntity.setFhirVersion(myContext.getVersion().getVersion());

			bytes = encodeResource(theResource, encoding, excludeElements, myContext);

			if (theUpdateHash) {
				HashFunction sha256 = Hashing.sha256();
				String hashSha256 = sha256.hashBytes(bytes).toString();
				if (hashSha256.equals(theEntity.getHashSha256()) == false) {
					changed = true;
				}
				theEntity.setHashSha256(hashSha256);
			}

			Set<ResourceTag> allDefs = new HashSet<>();
			Set<ResourceTag> allTagsOld = getAllTagDefinitions(theEntity);

			if (theResource instanceof IResource) {
				extractTagsHapi((IResource) theResource, theEntity, allDefs);
			} else {
				extractTagsRi((IAnyResource) theResource, theEntity, allDefs);
			}

			RuntimeResourceDefinition def = myContext.getResourceDefinition(theResource);
			if (def.isStandardType() == false) {
				String profile = def.getResourceProfile("");
				if (isNotBlank(profile)) {
					TagDefinition profileDef = getTagOrNull(TagTypeEnum.PROFILE, NS_JPA_PROFILE, profile, null);
					if (def != null) {
						ResourceTag tag = theEntity.addTag(profileDef);
						allDefs.add(tag);
						theEntity.setHasTags(true);
					}
				}
			}

			Set<ResourceTag> allTagsNew = getAllTagDefinitions(theEntity);
			Set<TagDefinition> allDefsPresent = new HashSet<>();
			allTagsNew.forEach(tag -> {

				// Don't keep duplicate tags
				if (!allDefsPresent.add(tag.getTag())) {
					theEntity.getTags().remove(tag);
				}

				// Drop any tags that have been removed
				if (!allDefs.contains(tag)) {
					if (shouldDroppedTagBeRemovedOnUpdate(theRequest, tag)) {
						theEntity.getTags().remove(tag);
					}
				}

			});

			if (!allTagsOld.equals(allTagsNew)) {
				changed = true;
			}
			theEntity.setHasTags(!allTagsNew.isEmpty());

		} else {
			theEntity.setHashSha256(null);
			bytes = null;
			encoding = ResourceEncodingEnum.DEL;
		}

		if (changed == false) {
			if (theEntity.getId() == null) {
				changed = true;
			} else {
				ResourceHistoryTable currentHistoryVersion = myResourceHistoryTableDao.findForIdAndVersion(theEntity.getId(), theEntity.getVersion());
				if (currentHistoryVersion == null || currentHistoryVersion.getResource() == null) {
					changed = true;
				} else {
					changed = !Arrays.equals(currentHistoryVersion.getResource(), bytes);
				}
			}
		}

		EncodedResource retVal = new EncodedResource();
		retVal.setEncoding(encoding);
		retVal.setResource(bytes);
		retVal.setChanged(changed);

		return retVal;
	}
1297226
def save(self, inplace=True):
        
        modified_data = self._modified_data()
        if bool(modified_data):
            extra = {
                'resource': self.__class__.__name__,
                'query': {
                    'id': self.id,
                    'modified_data': modified_data
                }
            }
            logger.info('Saving marker', extra=extra)
            data = self._api.patch(url=self._URL['get'].format(id=self.id),
                                   data=modified_data).json()
            marker = Marker(api=self._api, **data)
            return marker
        else:
            raise ResourceNotModified()
1297785
def reload(self):
        
        try:
            data = self._api.get(self.href, append_base=False).json()
            resource = File(api=self._api, **data)
        except Exception:
            try:
                data = self._api.get(
                    self._URL['get'].format(id=self.id)).json()
                resource = File(api=self._api, **data)
            except Exception:
                raise SbgError('Resource can not be refreshed!')

        self._data = resource._data
        self._dirty = resource._dirty
        self._old = copy.deepcopy(self._data.data)

        # If file.metadata = value was executed
        # file object will have attribute _method='PUT', which tells us
        # to force overwrite of metadata on the server. This is metadata
        # specific. Once we reload the resource we delete the attribute
        # _method from the instance.
        try:
            delattr(self, '_method')
        except AttributeError:
            pass
693208
private void ensureCapacity(int requestedCapacity) {

        if (requestedCapacity > getCapacity()) {
            int newCapacity = getCapacity();
            while (requestedCapacity > newCapacity) {
                newCapacity = (newCapacity * 3) / 2;
            }
            reallocateBuffer(newCapacity);
        }
    }
403624
def _update_inplace(self, result, verify_is_copy=True):
        
        # NOTE: This does *not* call __finalize__ and that's an explicit
        # decision that we may revisit in the future.

        self._reset_cache()
        self._clear_item_cache()
        self._data = getattr(result, '_data', result)
        self._maybe_update_cacher(verify_is_copy=verify_is_copy)
813148
public static void copyResource(String resource, File destination) throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            is = FileUtils.class.getResourceAsStream("/" + resource);
            fos = new FileOutputStream(destination);

            final byte[] buffer = new byte[10 * 1024];
            int len;
            while ((len = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } finally {
            close(is);
            close(fos);
        }

    }
625358
@GuardedBy("mLock")
  private boolean maybeUpdateFileCacheSize() {
    long now = mClock.now();
    if ((!mCacheStats.isInitialized()) ||
        mCacheSizeLastUpdateTime == UNINITIALIZED ||
        (now - mCacheSizeLastUpdateTime) > FILECACHE_SIZE_UPDATE_PERIOD_MS) {
      return maybeUpdateFileCacheSizeAndIndex();
    }
    return false;
  }