auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void allThreadMustHaveTheirOwnThreadLocalSimpleDateFormat() { int numberOfParties = 10; final CyclicBarrier barrier = new CyclicBarrier(numberOfParties + 1); final List<SimpleDateFormat> list = Collections.synchronizedList(new ArrayList<SimpleDateFormat>()); class Worker implements Runnable { @Override public void run() { try { list.add(SafeCalendarJsonAdapter.DATE_FORMAT_MAP.get(SafeCalendarJsonAdapter.REG_EX_YEAR).get()); barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } } } for (int index = 0; index < numberOfParties; ++index) { new Thread(new Worker()).start(); } try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } for (int i = 0; i < numberOfParties; ++i) { for (int j = 0; j < numberOfParties; ++j) { if (i == j) { continue; } SimpleDateFormat simpleDateFormatToCheck = list.get(i); SimpleDateFormat simpleDateFormatToVerify = list.get(j); if (simpleDateFormatToCheck == simpleDateFormatToVerify) { fail("Each thread should have it own instanse of thread SimpleDateFormat local variable"); return; } } } }

Target:
public void allThreadMustHaveTheirOwnThreadLocalSimpleDateFormat() { int numberOfParties = 10; final CyclicBarrier barrier = new CyclicBarrier(numberOfParties + 1); final List<SimpleDateFormat> list = Collections.synchronizedList(new ArrayList<SimpleDateFormat>()); class Worker implements Runnable { @Override public void run() { try { list.add(SafeCalendarJsonAdapter.DATE_FORMAT_MAP.get(SafeCalendarJsonAdapter.REG_EX_YEAR).get()); barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } } } for (int index = 0; index < numberOfParties; ++index) { new Thread(new Worker()).start(); } try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } for (int i = 0; i < numberOfParties; ++i) { for (int j = i; j < numberOfParties; ++j) { if (i == j) { continue; } SimpleDateFormat simpleDateFormatToCheck = list.get(i); SimpleDateFormat simpleDateFormatToVerify = list.get(j); if (simpleDateFormatToCheck == simpleDateFormatToVerify) { fail("Each thread should have it own instanse of thread SimpleDateFormat local variable"); return; } } } }
Source:
private JsonObject getNamedPlaceholderValues(ParameterAccessor accessor) { JsonObject namedValues = JsonObject.create(); HashSet<String> pNames=new HashSet<>(parameterNames); for (Parameter parameter : this.queryMethod.getParameters().getBindableParameters()) { String placeholder = parameter.getPlaceholder(); Object value = couchbaseConverter.convertForWriteIfNeeded(accessor.getBindableValue(parameter.getIndex())); if (placeholder != null && placeholder.charAt(0) == ':') { placeholder = placeholder.replaceFirst(":", ""); try { namedValues.put(placeholder,value); }catch(InvalidArgumentException iae){ Object o = accessor.getBindableValue(parameter.getIndex()); if(o instanceof Object[]) { Object[] array=(Object[])o; JsonArray ja=JsonValue.ja(); for(Object e:array) { ja.add(String.valueOf(couchbaseConverter.convertForWriteIfNeeded(e))); } namedValues.put(placeholder,ja); } else { throw iae; } } if(pNames.contains(placeholder)) pNames.remove(placeholder); else throw new RuntimeException("parameter named "+placeholder+ " does not match any named parameter "+parameterNames+ " in "+statement); } else { if(parameter.getName().isPresent()) namedValues.put(parameter.getName().get(), value); else throw new RuntimeException("cannot determine argument for named parameter. "+ "Argument "+ parameter.getIndex() +" to "+ queryMethod.getClass().getName()+"."+queryMethod.getName()+ "() needs @Param(\"name\") that matches a named parameter in "+ statement); } } if(!pNames.isEmpty()) throw new RuntimeException("no parameter found for "+pNames); return namedValues; }

Target:
private JsonObject getNamedPlaceholderValues(ParameterAccessor accessor) { JsonObject namedValues = JsonObject.create(); HashSet<String> pNames = new HashSet<>(parameterNames); for (Parameter parameter : this.queryMethod.getParameters().getBindableParameters()) { String placeholder = parameter.getPlaceholder(); Object rawValue = accessor.getBindableValue(parameter.getIndex()); Object value = couchbaseConverter.convertForWriteIfNeeded(rawValue); if (placeholder != null && placeholder.charAt(0) == ':') { placeholder = placeholder.replaceFirst(":", ""); putNamedValue(accessor, parameter, namedValues, placeholder, value); if (pNames.contains(placeholder)) { pNames.remove(placeholder); } else { throw new RuntimeException( "parameter named " + placeholder + " does not match any named parameter " + parameterNames + " in " + statement); } } else { if (parameter.getName().isPresent()) { putNamedValue(accessor, parameter, namedValues, parameter.getName().get(), value); } else { throw new RuntimeException( "cannot determine argument for named parameter. " + "Argument " + parameter.getIndex() + " to " + queryMethod.getClass().getName() + "." + queryMethod.getName() + "() needs @Param(\"name\") that matches a named parameter in " + statement); } } } if (!pNames.isEmpty()) { throw new RuntimeException("no parameter found for " + pNames); } return namedValues; }
Source:
public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); this.repositoryObservable.register(adapter); this.listeners.add(adapter); }

