Create a patch representing what we actually processed. This may contain some fixed content hashes for removed
modules.

@param original the original
@return the processed patch
348551
protected Patch createProcessedPatch(final Patch original) {

        // Process elements
        final List<PatchElement> elements = new ArrayList<PatchElement>();
        // Process layers
        for (final PatchEntry entry : getLayers()) {
            final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);
            elements.add(element);
        }
        // Process add-ons
        for (final PatchEntry entry : getAddOns()) {
            final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications);
            elements.add(element);
        }

        // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications
        return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications);
    }
1250404
public static Filter<FetchData> adaptFilterHttpResponse2FetchData(final Filter<HttpResponse> original) {
		return new AbstractFilter<FetchData>() {
			@Override
			public boolean apply(FetchData x) {
				return original.apply(x.response());
			}
			@Override
			public String toString() {
				return original.toString();
			}
			@Override
			public Filter<FetchData> copy() {
				return adaptFilterHttpResponse2FetchData(original.copy());
			}
		};
	}
106686
protected T createCopy (Kryo kryo, T original) {
		return (T)kryo.newInstance(original.getClass());
	}
439477
@SuppressWarnings("unchecked")
	public static <T> T shallowCopy(T original) {
		
		Class<? extends T> clazz = (Class<? extends T>) original.getClass();
		BeanClass<? extends T> beanClass = (BeanClass<? extends T>) classes.get(clazz);
		
		if (beanClass == null) {
			beanClass = BeanClass.buildFrom(clazz);
			classes.put(clazz, beanClass);
		}
		
		return shallowCopyHelper(original, beanClass);
	}
859370
def _patch_original_class(self):
        
        cls = self._cls
        base_names = self._base_names

        # Clean class of attribute definitions (`attr.ib()`s).
        if self._delete_attribs:
            for name in self._attr_names:
                if (
                    name not in base_names
                    and getattr(cls, name, None) is not None
                ):
                    try:
                        delattr(cls, name)
                    except AttributeError:
                        # This can happen if a base class defines a class
                        # variable and we want to set an attribute with the
                        # same name by using only a type annotation.
                        pass

        # Attach our dunder methods.
        for name, value in self._cls_dict.items():
            setattr(cls, name, value)

        # Attach __setstate__. This is necessary to clear the hash code
        # cache on deserialization. See issue
        # https://github.com/python-attrs/attrs/issues/482 .
        # Note that this code only handles setstate for dict classes.
        # For slotted classes, see similar code in _create_slots_class .
        if self._cache_hash:
            existing_set_state_method = getattr(cls, "__setstate__", None)
            if existing_set_state_method:
                raise NotImplementedError(
                    "Currently you cannot use hash caching if "
                    "you specify your own __setstate__ method."
                    "See https://github.com/python-attrs/attrs/issues/494 ."
                )

            def cache_hash_set_state(chss_self, _):
                # clear hash code cache
                setattr(chss_self, _hash_cache_field, None)

            setattr(cls, "__setstate__", cache_hash_set_state)

        return cls
705542
public static Date newDate(final Date original) {
        return original != null ? new Date(original.getTime()) : null;
    }
1126504
def patch(self):
        """"""
        original = self.__dict__['__original__']
        return jsonpatch.make_patch(original, dict(self)).to_string()
1366847
private static boolean patchShadedLibraryId(byte[] bytes, String originalName, String name) {
        // Our native libs always have the name as part of their id so we can search for it and replace it
        // to make the ID unique if shading is used.
        byte[] nameBytes = originalName.getBytes(CharsetUtil.UTF_8);
        int idIdx = -1;

        // Be aware this is a really raw way of patching a dylib but it does all we need without implementing
        // a full mach-o parser and writer. Basically we just replace the the original bytes with some
        // random bytes as part of the ID regeneration. The important thing here is that we need to use the same
        // length to not corrupt the mach-o header.
        outerLoop: for (int i = 0; i < bytes.length && bytes.length - i >= nameBytes.length; i++) {
            int idx = i;
            for (int j = 0; j < nameBytes.length;) {
                if (bytes[idx++] != nameBytes[j++]) {
                    // Did not match the name, increase the index and try again.
                    break;
                } else if (j == nameBytes.length) {
                    // We found the index within the id.
                    idIdx = i;
                    break outerLoop;
                }
            }
        }

        if (idIdx == -1) {
            logger.debug("Was not able to find the ID of the shaded native library {}, can't adjust it.", name);
            return false;
        } else {
            // We found our ID... now monkey-patch it!
            for (int i = 0; i < nameBytes.length; i++) {
                // We should only use bytes as replacement that are in our UNIQUE_ID_BYTES array.
                bytes[idIdx + i] = UNIQUE_ID_BYTES[PlatformDependent.threadLocalRandom()
                                                                    .nextInt(UNIQUE_ID_BYTES.length)];
            }

            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Found the ID of the shaded native library {}. Replacing ID part {} with {}",
                        name, originalName, new String(bytes, idIdx, nameBytes.length, CharsetUtil.UTF_8));
            }
            return true;
        }
    }
