language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@JRubyMethod public static IRubyObject initialize(IRubyObject self) { ((RubyObject)self).fastSetInstanceVariable("@tags", RubyHash.newHash(self.getRuntime())); return self; }
python
def integrate(self, tmax, exact_finish_time=1): """ Main integration function. Call this function when you have setup your simulation and want to integrate it forward (or backward) in time. The function might be called many times to integrate the simulation in steps and create outputs in-between steps. ...
java
public static String getLibraryHeader(boolean verbose) { if (!verbose) return calimero + " version " + version; final StringBuffer buf = new StringBuffer(); buf.append(calimero).append(sep); buf.append("version ").append(version).append(sep); buf.append(tuwien).append(sep); buf.append(group).app...
python
def get_vendor_extension_fields(mapping): """ Identify vendor extension fields and extract them into a new dictionary. Examples: >>> get_vendor_extension_fields({'test': 1}) {} >>> get_vendor_extension_fields({'test': 1, 'x-test': 2}) {'x-test': 2} """ return {k: v fo...
python
def handle_exception(self, exc_info=None, rendered=False, source_hint=None): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ global _make_traceback if exc_info is None: ex...
java
private void handleInProvisionalState(final SipPacket msg) throws SipPacketParseException { if (msg.isRequest() && msg.isCancel()) { transition(CallState.CANCELLING, msg); return; } else if (msg.isRequest()) { // assuming this is either a re-transmission or ...
java
public static Map<String, Map<String, String>> addContext(final String key, final Map<String, String> data, final Map<String, Map<String, String>> context) { final Map<String, Map<String, String>> newdata = new HashMap<>(); if (null != contex...
python
def on_shutdown(self, broker): """Called during :meth:`Broker.shutdown`, informs callbacks registered with :meth:`add_handle_cb` the connection is dead.""" _v and LOG.debug('%r.on_shutdown(%r)', self, broker) fire(self, 'shutdown') for handle, (persist, fn) in self._handle_map.it...
java
public static float max(final float a, final float b) { if (a > b) { return a; } if (a < b) { return b; } /* if either arg is NaN, return NaN */ if (a != b) { return Float.NaN; } /* min(+0.0,-0.0) == -0.0 */ /* 0...
java
public <A> A createAliasForProperty(Class<A> cl, Expression<?> path) { return createProxy(cl, path); }
java
public boolean matches(Property property) { return property.getName().equals(key) && (value == WILDCARD_VALUE || property.getValue().asString().equals(value)); }
java
public ListRecoveryPointsByResourceResult withRecoveryPoints(RecoveryPointByResource... recoveryPoints) { if (this.recoveryPoints == null) { setRecoveryPoints(new java.util.ArrayList<RecoveryPointByResource>(recoveryPoints.length)); } for (RecoveryPointByResource ele : recoveryPoints...
python
def _validate_publish_parameters(body, exchange, immediate, mandatory, properties, routing_key): """Validate Publish Parameters. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The excha...
java
public InterfaceType getSuperType() { if ( _intfDecl.getSuperinterfaces() == null ) return null; for (InterfaceType intfType : _intfDecl.getSuperinterfaces()) { InterfaceDeclaration superDecl = intfType.getDeclaration(); if ( superDecl != null ) ...
python
def _parse_transaction_entry(entry): """ Validate & parse a transaction into (date, action, value) tuple. """ parts = entry.split() date_string = parts[0] try: date = datetime.datetime.strptime(date_string[:-1], '%Y-%m-%d').date() except ValueError: raise ValueError('Invalid date in...
java
@Override public List<String> getFormats(final String aBaseName) { Objects.requireNonNull(aBaseName); return Arrays.asList(FORMAT); }
python
def reconfig(main_parser, args=sys.argv[1:]): """Parse any config paths and reconfigure defaults with them http://docs.python.org/library/argparse.html#partial-parsing Return parsed remaining arguments""" parsed, remaining_args = parser().parse_known_args(args) configure(parsed.config_paths, os.ge...
java
public final void addAllHelperTexts(@NonNull final CharSequence... helperTexts) { Condition.INSTANCE.ensureNotNull(helperTexts, "The array may not be null"); addAllHelperTexts(Arrays.asList(helperTexts)); }
java
public ListenableFuture<KeyValue> compareAndSet(String key, SetValue setValue) { checkThatDistributedStoreIsActive(); KayVeeCommand.CASCommand casCommand = new KayVeeCommand.CASCommand(getCommandId(), key, setValue.getExpectedValue(), setValue.getNewValue()); return issueCommandToCluster(casComm...
java
public static spilloverpolicy[] get_filtered(nitro_service service, String filter) throws Exception{ spilloverpolicy obj = new spilloverpolicy(); options option = new options(); option.set_filter(filter); spilloverpolicy[] response = (spilloverpolicy[]) obj.getfiltered(service, option); return response; }
java
public <T> CallOptions withOption(Key<T> key, T value) { Preconditions.checkNotNull(key, "key"); Preconditions.checkNotNull(value, "value"); CallOptions newOptions = new CallOptions(this); int existingIdx = -1; for (int i = 0; i < customOptions.length; i++) { if (key.equals(customOptions[i][0...
python
def by_name(cls, session, name): """ Get a package from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the group :type name: `unicode :return: package instance :rtype: :class:`pyshop.mode...
java
public void setStart(int x1, int y1) { start.x = x1; start.y = y1; needsRefresh = true; }
python
def trusted(self, scope=None): """Return list of [(scope, trusted key), ...] for given scope.""" trust = [(x['scope'], x['vk']) for x in self.data['verifiers'] if x['scope'] in (scope, '+')] trust.sort(key=lambda x: x[0]) trust.reverse() return trust
python
def from_dict(cls, d, encoding='base64'): ''' Construct a ``Report`` object from dictionary. :type d: dictionary :param d: dictionary representing the report :param encoding: encoding of strings in the dictionary (default: 'base64') :return: Report object ''' ...
java
@Deprecated public List<Index> listIndices() { InputStream response = null; try { URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build(); response = client.couchDbClient.get(uri); return getResponseList(response, client.getGson(), DeserializationTyp...
python
def find_available_port(): """Find an available port. Simple trick: open a socket to localhost, see what port was allocated. Could fail in highly concurrent setups, though. """ s = socket.socket() s.bind(('localhost', 0)) _address, port = s.getsockname() s.close() return port
java
protected void createTraceArrayForParameters() { // Static methods don't have an implicit "this" argment so start // working with local var 0 instead of 1 for the parm list. int localVarOffset = isStatic ? 0 : 1; int syntheticArgs = 0; // Use an heuristic to guess when we're in ...
python
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} ...
python
def token_perplexity_micro(eval_data, predictions, scores, learner='ignored'): ''' Return the micro-averaged per-token perplexity `exp(-score / num_tokens)` computed over the entire corpus, as a length-1 list of floats. The log scores in `scores` should be base e (`exp`, `log`). >>> refs = [Instanc...
java
public void compose(List<URI> sources, URI destination, String contentType) throws IOException { StorageResourceId destResource = StorageResourceId.fromObjectName(destination.toString()); List<String> sourceObjects = Lists.transform( sources, uri -> StorageResourceId.fromObjectName(uri.toStr...
java
public Pattern<T, F> times(int from, int to) { checkIfNoNotPattern(); checkIfQuantifierApplied(); this.quantifier = Quantifier.times(quantifier.getConsumingStrategy()); if (from == 0) { this.quantifier.optional(); from = 1; } this.times = Times.of(from, to); return this; }
python
def parse_duplicate_stats(self, stats_file): """ Parses sambamba markdup output, returns series with values. :param str stats_file: sambamba output file with duplicate statistics. """ import pandas as pd series = pd.Series() try: with open(stats_file)...
java
public void setComplex_atIndex(int index, double real, double imag){ this.real[index] = real; this.imag[index] = imag; if(synchronizePowerSpectrum){ computePower(index); } }
python
def ignore_broken_pipe(): """ If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions. """ for f in sys.stdin, sys.std...
java
public BaseField setupField(int iFieldSeq) { BaseField field = null; //if (iFieldSeq == 0) //{ // field = new CounterField(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); // field.setHidden(true); //} //if (iFieldSeq == 1) //{ // fiel...
python
def write_size (self, url_data): """Write url_data.size.""" self.writeln(u"<tr><td>"+self.part("dlsize")+u"</td><td>"+ strformat.strsize(url_data.size)+ u"</td></tr>")
java
public void marshall(DescribeSubscriptionFiltersRequest describeSubscriptionFiltersRequest, ProtocolMarshaller protocolMarshaller) { if (describeSubscriptionFiltersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
python
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True ): """ Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we do...
python
def get_widget(self, page, language, fallback=Textarea): """Given the name of a placeholder return a `Widget` subclass like Textarea or TextInput.""" if isinstance(self.widget, str): widget = get_widget(self.widget) else: widget = self.widget try: ...
python
def get_commands(self): """Gets command that have been run and have not been redacted. """ shutit_global.shutit_global_object.yield_to_draw() s = '' for c in self.build['shutit_command_history']: if isinstance(c, str): #Ignore commands with leading spaces if c and c[0] != ' ': s += c + '\n' ...
python
def rankdata(inlist): """ Ranks the data in inlist, dealing with ties appropritely. Assumes a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. Usage: rankdata(inlist) Returns: a list of length equal to inlist, containing rank scores """ n = len(inlist) svec, ivec = shellsort(inlist) sumranks ...
java
public static FsInfoSector create(Fat32BootSector bs) throws IOException { final int offset = offset(bs); if (offset == 0) throw new IOException( "creating a FS info sector at offset 0 is strange"); final FsInfoSector result = new FsInfoSector(bs.getDevi...
python
def GetLocations(): """Return all cloud locations available to the calling alias.""" r = clc.v1.API.Call('post','Account/GetLocations',{}) if r['Success'] != True: if clc.args: clc.v1.output.Status('ERROR',3,'Error calling %s. Status code %s. %s' % ('Account/GetLocations',r['StatusCode'],r['Message'])) ...
java
public static Ref callRef(Callable function, Scriptable thisObj, Object[] args, Context cx) { if (function instanceof RefCallable) { RefCallable rfunction = (RefCallable)function; Ref ref = rfunction.refCall(cx, thisObj, args); if (ref == nul...
python
def _orient3dfast(plane, pd): """ Performs a fast 3D orientation test. Parameters ---------- plane: (3,3) float, three points in space that define a plane pd: (3,) float, a single point Returns ------- result: float, if greater than zero then pd is above the plane through ...
python
def is_image(filename): """Determine if given filename is an image.""" # note: isfile() also accepts symlinks return os.path.isfile(filename) and filename.lower().endswith(ImageExts)
python
def log_level_from_vebosity(verbosity): """ Get the `logging` module log level from a verbosity. :param verbosity: The number of times the `-v` option was specified. :return: The corresponding log level. """ if verbosity == 0: return logging.WARNING if verbosity == 1: return...
python
def update(self, match_set): """Update the classifier set from which the match set was drawn, e.g. by applying a genetic algorithm. The match_set argument is the MatchSet instance whose classifier set should be updated. Usage: match_set = model.match(situation) m...
python
def _varargs_checks_gen(self, decorated_function, function_spec, arg_specs): """ Generate checks for positional variable argument (varargs) testing :param decorated_function: function decorator :param function_spec: function inspect information :param arg_specs: argument specification (same as arg_specs in :me...
python
def compute_verdict(self, results): """ Match results to the configured reject, quarantine and accept classes, and return a verdict based on that. The verdict classes are matched in the order: reject_classes, quarantine_classes, accept_classes. This means that you can configure ...
java
public static boolean isSuperuser(String username) { UntypedResultSet result = selectUser(username); return !result.isEmpty() && result.one().getBoolean("super"); }
python
def aes_decrypt(key: bytes, cipher_text: bytes) -> bytes: """ AES-GCM decryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys cipher_text: bytes Encrypted text: nonce(16 bytes) + tag(16 bytes) + encrypted data Returns ...
python
def make_sshable(c): """ Set up passwordless SSH keypair & authorized_hosts access to localhost. """ user = c.travis.sudo.user home = "~{0}".format(user) # Run sudo() as the new sudo user; means less chown'ing, etc. c.config.sudo.user = user ssh_dir = "{0}/.ssh".format(home) # TODO: ...
java
protected void recordLocalNSDecl(Node node) { NamedNodeMap atts = ((Element) node).getAttributes(); int length = atts.getLength(); for (int i = 0; i < length; i++) { Node attr = atts.item(i); String localName = attr.getLocalName(); String attrPrefix = attr.g...
python
def _strip_ctype(name, ctype, protocol=2): """Strip the ctype from a channel name for the given nds server version This is needed because NDS1 servers store trend channels _including_ the suffix, but not raw channels, and NDS2 doesn't do this. """ # parse channel type from name (e.g. 'L1:GDS-CALIB_...
python
def path(filename): """Return full filename path for filename""" filename = unmap_file(filename) if filename not in file_cache: return None return file_cache[filename].path
java
public String splice(DNASequence sequence) { StringBuilder subData = new StringBuilder(); Location last = null; for (FeatureI f : this) { Location loc = f.location(); if (last == null || loc.startsAfter(last)) { subData.append(sequence.getSubSequence(loc.start(), loc.end()).toString()); last = loc...
java
public static Polygon makePolygon(Geometry shell, Geometry... holes) throws IllegalArgumentException { if(shell == null) { return null; } LinearRing outerLine = checkLineString(shell); LinearRing[] interiorlinestrings = new LinearRing[holes.length]; for (int i = 0; i ...
java
protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) { for (AnnounceResponseListener listener : this.listeners) { listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash); } }
python
def pmap(func, args, processes=None, callback=lambda *_, **__: None, **kwargs): """pmap(func, args, processes=None, callback=do_nothing, **kwargs) Parallel equivalent of ``map(func, args)``, with the additional ability of providing keyword arguments to func, and a callback function which is applied to ...
python
def component_activated(self, component): """Initialize additional member variables for components. Every component activated through the `Environment` object gets an additional member variable: `env` (the environment object) """ component.env = self super(Environment, s...
python
def sizeOfOverlap(self, e): """ Get the size of the overlap between self and e. :return: the number of bases that are shared in common between self and e. """ # no overlap if not self.intersects(e): return 0 # complete inclusion.. if e.start >= self.start and e.end <= self.end: ...
python
def estimate(self): """ Returns the estimate of the cardinality """ E = self.alpha * float(self.m ** 2) / np.power(2.0, - self.M).sum() if E <= 2.5 * self.m: # Small range correction V = self.m - np.count_nonzero(self.M) return int(self.m * np.log(self.m / flo...
python
def fs_decode(path): """ Decode a filesystem path using the proper filesystem encoding :param path: The filesystem path to decode from bytes or string :return: The filesystem path, decoded with the determined encoding :rtype: Text """ path = _get_path(path) if path is None: rai...
java
private int allocateNode(int d) { int id = 1; int initial = - (1 << d); // has last d bits = 0 and rest all = 1 byte val = value(id); if (val > d) { // unusable return -1; } while (val < d || (id & initial) == 0) { // id & initial == 1 << d for all ids at dept...
python
def write_ch (self, ch): '''This puts a character at the current cursor position. The cursor position is moved forward with wrap-around, but no scrolling is done if the cursor hits the lower-right corner of the screen. ''' if isinstance(ch, bytes): ch = self._decode(ch) ...
java
public final void ruleOpMultiAssign() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXbase.g:146:2: ( ( ( rule__OpMultiAssign__Alternatives ) ) ) // InternalXbase.g:147:2: ( ( rule__OpMultiAssign__Alternatives ) ) { ...
python
def plot(self, figure_list): ''' When each subscript is called, uses its standard plotting Args: figure_list: list of figures passed from the guit ''' #TODO: be smarter about how we plot ScriptIterator if self._current_subscript_stage is not None: ...
python
def center_widget_on_screen(widget, screen=None): """ Centers given Widget on the screen. :param widget: Current Widget. :type widget: QWidget :param screen: Screen used for centering. :type screen: int :return: Definition success. :rtype: bool """ screen = screen and screen or...
java
@Override public void start() { super.start(); // load the resource index for phase II use. String resIdxURL = syscfg.getResourceIndexURL(); try { final ResolvedResource resolvedResource = cache.resolveResource( ResourceType.RESOURCE_INDEX, resIdxURL)...
python
def makePalette(color1, color2, N, hsv=True): """ Generate N colors starting from `color1` to `color2` by linear interpolation HSV in or RGB spaces. :param int N: number of output colors. :param color1: first rgb color. :param color2: second rgb color. :param bool hsv: if `False`, interpola...
java
@SuppressWarnings({"WeakerAccess"}) public static void createNotification(final Context context, final Bundle extras) { createNotification(context, extras, Constants.EMPTY_NOTIFICATION_ID); }
python
def flush(self): """Empty the local queue and send its elements to be executed remotely. """ for elem in self: if elem.id[0] != scoop.worker: elem._delete() self.socket.sendFuture(elem) self.ready.clear() self.movable.clear()
java
public boolean inRanges(Instance instance, double[][] ranges) { boolean isIn = true; // updateRangesFirst must have been called on ranges for (int j = 0; isIn && (j < ranges.length); j++) { if (!instance.isMissing(j)) { double value = instance.value(j); isIn = value <= ranges[j][R...
python
def plotCastro(castroData, ylims, nstep=25, zlims=None): """ Make a color plot (castro plot) of the delta log-likelihood as a function of energy and flux normalization castroData : A CastroData object, with the log-likelihood v. normalization for each energy bin ylims ...
java
@XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "carLicense") public JAXBElement<String> createCarLicense(String value) { return new JAXBElement<String>(_CarLicense_QNAME, String.class, null, value); }
java
public AtomixConfig setPartitionGroups(Map<String, PartitionGroupConfig<?>> partitionGroups) { partitionGroups.forEach((name, group) -> group.setName(name)); this.partitionGroups = partitionGroups; return this; }
python
def btc_is_multisig_segwit(privkey_info): """ Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh) """ try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) == 1: ...
python
def _relative_position_to_absolute_position_unmasked(x): """Converts tensor from relative to aboslute indexing for local attention. Args: x: a Tensor of shape [batch (or batch*num_blocks), heads, length, 2 * length - 1] Returns: A Tensor of shape [batch (or batch*num_blocks), h...
java
protected RpcInvocation createRpcInvocationMessage( final String methodName, final Class<?>[] parameterTypes, final Object[] args) throws IOException { final RpcInvocation rpcInvocation; if (isLocal) { rpcInvocation = new LocalRpcInvocation( methodName, parameterTypes, args); } else { ...
python
def agent_show(self, agent_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/agents#get-agent-by-id" api_path = "/api/v2/agents/{agent_id}" api_path = api_path.format(agent_id=agent_id) return self.call(api_path, **kwargs)
python
def parse(readDataInstance): """ Returns a L{Directory}-like object. @type readDataInstance: L{ReadData} @param readDataInstance: L{ReadData} object to read from. @rtype: L{Directory} @return: L{Directory} object. """ d = Directory() ...
java
void visitProperty( @Nonnull TypedElement type, @Nonnull String name, @Nullable MethodElement readMethod, @Nullable MethodElement writeMethod, boolean isReadOnly, @Nullable AnnotationMetadata annotationMetadata, @Nullable Map<String, Cl...
python
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth,...
java
public static int cs_tdfs(int j, int k, int[] head, int head_offset, int[] next, int next_offset, int[] post, int post_offset, int[] stack, int stack_offset) { int i, p, top = 0; if (head == null || next == null || post == null || stack == null) return (-1); /* check inputs *...
java
private void addDCTriples(Datastream ds, URIReference objURI, Set<Triple> set) throws Exception { DCFields dc = new DCFields(ds.getContentStream()); Map<RDFName, List<DCField>> map = dc.getMap(); for (RDFName predicate : map.keySet()) {...
python
def get(self, id_vlan): """Get a VLAN by your primary key. Network IPv4/IPv6 related will also be fetched. :param id_vlan: ID for VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >...
java
static final public DateFormat getDateInstance(Calendar cal, int dateStyle) { return getDateInstance(cal, dateStyle, ULocale.getDefault(Category.FORMAT)); }
java
private void cleanupSession(){ eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.CLOSED)); watcherManager.cleanup(); session.id = ""; session.password = null; session.serverId = -1; onSessionClose(); }
python
def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single...
python
def _dump_spec(spec): """Dump bel specification dictionary using YAML Formats this with an extra indentation for lists to make it easier to use cold folding on the YAML version of the spec dictionary. """ with open("spec.yaml", "w") as f: yaml.dump(spec, f, Dumper=MyDumper, default_flow_sty...
java
protected <T> Optional<T> getTarget(Event event, Class<T> type) { return getValue(event, event::getTarget, type); }
java
private void checkPolicy(X509Certificate currCert) throws CertPathValidatorException { String msg = "certificate policies"; if (debug != null) { debug.println("PolicyChecker.checkPolicy() ---checking " + msg + "..."); debug.println("PolicyChecker.check...
python
def main(): """Main function for SPEAD sender module.""" # Check command line arguments. if len(sys.argv) != 2: raise RuntimeError('Usage: python3 async_send.py <json config>') # Set up logging. sip_logging.init_logger(show_thread=False) # Load SPEAD configuration from JSON file. #...
java
public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader) { if (loader == null) { loader = service.getClassLoader(); } return new ServiceLoader<S>(service, new ClassLoaderResourceLoader(loader)); }
java
private boolean startsWith(ArchivePath fullPath, ArchivePath startingPath) { final String context = fullPath.get(); final String startingContext = startingPath.get(); return context.startsWith(startingContext); }
java
public static String getStringForSign(ProductPayRequest request) { Map<String, Object> params = new HashMap<String, Object>(); // 必选参数 params.put(HwPayConstant.KEY_MERCHANTID, request.getMerchantId()); params.put(HwPayConstant.KEY_APPLICATIONID, request.getApplicationID()); ...
java
private void readIdToPendingRequests(CoronaSerializer coronaSerializer) throws IOException { coronaSerializer.readField("idToPendingRequests"); // Expecting the START_ARRAY token for idToPendingRequests coronaSerializer.readStartArrayToken("idToPendingRequests"); JsonToken current = coronaSerializer...
java
public final void replace(final List<Resource> r1, final List<Resource> r2) { this.resources.removeAll(r1); this.resources.addAll(r2); }