Target:
public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); if (this.repositoryObservable.register(adapter)) { this.listeners.add(adapter); } }
Source:
public void testInvokeByPassingNullValue() throws RemotingException { mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")); given(mockInvoker.invoke(any(Invocation.class))).willReturn(new RpcResult("ok")); mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20883")); DubboProtocol.getDubboProtocol().export(mockInvoker); try { invoke.telnet(mockChannel, "DemoService.add(null, 2)"); fail("It should cause a NullPointerException here."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.1 parameter is primitive(int), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.add(1, null)"); fail("It should cause a NullPointerException here."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.2 parameter is primitive(long), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.sayHello(null)"); } catch (NullPointerException ex) { fail("It shouldn't cause a NullPointerException here."); } }

Target:
public void testInvokeByPassingNullValue() throws RemotingException { mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")); given(mockInvoker.invoke(any(Invocation.class))).willReturn(new RpcResult("ok")); mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20883")); DubboProtocol.getDubboProtocol().export(mockInvoker); try { invoke.telnet(mockChannel, "DemoService.add(null, 2)"); fail("It should cause a NullPointerException by the above code."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.1 parameter is primitive(int), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.add(1, null)"); fail("It should cause a NullPointerException by the above code."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.2 parameter is primitive(long), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.sayHello(null)"); } catch (NullPointerException ex) { fail("It shouldn't cause a NullPointerException by the above code."); } }
Source:
public static void setUp() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer bb = ByteBuffer.allocate(25); bb.order(ByteOrder.BIG_ENDIAN); bb.put((byte) 0x46); bb.put((byte) 0x9A); bb.put((byte) 0x00); bb.put((byte) 0xFF); bb.put((byte) 0x0F); bb.put((byte) 0xF0); bb.put((byte) 0x1E); bb.put((byte) 0xE1); bb.put((byte) 0xA0); bb.put((byte) 0xFE); bb.put((byte) 0x33); bb.put((byte) 0x44); bb.put((byte) 192); bb.put((byte) 168); bb.put((byte) 1); bb.put((byte) 0); bb.put((byte) 193); bb.put((byte) 169); bb.put((byte) 2); bb.put((byte) 1); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA6); bb.flip(); PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); PcapFile dummy = trace.getTrace(); IPv4Packet packet = new IPv4Packet(dummy, null, bb); ITmfEventField[] fieldArray = generatePacketFields(packet); fRegularField = new PcapEventField("Regular Field", EMPTY_STRING, fieldArray, packet); fRootField = new PcapRootEventField(fieldArray, packet); }

Target:
public static void setUp() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer bb = ByteBuffer.allocate(25); bb.order(ByteOrder.BIG_ENDIAN); bb.put((byte) 0x46); bb.put((byte) 0x9A); bb.put((byte) 0x00); bb.put((byte) 0xFF); bb.put((byte) 0x0F); bb.put((byte) 0xF0); bb.put((byte) 0x1E); bb.put((byte) 0xE1); bb.put((byte) 0xA0); bb.put((byte) 0xFE); bb.put((byte) 0x33); bb.put((byte) 0x44); bb.put((byte) 192); bb.put((byte) 168); bb.put((byte) 1); bb.put((byte) 0); bb.put((byte) 193); bb.put((byte) 169); bb.put((byte) 2); bb.put((byte) 1); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA6); bb.flip(); PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { IPv4Packet packet = new IPv4Packet(dummy, null, bb); ITmfEventField[] fieldArray = generatePacketFields(packet); fRegularField = new PcapEventField("Regular Field", EMPTY_STRING, fieldArray, packet); fRootField = new PcapRootEventField(fieldArray, packet); } }
Source:
public int compareTo(DiskImageDynamic o) { return BusinessEntityComparator.newGuidInstance().compare(this, o); }

Target:
public int compareTo(DiskImageDynamic o) { return BusinessEntityComparator.<DiskImageDynamic, Guid>newInstance().compare(this, o); }
Source:
public boolean filterOut(SAMRecord record) { if (includeReads) { if (values.contains(record.getAttribute(tag))) { return false; } } else { if (!values.contains(record.getAttribute(tag))) { return false; } } return true; }

Target:
public boolean filterOut(SAMRecord record) { return values.contains(record.getAttribute(tag)) != includeReads; }
Source:
public void convertRelationshipToRelationshipField(final Relationship oldRelationship) throws DotDataException, DotSecurityException{ final ContentType parentContentType = new StructureTransformer(oldRelationship.getParentStructure()).from(); final ContentType childContentType = new StructureTransformer(oldRelationship.getChildStructure()).from(); final com.dotcms.contenttype.model.field.Field parentRelationshipField = createRelationshipField(oldRelationship.getChildRelationName(),parentContentType.id(), oldRelationship.getCardinality(),oldRelationship.isChildRequired(),childContentType.variable()); createRelationshipField(oldRelationship.getParentRelationName(), childContentType.id(), oldRelationship.getCardinality(), oldRelationship.isParentRequired(), parentContentType.variable()+"."+parentRelationshipField.variable()); final Relationship newRelationship = byTypeValue(parentContentType.variable()+"."+parentRelationshipField.variable()); final DotConnect dc = new DotConnect (); dc.setSQL("update tree set relation_type = '" + newRelationship.getRelationTypeValue() + "' where relation_type = '" + oldRelationship.getRelationTypeValue() + "'"); dc.loadResult(); APILocator.getRelationshipAPI().delete(oldRelationship); APILocator.getContentletAPI().refresh(oldRelationship.getParentStructure()); APILocator.getContentletAPI().refresh(oldRelationship.getChildStructure()); }