809615
public int originalSize()
    {
        Block<T> currentHeadBlock = getHeadBlock();
        int head = currentHeadBlock.head();
        int size = 0;
        while (true)
        {
            if (head == getBlockSize())
            {
                Block<T> nextHeadBlock = currentHeadBlock.next();
                if (nextHeadBlock == null)
                {
                    break;
                }
                else
                {
                    // Use next block and loop
                    currentHeadBlock = nextHeadBlock;
                    head = currentHeadBlock.head();
                }
            }
            else
            {
                Object element = currentHeadBlock.peek(head);
                if (element == REMOVED_ELEMENT)
                {
                    // Already removed, try next index
                    ++head;
                }
                else if (element != null)
                {
                    ++size;
                    ++head;
                }
                else
                {
                    break;
                }
            }
        }
        return size;
    }
278334
public LinkedList<Patch> patch_make(String text1, String text2) {
        if (text1 == null || text2 == null) {
            throw new IllegalArgumentException("Null inputs. (patch_make)");
        }
        // No diffs provided, compute our own.
        LinkedList<Diff> diffs = diff_main(text1, text2, true);
        if (diffs.size() > 2) {
            diff_cleanupSemantic(diffs);
            diff_cleanupEfficiency(diffs);
        }
        return patch_make(text1, diffs);
    }
906007
private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {
        final List<File> processed = new ArrayList<File>();
        List<File> reenabled = Collections.emptyList();
        List<File> disabled = Collections.emptyList();
        try {
            try {
                // Update the state to invalidate and process module resources
                if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {
                    if (mode == PatchingTaskContext.Mode.APPLY) {
                        // Only invalidate modules when applying patches; on rollback files are immediately restored
                        for (final File invalidation : moduleInvalidations) {
                            processed.add(invalidation);
                            PatchModuleInvalidationUtils.processFile(this, invalidation, mode);
                        }
                        if (!modulesToReenable.isEmpty()) {
                            reenabled = new ArrayList<File>(modulesToReenable.size());
                            for (final File path : modulesToReenable) {
                                reenabled.add(path);
                                PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);
                            }
                        }
                    } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {
                        if (!modulesToDisable.isEmpty()) {
                            disabled = new ArrayList<File>(modulesToDisable.size());
                            for (final File path : modulesToDisable) {
                                disabled.add(path);
                                PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);
                            }
                        }
                    }

                }
                modification.complete();
                callback.completed(this);
                state = State.COMPLETED;
            } catch (Exception e) {
                this.moduleInvalidations.clear();
                this.moduleInvalidations.addAll(processed);
                this.modulesToReenable.clear();
                this.modulesToReenable.addAll(reenabled);
                this.modulesToDisable.clear();
                this.moduleInvalidations.addAll(disabled);
                throw new RuntimeException(e);
            }
        } finally {
            if (state != State.COMPLETED) {
                try {
                    modification.cancel();
                } finally {
                    try {
                        undoChanges();
                    } finally {
                        callback.operationCancelled(this);
                    }
                }
            } else  {
                try {
                    if (checkForGarbageOnRestart) {
                        final File cleanupMarker = new File(installedImage.getInstallationMetadata(), "cleanup-patching-dirs");
                        cleanupMarker.createNewFile();
                    }
                    storeFailedRenaming();
                } catch (IOException e) {
                    PatchLogger.ROOT_LOGGER.debugf(e, "failed to create cleanup marker");
                }
            }
        }
    }
544818
protected String resolveIOSPlaceholders(String original) {
    int index = 1;
    String resolved = original;

    final Pattern pattern = Pattern.compile("%[a-zA-Z@]");
    final Matcher matcher = pattern.matcher(original);
    while (matcher.find()) {
      String placeholderIOS = matcher.group();
      String placeholderAndroid = placeholderMap.get(placeholderIOS);
      if (placeholderAndroid != null) {
        placeholderAndroid = String.format(placeholderAndroid, index++);
        resolved = resolved.replaceFirst(placeholderIOS, placeholderAndroid);
      }
    }

    return resolved;
  }