Target:
public void convertRelationshipToRelationshipField(final Relationship oldRelationship) throws DotDataException, DotSecurityException{ final ContentType parentContentType = new StructureTransformer(oldRelationship.getParentStructure()).from(); final ContentType childContentType = new StructureTransformer(oldRelationship.getChildStructure()).from(); final com.dotcms.contenttype.model.field.Field parentRelationshipField = createRelationshipField(oldRelationship.getChildRelationName(),parentContentType.id(), oldRelationship.getCardinality(),oldRelationship.isChildRequired(),childContentType.variable()); createRelationshipField(oldRelationship.getParentRelationName(), childContentType.id(), oldRelationship.getCardinality(), oldRelationship.isParentRequired(), parentContentType.variable()+"."+parentRelationshipField.variable()); final Relationship newRelationship = byTypeValue(parentContentType.variable()+"."+parentRelationshipField.variable()); final DotConnect dc = new DotConnect (); dc.setSQL("update tree set relation_type = ? where relation_type = ?"); dc.addParam(newRelationship.getRelationTypeValue()); dc.addParam(oldRelationship.getRelationTypeValue()); dc.loadResult(); APILocator.getRelationshipAPI().delete(oldRelationship); APILocator.getContentletAPI().refresh(oldRelationship.getParentStructure()); APILocator.getContentletAPI().refresh(oldRelationship.getChildStructure()); }
Source:
void run() { List<String> eventHubPartitionIds = new ArrayList<>(); this.eventHubAsyncClient.getPartitionIds() .map(eventHubPartitionIds::add).blockLast(Duration.ofSeconds(1)); logger.info("Found partitions", eventHubPartitionIds.size()); List<PartitionOwnership> ownership = new ArrayList<>(); this.partitionManager .listOwnership(this.eventHubName, this.consumerGroupName) .map(ownership::add) .blockLast(Duration.ofSeconds(1)); logger.info("Got ownership info from partition manager"); List<PartitionOwnership> myOwnership = new ArrayList<>(); this.partitionManager .claimOwnership(ownership) .doOnNext(myOwnership::add) .blockLast(Duration.ofSeconds(1)); logger.info("Claimed ownership"); eventHubPartitionIds.forEach(this::receiveEvents); }

Target:
void run() { final Flux<PartitionOwnership> ownershipFlux = partitionManager.listOwnership(eventHubName, consumerGroupName) .cache(); eventHubAsyncClient.getPartitionIds() .flatMap(id -> getCandidatePartitions(ownershipFlux, id)) .flatMap(this::claimOwnership) .subscribeOn(Schedulers.newElastic("PartitionPumps")) .subscribe(this::receiveEvents); }
Source:
public WptPt toWpt() { WptPt pt = super.toWpt(); pt.getExtensionsToWrite().put(PERSONAL, "true"); pt.name = type.toString(); pt.desc = getDescription(); return pt; }

Target:
public WptPt toWpt() { WptPt pt = super.toWpt(); pt.getExtensionsToWrite().put(PERSONAL, "true"); pt.name = type.typeName; pt.desc = getDescription(); return pt; }
Source:
public Set<? extends NodeMetadata> suspendNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> suspending nodes matching(%s)", filter); Set<NodeMetadata> set = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { suspendNode(from.getId()); return from; } public String toString() { return "suspendNode(" + from.getId() + ")"; } }); } }, userExecutor, null, logger, "suspendNodesMatching(" + filter + ")")); logger.debug("<< suspended"); cleanUpIncidentalResourcesOfDeadNodes(set); return set; }

Target:
public Set<? extends NodeMetadata> suspendNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> suspending nodes matching(%s)", filter); Set<NodeMetadata> suspendNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { suspendNode(from.getId()); return from; } public String toString() { return "suspendNode(" + from.getId() + ")"; } }); } }, userExecutor, null, logger, "suspendNodesMatching(" + filter + ")")); logger.debug("<< suspended(%d)", suspendNodes.size()); return suspendNodes; }
Source:
public void handlesConnectTimeouts_alwaysRetry() throws IOException, InterruptedException { String urlConnectTimeout = "http:/10.255.255.1"; server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); OkHttpClient client = OkHttpClients.withStableUris( ClientConfiguration.builder() .from(createTestConfig(urlConnectTimeout, url)) .readTimeout(Duration.ofMillis(20)) .maxNumRetries(1) .backoffSlotSize(Duration.ofMillis(10)) .connectTimeout(Duration.ofMillis(50)) .retryOnTimeout(ClientConfiguration.RetryOnTimeout.DISABLED) .build(), AGENT, hostEventsSink, OkHttpClientsTest.class); Call call = client.newCall(new Request.Builder().url(url + "/foo?bar").build()); assertThat(call.execute().body().string()).isEqualTo("foo"); assertThat(server.takeRequest().getPath()).isEqualTo("/foo?bar"); }

Target:
public void handlesConnectTimeouts_alwaysRetry() throws IOException, InterruptedException { String urlConnectTimeout = "<LINK_0>"; server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); OkHttpClient client = OkHttpClients.withStableUris( ClientConfiguration.builder() .from(createTestConfig(urlConnectTimeout, url)) .readTimeout(Duration.ofMillis(20)) .maxNumRetries(1) .backoffSlotSize(Duration.ofMillis(10)) .connectTimeout(Duration.ofMillis(50)) .retryOnTimeout(ClientConfiguration.RetryOnTimeout.DISABLED) .build(), AGENT, hostEventsSink, OkHttpClientsTest.class); Call call = client.newCall(new Request.Builder().url(url + "/foo?bar").build()); assertThat(call.execute().body().string()).isEqualTo("foo"); assertThat(server.takeRequest().getPath()).isEqualTo("/foo?bar"); }
Source:
private CharSequence formatTimeLabel(Calendar cal, int strRes) { String label = mRes.getString(strRes); GregorianCalendar tomorrowEOD = new GregorianCalendar(); tomorrowEOD.add(Calendar.DAY_OF_YEAR, 1); tomorrowEOD.set(Calendar.HOUR_OF_DAY, 23); tomorrowEOD.set(Calendar.MINUTE, 59); String time; if (cal.before(tomorrowEOD)) { time = mTimeFormatter.format(cal.getTime()); } else { time = mTimeAndDayFormatter.format(cal.getTime()); } return String.format(label, time); }

Target:
private CharSequence formatTimeLabel(Calendar cal, int strRes) { String label = mRes.getString(strRes); GregorianCalendar tomorrowEOD = new GregorianCalendar(); tomorrowEOD.add(Calendar.DAY_OF_YEAR, 2); tomorrowEOD.set(Calendar.HOUR_OF_DAY, 0); tomorrowEOD.set(Calendar.MINUTE, 0); tomorrowEOD.set(Calendar.SECOND, 0); String time; if (cal.before(tomorrowEOD)) { time = mTimeFormatter.format(cal.getTime()); } else { time = mTimeAndDayFormatter.format(cal.getTime()); } return String.format(label, time); }
Source:
public JpaPagingItemReader<WeekActivity> weekActivityReader() { try { String jpqlQuery = "SELECT w FROM WeekActivity w WHERE w.startDate <= :lastWeek AND w.aggregatesComputed = false"; JpaPagingItemReader<WeekActivity> reader = new JpaPagingItemReader<>(); reader.setQueryString(jpqlQuery); reader.setParameterValues(Collections.singletonMap("lastWeek", TimeUtil.getStartOfWeek(ZonedDateTime.now(DEFAULT_TIME_ZONE).toLocalDate()).minusWeeks(1))); reader.setEntityManagerFactory(entityManager.getEntityManagerFactory()); reader.setPageSize(WEEK_ACTIVITY_CHUNK_SIZE); reader.afterPropertiesSet(); reader.setSaveState(true); return reader; } catch (Exception e) { throw YonaException.unexpected(e); } }

Target:
public JpaPagingItemReader<WeekActivity> weekActivityReader() { try { String jpqlQuery = "SELECT w FROM WeekActivity w WHERE w.startDate <= :lastWeek AND w.aggregatesComputed = false"; JpaPagingItemReader<WeekActivity> reader = new JpaPagingItemReader<>(); reader.setQueryString(jpqlQuery); reader.setParameterValues(Collections.singletonMap("lastWeek", TimeUtil.getStartOfWeek(ZonedDateTime.now(DEFAULT_TIME_ZONE).minusWeeks(1).toLocalDate()))); reader.setEntityManagerFactory(entityManager.getEntityManagerFactory()); reader.setPageSize(WEEK_ACTIVITY_CHUNK_SIZE); reader.afterPropertiesSet(); reader.setSaveState(true); return reader; } catch (Exception e) { throw YonaException.unexpected(e); } }
Source:
public String getUsages() { return node.getUsages().stream().map(TriggerUsage::name).sorted().collect(Collectors.joining(",")); }

Target:
public List<TriggerUsage> getUsages() { return node.getUsages().stream() .map(TriggerUsage::of) .sorted() .collect(Collectors.toList()); }
Source:
public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { final Script cmd = new Script(_ovsTunnelPath, _timeout.getMillis(), s_logger); cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; }

Target:
public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef attackingPlayer = event.getInstigator(); if (attackingPlayer.getComponent(CharacterHeldItemComponent.class).selectedItem.hasComponent(RaycastOnActivateComponent.class)) { if (entity.hasComponent(PlayerCharacterComponent.class)) { blackFlagSlot = searchInventoryForFlag(entity, LASUtils.BLACK_FLAG_URI); if (blackFlagSlot != EntityRef.NULL) { Vector3f position = new Vector3f(entity.getComponent(LocationComponent.class).getLocalPosition()); Vector3f impulseVector = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); entity.send(new DropItemRequest(blackFlagSlot, entity, impulseVector, position)); return; } redFlagSlot = searchInventoryForFlag(entity, LASUtils.RED_FLAG_URI); if (redFlagSlot != EntityRef.NULL) { Vector3f position = new Vector3f(entity.getComponent(LocationComponent.class).getLocalPosition()); Vector3f impulseVector = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); entity.send(new DropItemRequest(redFlagSlot, entity, impulseVector, position)); return; } } } }

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { dropFlagOnPlayerAttack(event, entity); }
Source:
public void test() { channels.input().send(new GenericMessage<Object>("hello")); channels.input().send(new GenericMessage<Object>("hello world")); channels.input().send(new GenericMessage<Object>("hi!")); assertThat(collector.forChannel(channels.output()), receivesPayloadThat(is("hello world"))); }