869440
function patchClass(className) {
    var OriginalClass = _global[className];
    if (!OriginalClass)
        return;
    // keep original class in global
    _global[zoneSymbol(className)] = OriginalClass;
    _global[className] = function () {
        var a = bindArguments(arguments, className);
        switch (a.length) {
            case 0:
                this[originalInstanceKey] = new OriginalClass();
                break;
            case 1:
                this[originalInstanceKey] = new OriginalClass(a[0]);
                break;
            case 2:
                this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
                break;
            case 3:
                this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
                break;
            case 4:
                this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
                break;
            default:
                throw new Error('Arg list too long.');
        }
    };
    // attach original delegate to patched function
    attachOriginToPatched(_global[className], OriginalClass);
    var instance = new OriginalClass(function () { });
    var prop;
    for (prop in instance) {
        // https://bugs.webkit.org/show_bug.cgi?id=44721
        if (className === 'XMLHttpRequest' && prop === 'responseBlob')
            continue;
        (function (prop) {
            if (typeof instance[prop] === 'function') {
                _global[className].prototype[prop] = function () {
                    return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
                };
            }
            else {
                Object.defineProperty(_global[className].prototype, prop, {
                    set: function (fn) {
                        if (typeof fn === 'function') {
                            this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);
                            // keep callback in wrapped function so we can
                            // use it in Function.prototype.toString to return
                            // the native one.
                            attachOriginToPatched(this[originalInstanceKey][prop], fn);
                        }
                        else {
                            this[originalInstanceKey][prop] = fn;
                        }
                    },
                    get: function () {
                        return this[originalInstanceKey][prop];
                    }
                });
            }
        }(prop));
    }
    for (prop in OriginalClass) {
        if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
            _global[className][prop] = OriginalClass[prop];
        }
    }
}
992790
function patchIt(specs) {
  var original = it;
  var restore = function() {
    it = original;
    xit = it.skip;
  };

  var createSpec = function(name, fn, opts) {
    opts = opts || {};

    var spec = {
      name: name,
      getPromise: function() {
        var start = Date.now();
        return createWrapper(fn, spec.ctx)().then(function(duration) {
          spec.duration = duration;
        });
      },
      duration: 0,
      only: opts.only || null,
      skip: opts.skip || null,
      timeout: null,
      error: null,
      promise: null
    };

    spec.ctx = new ContextProxy(spec);
    specs.push(spec);
  };

  it = function it(name, fn) {
    createSpec(name, fn, {skip: !fn});
  };

  xit = it.skip = function skip(name, fn) {
    createSpec(name, fn, {skip: true});
  };

  it.only = function only(name, fn) {
    createSpec(name, fn, {only: true});
  };

  return restore;
}
532129
public String create(String id, Integer size, HashSet<String> data, String originalVersion)
      throws IOException {
    if (collectionCachePath != null) {
      // initialization
      Date date = clear();
      // create always new version, unless explicit original version is provided
      String version;
      if(originalVersion!=null&&versionToItem.containsKey(originalVersion)) {
        version = originalVersion;
      } else {
        do {
          version = UUID.randomUUID().toString();
        } while (versionToItem.containsKey(version));
      }  
      // create new item
      MtasSolrCollectionCacheItem item;
      if (id != null) {
        item = new MtasSolrCollectionCacheItem(id, size, data);
        // remove if item with id already exists
        deleteById(id);
      } else {
        item = new MtasSolrCollectionCacheItem(version, size, data);
      }
      // register
      idToVersion.put(id, version);
      expirationVersion.put(version, date.getTime() + (1000 * lifeTime));
      versionToItem.put(version, item);
      // store data in file
      File file = collectionCachePath.resolve(version).toFile();
      try (OutputStream outputStream = new FileOutputStream(file);
          Writer outputStreamWriter = new OutputStreamWriter(outputStream,
              StandardCharsets.UTF_8);) {
        outputStreamWriter.write(encode(item));
        // set correct time to reconstruct administration on restart
        if (!file.setLastModified(date.getTime())) {
          log.debug("couldn't change filetime " + file.getAbsolutePath());
        }
        // don't store data in memory
        item.data = null;
        // return version
        return version;
      } catch (IOException e) {
        idToVersion.remove(id);
        expirationVersion.remove(version);
        versionToItem.remove(version);
        throw new IOException("couldn't create " + version, e);
      }
    } else {
      throw new IOException("no cachePath available, can't store data");
    }
  }
589069
public void restoreOriginal() {
    if (original == null) {
      throw new IllegalStateException("Original EbeanServer instance is null");
    }
    if (original.getName() == null) {
      throw new IllegalStateException("Original EbeanServer name is null");
    }

    // restore the original EbeanServer back
    Ebean.mock(original.getName(), original, true);
  }
1312365
private MetaMethod specialCasedOverrideForCreate(final Method m) {
        return new MetaMethod() {

            @Override
            public int getModifiers() {
                return m.getModifiers();
            }

            @Override
            public String getName() {
                return m.getName();
            }

            @Override
            public Class<?> getReturnType() {
                return m.getReturnType();
            }

            @Override
            public CachedClass getDeclaringClass() {
                return ReflectionCache.getCachedClass(m.getDeclaringClass());
            }

            @Override
            @SuppressWarnings("unchecked")
            public Object invoke(Object object, final Object[] arguments) {
                return Observable.create(new GroovyCreateWrapper((Closure) arguments[0]));
            }

            @Override
            public CachedClass[] getParameterTypes() {
                if (parameterTypes == null) {
                    getParametersTypes0();
                }

                return parameterTypes;
            }

            private synchronized void getParametersTypes0() {
                if (parameterTypes != null)
                    return;

                Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes;

                CachedClass[] pt = new CachedClass [npt.length];
                for (int i = 0; i != npt.length; ++i) {
                    if (Function.class.isAssignableFrom(npt[i])) {
                        // function type to be replaced by closure
                        pt[i] = ReflectionCache.getCachedClass(Closure.class);
                    } else {
                        // non-function type
                        pt[i] = ReflectionCache.getCachedClass(npt[i]);
                    }
                }

                nativeParamTypes = npt;
                setParametersTypes(pt);
            }

            @Override
            protected Class[] getPT() {
                return m.getParameterTypes();
            }
        };
    }