Target:
public void test() throws InterruptedException { channels.input().send(new GenericMessage<Object>("hello")); channels.input().send(new GenericMessage<Object>("hello world")); channels.input().send(new GenericMessage<Object>("hi!")); assertThat(collector.forChannel(channels.output()), receivesPayloadThat(is("hello world"))); assertThat(collector.forChannel(channels.output()).poll(10, MILLISECONDS), is(nullValue(Message.class))); }
Source:
public Either<java.util.Set<ParseFailedException>, Term> apply(TermCons tc) { if (tc.production().klabel().isDefined() && tc.production().klabel().get().name().equals("#KRewrite")) { String msg = "Due to typing errors, => is not greedy. Use parentheses to set proper scope."; KException kex = new KException(KException.ExceptionType.ERROR, KException.KExceptionGroup.CRITICAL, msg, null, null); return Left.apply(Sets.newHashSet(new PriorityException(kex))); } return Right.apply(tc); }

Target:
public Either<java.util.Set<ParseFailedException>, Term> apply(TermCons tc) { if (tc.production().klabel().isDefined() && tc.production().klabel().get().name().equals("#KRewrite")) { String msg = "Rewrite is not allowed to be an immediate child of " + parent.production().klabel().get() + " Use parentheses: (x)=>(y) to set the proper scope of the operations."; KException kex = new KException(KException.ExceptionType.ERROR, KException.KExceptionGroup.CRITICAL, msg, null, tc.location().get()); return Left.apply(Sets.newHashSet(new PriorityException(kex))); } return Right.apply(tc); }
Source:
private Iterable<ThriftStructFieldInfo> getFieldInfosForUnion(Class klass) { ArrayList<ThriftStructFieldInfo> fields = new ArrayList<ThriftStructFieldInfo>(); for(Field f: klass.getDeclaredFields()){ if (f.getType().equals(Manifest.class)) { Class unionClass = (Class)((ParameterizedType)f.getGenericType()).getActualTypeArguments()[0]; Class companionUnionClass = getCompanionClass(unionClass); try { Object companionUnionObj = companionUnionClass.getField("MODULE$").get(null); ThriftStructFieldInfo info = (ThriftStructFieldInfo)companionUnionClass.getMethod("fieldInfo").invoke(companionUnionObj); fields.add(info); } catch (Exception e) { throw new RuntimeException("can not find fiedInfo for " + unionClass, e); } } } return fields; }

Target:
private Iterable<ThriftStructFieldInfo> getFieldInfosForUnion(Class klass) { ArrayList<ThriftStructFieldInfo> fields = new ArrayList<ThriftStructFieldInfo>(); for(Field f: klass.getDeclaredFields()){ if (f.getType().equals(Manifest.class)) { Class unionClass = (Class)((ParameterizedType)f.getGenericType()).getActualTypeArguments()[0]; Class companionUnionClass = getCompanionClass(unionClass); try { Object companionUnionObj = companionUnionClass.getField("MODULE$").get(null); ThriftStructFieldInfo info = (ThriftStructFieldInfo)companionUnionClass.getMethod("fieldInfo").invoke(companionUnionObj); fields.add(info); } catch (ReflectiveOperationException e) { throw new ScroogeSchemaConversionException("can not find fiedInfo for " + unionClass, e); } } } return fields; }
Source:
public void testInvalidFiles() { MappingFile mf = MappingFile.create("test", false); assertNull(mf); Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "emptyFile"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); mf = MappingFile.create(filePath, false); assertNull(mf); }

Target:
public void testInvalidFiles() { IMappingFile mf = IMappingFile.create("test", false); assertNull(mf); mf = getMappingFile("emptyFile"); assertNull(mf); }
Source:
private QNode getOrAddNode() { TaskNode head; QNode headNext; PoolThreadNode newNode = null; for (;;) { head = EnhancedQueueExecutor.this.head; headNext = head.getNext(); if (headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { if (! NO_QUEUE_LIMIT) decreaseQueueSize(); return taskNode; } } else if (headNext instanceof PoolThreadNode || headNext == null) { if (newNode == null) { newNode = new PoolThreadNode(null, Thread.currentThread()); } newNode.setNext(headNext); if (head.compareAndSetNext(headNext, newNode)) { return newNode; } } else { assert headNext instanceof TerminateWaiterNode; return headNext; } if (UPDATE_STATISTICS) spinMisses.increment(); } }

Target:
private QNode getOrAddNode() { TaskNode head; QNode headNext; PoolThreadNode newNode = null; for (;;) { head = EnhancedQueueExecutor.this.head; headNext = head.getNext(); if (headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { if (! NO_QUEUE_LIMIT) decreaseQueueSize(); return taskNode; } } else if (headNext instanceof PoolThreadNode || headNext == null) { if (newNode == null) { newNode = new PoolThreadNode(Thread.currentThread()); } newNode.setNext(headNext); if (head.compareAndSetNext(headNext, newNode)) { return newNode; } } else { assert headNext instanceof TerminateWaiterNode; return headNext; } if (UPDATE_STATISTICS) spinMisses.increment(); } }
Source:
private static List<Object> allParameters( TestClass testClass, FrameworkMethod parametersMethod) throws Throwable { Object parameters; try { parameters = parametersMethod.invokeExplosively(null); } catch (AssumptionViolatedException e) { return Collections.<Object>singletonList( new AssumptionViolationRunner(testClass, parametersMethod.getName(), e)); } if (parameters instanceof List) { return (List<Object>) parameters; } else if (parameters instanceof Collection) { return new ArrayList<Object>((Collection<Object>) parameters); } else if (parameters instanceof Iterable) { List<Object> result = new ArrayList<Object>(); for (Object entry : ((Iterable<Object>) parameters)) { result.add(entry); } return result; } else if (parameters instanceof Object[]) { return Arrays.asList((Object[]) parameters); } else { throw parametersMethodReturnedWrongType(testClass, parametersMethod); } }

Target:
private static List<Object> allParameters( TestClass testClass, FrameworkMethod parametersMethod) throws Throwable { Object parameters = parametersMethod.invokeExplosively(null); if (parameters instanceof List) { return (List<Object>) parameters; } else if (parameters instanceof Collection) { return new ArrayList<Object>((Collection<Object>) parameters); } else if (parameters instanceof Iterable) { List<Object> result = new ArrayList<Object>(); for (Object entry : ((Iterable<Object>) parameters)) { result.add(entry); } return result; } else if (parameters instanceof Object[]) { return Arrays.asList((Object[]) parameters); } else { throw parametersMethodReturnedWrongType(testClass, parametersMethod); } }
Source:
private List<WorkspaceImpl> createEntities(int number) throws TckRepositoryException { List<WorkspaceImpl> wsList = new ArrayList<>(); for (int i = 0; i < number; i++) { wsList.add(new WorkspaceImpl("id" + i, null, null)); } return wsList; }

Target:
private List<WorkspaceImpl> createEntities(int number) { List<WorkspaceImpl> wsList = new ArrayList<>(); for (int i = 0; i < number; i++) { wsList.add(new WorkspaceImpl("id" + i, null, null)); } return wsList; }
Source:
private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { Target target = null; for (Target t : availableTargets) { if (t.matches(targetLabel)) { target = t; break; } } if (target == null) { throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); } return target; }

Target:
private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { for (Target target : availableTargets) { if (target.matches(targetLabel)) { return target; } } throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); }
Source:
public Object execute() throws Exception { return chan.eventLoop().submit(new Runnable() { @Override public void run() }).get(); }

Target:
public Object execute() throws Exception { return chan.eventLoop().submit(runnable).get(); }
Source:
protected void tearDownContext() { view.getComputeService().destroyNodesMatching(inGroup(imageGroup)); Optional<? extends Image> image = getImage(); if (image.isPresent() && image.get().getStatus() != Image.Status.DELETED) { Optional<ImageExtension> imageExtension = view.getComputeService().getImageExtension(); if (imageExtension.isPresent()) { imageExtension.get().deleteImage(image.get().getId()); } } super.tearDownContext(); }

Target:
protected void tearDownContext() { try { view.getComputeService().destroyNodesMatching(inGroup(imageGroup)); Optional<? extends Image> image = getImage(); if (image.isPresent() && image.get().getStatus() != Image.Status.DELETED) { Optional<ImageExtension> imageExtension = view.getComputeService().getImageExtension(); if (imageExtension.isPresent()) { imageExtension.get().deleteImage(image.get().getId()); } } } catch (Exception e) { } super.tearDownContext(); }
Source:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { AbstractTypedTree variable = (AbstractTypedTree) tree.variable(); if (variable.is(Kind.IDENTIFIER)) { Symbol variableSymbol = getSemanticModel().getReference((IdentifierTree) variable); if (field.equals(variableSymbol)) { addIssue(synchronizedStatement, MessageFormat.format("Don''t synchronize on \"{0}\" or remove its reassignment on line {1}.", field.getName(), String.valueOf(variable.getLine()))); } } }

Target:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { checkSymbolAssignment((AbstractTypedTree) tree.variable()); }
Source:
private Set<IEntityGroup> getParentGroups(String key, Set<IEntityGroup> groups) { log.debug("Getting parents of group: {}", key); IEntityGroup group = groupsTree.getGroups().get(key); if (group == null) { log.warn("SmartLdap group not found for key: {}", key); return groups; } List<String> parentKeys = groupsTree.getParents().get(key); parentKeys = parentKeys != null ? parentKeys : Collections.emptyList(); log.debug("Parent keys for {}: {}", key, String.join(",", parentKeys)); for (String parentKey : parentKeys) { IEntityGroup parent = groupsTree.getGroups().get(parentKey); if (parent == null) { log.warn("Group tree inconsistent -- missing parent: {}", parentKey); } else if (groups.contains(parent)) { log.warn("Parent found multiple times, could be recursion group tree!"); } else { groups.add(parent); getParentGroups(parentKey, groups); } } return groups; }

Target:
private Set<IEntityGroup> getParentGroups(String key, Set<IEntityGroup> groups) { log.debug("Getting parents of group: {}", key); IEntityGroup group = groupsTree.getGroups().get(key); if (group == null) { log.warn("SmartLdap group not found for key: {}", key); return groups; } List<String> parentKeys = groupsTree.getParents().get(key); parentKeys = parentKeys != null ? parentKeys : Collections.emptyList(); log.debug("Parent keys for {}: {}", key, String.join(",", parentKeys)); for (String parentKey : parentKeys) { IEntityGroup parent = groupsTree.getGroups().get(parentKey); if (parent == null) { log.warn("Group tree inconsistent -- missing parent: {}", parentKey); } else if (groups.contains(parent)) { log.warn( "Parent found multiple times, could be recursion group tree! key: {}, parent key: {}", key, parentKey); } else { groups.add(parent); getParentGroups(parentKey, groups); } } return groups; }
Source:
public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } int nextNullRow = nullIterator.next(); if (offset.isContiguous()) { final int startOffset = offset.getStartOffset(); nullIterator.advanceIfNeeded(startOffset); for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; if (row == nextNullRow) { retVal[i] = true; if (nullIterator.hasNext()) { nextNullRow = nullIterator.next(); } else { break; } } else { retVal[i] = false; } } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; if (row == nextNullRow) { retVal[i] = true; if (nullIterator.hasNext()) { nextNullRow = nullIterator.next(); } else { break; } } else { retVal[i] = false; } } } return retVal; }

Target:
public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } if (offset.isContiguous()) { final int startOffset = offset.getStartOffset(); nullIterator.advanceIfNeeded(startOffset); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { break; } retVal[i] = row == nullIterator.peekNext(); } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { break; } retVal[i] = row == nullIterator.peekNext(); } } return retVal; }
Source:
public static void startMeasure(final String heading, final String stepName) { LogCollector collector; synchronized (COLLECTOR_POOL) { collector = COLLECTOR_POOL.poll(); } if (null == collector) { collector = new LogCollector(); } LogCollector[] collectors = THREAD_COLLECTORS.get(); final int idxToSet; if (null == collectors) { collectors = new LogCollector[2]; THREAD_COLLECTORS.set(collectors); idxToSet = 0; } else { int freeSlot = -1; for (int idx = 0; idx < collectors.length; ++idx) { if (collectors[idx] == null) { freeSlot = idx; break; } } if (freeSlot < 0) { idxToSet = collectors.length; collectors = Arrays.copyOf(collectors, collectors.length + 2); THREAD_COLLECTORS.set(collectors); } else { idxToSet = freeSlot; } } if (idxToSet > 0) { collectors[idxToSet].addRecord(heading); } collectors[idxToSet] = collector; collector.addRecord(heading); collector.addRecord(stepName); }

Target:
public static void startMeasure(final String heading, final String stepName) { final LogCollector collector = new LogCollector(); List<LogCollector> collectors = THREAD_COLLECTORS.get(); if (null == collectors) { collectors = new ArrayList<>(2); THREAD_COLLECTORS.set(collectors); } if (!collectors.isEmpty()) { collectors.get(collectors.size() - 1).addRecord(heading); } collectors.add(collector); collector.addRecord(heading); collector.addRecord(stepName); }
Source:
public void start() { eventService.subscribe(new EventSubscriber<WorkspaceCreatedEvent>() { @Override public void onEvent(WorkspaceCreatedEvent workspaceCreatedEvent) { try { sshManager.generatePair(EnvironmentContext.getCurrent().getSubject().getUserId(), "workspace", workspaceCreatedEvent.getWorkspace().getId()); } catch (ServerException | ConflictException e) { LOG.error(String.format("Unable to generate a default ssh pair for the workspace with ID %s", workspaceCreatedEvent.getWorkspace().getId()), e); } } }); eventService.subscribe(new EventSubscriber<WorkspaceRemovedEvent>() { @Override public void onEvent(WorkspaceRemovedEvent workspaceRemovedEvent) { try { sshManager.removePair(EnvironmentContext.getCurrent().getSubject().getUserId(), "workspace", workspaceRemovedEvent.getWorkspace().getId()); } catch (NotFoundException e) { LOG.error(String.format("Do not remove default keypair from workspace %s as it is not existing (workspace ID %s)", workspaceRemovedEvent.getWorkspace().getConfig().getName(), workspaceRemovedEvent.getWorkspace().getId())); } catch (ServerException e) { LOG.error(String.format( "Error when trying to remove default ssh pair for the workspace %s as it is not existing (workspace ID %s)", workspaceRemovedEvent.getWorkspace().getConfig().getName(), workspaceRemovedEvent.getWorkspace().getId())); } } }); }

Target:
public void start() { eventService.subscribe(new EventSubscriber<WorkspaceCreatedEvent>() { @Override public void onEvent(WorkspaceCreatedEvent workspaceCreatedEvent) { try { sshManager.generatePair(EnvironmentContext.getCurrent().getSubject().getUserId(), "workspace", workspaceCreatedEvent.getWorkspace().getId()); } catch (ServerException | ConflictException e) { LOG.error("Unable to generate a default ssh pair for the workspace with ID {}", workspaceCreatedEvent.getWorkspace().getId(), e); } } }); eventService.subscribe(new EventSubscriber<WorkspaceRemovedEvent>() { @Override public void onEvent(WorkspaceRemovedEvent workspaceRemovedEvent) { try { sshManager.removePair(EnvironmentContext.getCurrent().getSubject().getUserId(), "workspace", workspaceRemovedEvent.getWorkspace().getId()); } catch (NotFoundException e) { LOG.debug("Do not remove default keypair from workspace as it is not existing (workspace ID {})", workspaceRemovedEvent.getWorkspace().getConfig().getName(), workspaceRemovedEvent.getWorkspace().getId()); } catch (ServerException e) { LOG.error("Error when trying to remove default ssh pair for the workspace (workspace ID {})", workspaceRemovedEvent.getWorkspace().getConfig().getName(), workspaceRemovedEvent.getWorkspace().getId()); } } }); }
Source:
private boolean init(boolean firstAttempt) { close(); try { logger.info("Loading Record Manager from file : " + statusFile); recMan = RecordManagerFactory.createRecordManager(statusFile.getCanonicalPath()); persistedChannels = recMan.hashMap(STATUS_RECORD_NAME); logger.info("Content of persisted store : " + persistedChannels); for (Map.Entry<String, Channel> tempChannels : persistedChannels.entrySet()) ; recMan.commit(); if (!firstAttempt) { logger.info("Loading of job database successful after clean."); } } catch (Throwable e) { if (firstAttempt) { logger.error("Error occurred when loading channels database " + statusFile.getAbsolutePath() + ", now cleaning it and retrying.", e); close(); recMan = null; cleanDataBase(); init(false); } else { close(); throw new IllegalStateException("Error when loading database (even after cleaning it): " + statusFile.getAbsolutePath(), e); } } return true; }

Target:
private void init(boolean firstAttempt) { close(); try { logger.info("Loading Record Manager from file : " + statusFile); recordManager = RecordManagerFactory.createRecordManager(statusFile.getCanonicalPath()); persistedChannels = recordManager.hashMap(STATUS_RECORD_NAME); logger.info("Content of persisted store : " + persistedChannels); recordManager.commit(); if (!firstAttempt) { logger.info("Loading of job database successful after clean."); } } catch (Throwable e) { if (firstAttempt) { logger.error("Error occurred when loading channels database " + statusFile.getAbsolutePath() + ", now cleaning it and retrying.", e); cleanDataBase(); init(false); } else { close(); throw new IllegalStateException("Error when loading database (even after cleaning it): " + statusFile.getAbsolutePath(), e); } } isStarted = true; }
Source:
BridgeFile(VirtualFile file) { this.file = file; this.parent = file.parent(); }

Target:
BridgeFile(VirtualFile file) { this.file = file; }
Source:
private void electedTruncationLeader() throws Exception { loggingLog.info("This node was selected as the leader for snapshot truncation"); m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { scanTruncationSnapshots(); } catch (Exception e) { loggingLog.error("Error during scan and group of truncation snapshots"); } } }, 0, 1, TimeUnit.MINUTES); try { truncationRequestExistenceCheck(); userSnapshotRequestExistenceCheck(false); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error while accepting snapshot daemon leadership", true, e); } }

Target:
private void electedTruncationLeader() throws Exception { loggingLog.info("This node was selected as the leader for snapshot truncation"); m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { scanTruncationSnapshots(); } catch (Exception e) { loggingLog.error("Error during scan and group of truncation snapshots"); } } }, 0, 1, TimeUnit.HOURS); try { truncationRequestExistenceCheck(); userSnapshotRequestExistenceCheck(false); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error while accepting snapshot daemon leadership", true, e); } }
Source:
public MutableList<String> rsplit( String self, String sep, Object maxSplitO, Location loc, Environment env) throws EvalException { if (sep.isEmpty()) { throw new EvalException(loc, "Empty separator"); } int maxSplit = Integer.MAX_VALUE; if (maxSplitO != Runtime.NONE) { maxSplit = (Integer) maxSplitO; } ArrayDeque<String> res = new ArrayDeque<>(); int end = self.length() - 1; while (true) { int start = self.lastIndexOf(sep, end); if (start < 0 || maxSplit-- == 0) { res.addFirst(self.substring(0, Math.max(0, end + 1))); break; } res.addFirst(self.substring(start + sep.length(), end + 1)); end = start - 1; } return MutableList.copyOf(env, res); }

Target:
public MutableList<String> rsplit( String self, String sep, Object maxSplitO, Location loc, Environment env) throws EvalException { if (sep.isEmpty()) { throw new EvalException(loc, "Empty separator"); } int maxSplit = Integer.MAX_VALUE; if (maxSplitO != Runtime.NONE) { maxSplit = (Integer) maxSplitO; } ArrayList<String> res = new ArrayList<>(); int end = self.length(); while (true) { int start = self.lastIndexOf(sep, end - 1); if (start < 0 || maxSplit-- == 0) { res.add(self.substring(0, end)); break; } res.add(self.substring(start + sep.length(), end)); end = start; } Collections.reverse(res); return MutableList.wrapUnsafe(env, res); }