auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void writeToParcel(Parcel out, int flags) { out.writeString(user); out.writeString(interfaze); out.writeString(session); out.writeInt(mtu); out.writeTypedList(addresses); out.writeTypedList(routes); out.writeStringList(dnsServers); out.writeStringList(searchDomains); out.writeStringList(allowedApplications); out.writeStringList(disallowedApplications); out.writeParcelable(configureIntent, flags); out.writeLong(startTime); out.writeInt(legacy ? 1 : 0); out.writeInt(blocking ? 1 : 0); out.writeInt(allowBypass ? 1 : 0); out.writeInt(allowIPv4 ? 1 : 0); out.writeInt(allowIPv6 ? 1 : 0); out.writeTypedArray(underlyingNetworks, flags); out.writeString(proxy == null ? "" : proxy.getHost()); out.writeInt(proxy == null ? 0 :proxy.getPort()); }

Target:
public void writeToParcel(Parcel out, int flags) { out.writeString(user); out.writeString(interfaze); out.writeString(session); out.writeInt(mtu); out.writeTypedList(addresses); out.writeTypedList(routes); out.writeStringList(dnsServers); out.writeStringList(searchDomains); out.writeStringList(allowedApplications); out.writeStringList(disallowedApplications); out.writeParcelable(configureIntent, flags); out.writeLong(startTime); out.writeInt(legacy ? 1 : 0); out.writeInt(blocking ? 1 : 0); out.writeInt(allowBypass ? 1 : 0); out.writeInt(allowIPv4 ? 1 : 0); out.writeInt(allowIPv6 ? 1 : 0); out.writeTypedArray(underlyingNetworks, flags); out.writeParcelable(proxy, flags); }
Source:
public void execute(List<VertexRef> targets, final OperationContext operationContext) { if (targets == null || targets.isEmpty()) { return; } final GraphContainer graphContainer = operationContext.getGraphContainer(); final Set<VertexHopCriteria> criteriaForGraphContainer = Criteria.getCriteriaForGraphContainer(graphContainer, VertexHopCriteria.class); for (VertexHopCriteria eachCriteria : criteriaForGraphContainer) { boolean shouldRemove = true; for (VertexRef vertex : eachCriteria.getVertices()) { if (targets.contains(vertex)) { shouldRemove = false; break; } } if (shouldRemove) { graphContainer.removeCriteria(eachCriteria); } } graphContainer.redoLayout(); }

Target:
public void execute(List<VertexRef> targets, final OperationContext operationContext) { final GraphContainer graphContainer = operationContext.getGraphContainer(); final Set<VertexHopCriteria> criteriaForGraphContainer = Criteria.getCriteriaForGraphContainer(graphContainer, VertexHopCriteria.class); boolean didRemoveCriteria = false; for (VertexHopCriteria eachCriteria : criteriaForGraphContainer) { boolean shouldRemove = true; for (VertexRef vertex : eachCriteria.getVertices()) { if (targets.contains(vertex)) { shouldRemove = false; break; } } if (shouldRemove) { graphContainer.removeCriteria(eachCriteria); didRemoveCriteria = true; } } if (didRemoveCriteria) { graphContainer.redoLayout(); } }
Source:
private void createAlertNotification(){ Map<String, Object> ambariAlertNotifications = getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS); createAlertNotification(mapAlertNotificationsConfigWithDefaults(ambariAlertsConfigFromProperties, ambariAlertNotifications)); }

Target:
protected void createAlertNotification(){ Map<String, Object> ambariAlertNotifications = MutableMap.of(); for (Map.Entry config: getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS).entrySet()) { Object value = (config.getValue() instanceof Map && !((String) config.getKey()).contains("properties")) ? ((Map) config.getValue()).keySet().toArray()[0] : config.getValue(); ambariAlertNotifications.put((String) config.getKey(), value); } Map<String, Object> mergedPropertiesConfig = MutableMap.of(); mergedPropertiesConfig.putAll((Map<String, Object>) getConfig(AmbariCluster.AMBARI_ALERT_NOTIFICATIONS).get("default_properties")); mergedPropertiesConfig.putAll((Map<String, Object>) ambariAlertNotifications.get("properties")); ambariAlertNotifications.put("properties", mergedPropertiesConfig); ambariAlertNotifications.remove("default_properties"); createAlertNotification(ambariAlertNotifications); }
Source:
private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { context.setDriverInstanceCount(1); checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); OrderingScheme orderingScheme = node.getOrderingScheme().get(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); Map<Symbol, Integer> sourceLayout = makeLayoutFromOutputSymbols(node.getOutputSymbols()); List<Symbol> orderBySymbols = orderingScheme.getOrderBy(); List<Integer> sortChannels = getChannelsForSymbols(orderBySymbols, sourceLayout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), node.getId(), exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), new SimplePageWithPositionComparator.Factory(), types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }

Target:
private PhysicalOperation createMergeSource(RemoteSourceNode node, LocalExecutionPlanContext context) { checkArgument(node.getOrderingScheme().isPresent(), "orderingScheme is absent"); context.setDriverInstanceCount(1); OrderingScheme orderingScheme = node.getOrderingScheme().get(); ImmutableMap<Symbol, Integer> layout = makeLayout(node); List<Integer> sortChannels = getChannelsForSymbols(orderingScheme.getOrderBy(), layout); List<SortOrder> sortOrder = orderingScheme.getOrderingList(); List<Type> types = getSourceOperatorTypes(node, context.getTypes()); ImmutableList<Integer> outputChannels = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); OperatorFactory operatorFactory = new MergeOperatorFactory( context.getNextOperatorId(), node.getId(), exchangeClientSupplier, new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session)), orderingCompiler, types, outputChannels, sortChannels, sortOrder); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }
Source:
private boolean isValid(String validity) { int expiresOnIndex = validity.indexOf(X509CertificateParser.EXPIRES_ON_PREFIX); if(expiresOnIndex >= 0) { SimpleDateFormat dateFormat = new SimpleDateFormat(X509CertificateParser.DATE_FORMAT, Locale.ENGLISH); String expiresOn = validity.substring(expiresOnIndex + X509CertificateParser.EXPIRES_ON_PREFIX.length()).trim(); try { Date date = dateFormat.parse(expiresOn); return date.getTime() > System.currentTimeMillis(); } catch (ParseException e) { dateFormat = new SimpleDateFormat(X509CertificateParser.DATE_FORMAT); try { Date date = dateFormat.parse(expiresOn); return date.getTime() > System.currentTimeMillis(); } catch(ParseException e2) { OpenShiftUIActivator.getDefault().getLogger().logError("SSLCertificatesPreference.isValid(String): Could not parse '" + expiresOn + "' in format " + X509CertificateParser.DATE_FORMAT); } } } return true; }

Target:
private boolean isValid(String validity) { return X509CertificateParser.isValid(validity); }
Source:
protected static Collection<Territory> findNearbyEnemyCapitalsAndFactories( final Territory startTerritory, final Set<Territory> enemyCapitalsAndFactories) { final var found = new HashSet<Territory>(); final BreadthFirstSearch bfs = new BreadthFirstSearch(startTerritory) { @Override public void visit(final Territory territory) { if (enemyCapitalsAndFactories.contains(territory)) { found.add(territory); } } @Override public boolean shouldContinueSearch(final int distanceSearched) { if (distanceSearched >= MIN_FACTORY_CHECK_DISTANCE && !found.isEmpty()) { return false; } return true; } }; bfs.search(); return found; }

Target:
protected static Collection<Territory> findNearbyEnemyCapitalsAndFactories( final Territory startTerritory, final Set<Territory> enemyCapitalsAndFactories) { final var found = new HashSet<Territory>(); new BreadthFirstSearch(startTerritory) .traverse( new BreadthFirstSearch.Visitor() { @Override public void visit(final Territory territory) { if (enemyCapitalsAndFactories.contains(territory)) { found.add(territory); } } @Override public boolean shouldContinueSearch(final int distanceSearched) { return distanceSearched < MIN_FACTORY_CHECK_DISTANCE || found.isEmpty(); } }); return found; }
Source:
public void onUserLoginFailure(Exception ex, String accessToken, String backend) { tryToSetUIInteraction(true); logger.error(ex); if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.FORBIDDEN) { RegisterActivity.this.showAlertDialog(getString(R.string.login_error), getString(R.string.auth_provider_disabled_user_error), getString(R.string.CUSTOMER_SUPPORT), (dialog, which) -> environment.getRouter() .showFeedbackScreen(RegisterActivity.this, getString(R.string.email_subject)), getString(android.R.string.cancel), null); } else { SocialFactory.SOCIAL_SOURCE_TYPE socialType = SocialFactory.SOCIAL_SOURCE_TYPE.fromString(backend); updateUIOnSocialLoginToEdxFailure(socialType, accessToken); } }

Target:
public void onUserLoginFailure(Exception ex, String accessToken, String backend) { tryToSetUIInteraction(true); logger.error(ex); if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.FORBIDDEN) { RegisterActivity.this.showAlertDialog(getString(R.string.login_error), getString(R.string.auth_provider_disabled_user_error), getString(R.string.label_customer_support), (dialog, which) -> environment.getRouter() .showFeedbackScreen(RegisterActivity.this, getString(R.string.email_subject_account_disabled)), getString(android.R.string.cancel), null); } else { SocialFactory.SOCIAL_SOURCE_TYPE socialType = SocialFactory.SOCIAL_SOURCE_TYPE.fromString(backend); updateUIOnSocialLoginToEdxFailure(socialType, accessToken); } }
Source:
protected void createFormContent(final IManagedForm managedForm) { super.createFormContent(managedForm); final ScrolledForm scrolledForm = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); int sessionUriSegmentSize = session.getSessionResource().getURI().segmentsList().size(); scrolledForm.setText( Messages.UI_SessionEditor_header_title_prefix + session.getSessionResource().getURI().segmentsList().subList(1, sessionUriSegmentSize).stream().collect(Collectors.joining(DELIMITER))); toolkit.decorateFormHeading(scrolledForm.getForm()); Composite body = managedForm.getForm().getBody(); body.setLayout(GridLayoutFactory.swtDefaults().create()); informativeLabel = toolkit.createLabel(body, "Informative message."); informativeLabel.setForeground(body.getDisplay().getSystemColor(SWT.COLOR_RED)); Composite subBody = toolkit.createComposite(body); subBody.setLayout(GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).create()); subBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createModelsControl(toolkit, subBody); Composite rightComposite = toolkit.createComposite(subBody); rightComposite.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create()); rightComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createRepresentationsControl(toolkit, rightComposite); createViewpointSelectionControl(toolkit, rightComposite); }

Target:
protected void createFormContent(final IManagedForm managedForm) { super.createFormContent(managedForm); final ScrolledForm scrolledForm = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); int sessionUriSegmentSize = session.getSessionResource().getURI().segmentsList().size(); scrolledForm.setText(MessageFormat.format(Messages.UI_SessionEditor_header_title_prefix, session.getSessionResource().getURI().segmentsList().subList(1, sessionUriSegmentSize).stream().collect(Collectors.joining(DELIMITER)))); toolkit.decorateFormHeading(scrolledForm.getForm()); Composite body = managedForm.getForm().getBody(); body.setLayout(GridLayoutFactory.swtDefaults().create()); informativeLabel = toolkit.createLabel(body, "Informative message."); informativeLabel.setForeground(body.getDisplay().getSystemColor(SWT.COLOR_RED)); Composite subBody = toolkit.createComposite(body); subBody.setLayout(GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).create()); subBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createModelsControl(toolkit, subBody); Composite rightComposite = toolkit.createComposite(subBody); rightComposite.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create()); rightComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); createRepresentationsControl(toolkit, rightComposite); createViewpointSelectionControl(toolkit, rightComposite); }
Source:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (!NullHandling.useDefaultValuesForNull() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }

Target:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }
Source:
public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { IAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); LttngKernelTrace trace = new LttngKernelTrace(); try { trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } testTrace.dispose(); time[i] = end - start; } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : "+ String.format("%.3f", 0.000001 * time[0]) +"ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }

Target:
public void testTrace() { long[] time = new long[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { IAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); try (LttngKernelTrace trace = new LttngKernelTrace()) { trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class); module.setTrace(trace); long start = System.nanoTime(); TmfTestHelper.executeAnalysis(module); long end = System.nanoTime(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace)); for (File file : suppDir.listFiles()) { file.delete(); } trace.dispose(); time[i] = end - start; } catch (TmfAnalysisException | TmfTraceException e) { fail(e.getMessage()); } } double avg = 0, avgHot = 0; for (int i = 0; i < LOOP_COUNT; i++) { avg += time[i]; if (i > 2) { avgHot += time[i]; } } System.out.println("Cache cold : " + String.format("%.3f", 0.000001 * time[0]) + "ms\t average time : " + String.format("%.3f", 0.000001 * avg / LOOP_COUNT) + " ms\t average (cache hot) time : " + String.format("%.3f", 0.000001 * (avgHot / LOOP_COUNT - 3))); }
Source:
public boolean isSizeGreaterThan(int s) { if (sparseMap.size() + tempListIdx > s) { mergeTempListToSparseMap(); return sparseMap.size() > s; } return false; }

Target:
public boolean isSizeGreaterThan(int s) { return sparseMap.size() > s; }
Source:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) { NetworkVO network = networkDao.findById(networkId); if (UserVmSearch == null && network != null) { SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); nicSearch.and("removed", nicSearch.entity().getRemoved(), SearchCriteria.Op.NULL); if (! network.getGuestType().equals(Network.GuestType.L2)) { nicSearch.and().op("ip4Address", nicSearch.entity().getIPv4Address(), SearchCriteria.Op.NNULL); nicSearch.or("ip6Address", nicSearch.entity().getIPv6Address(), SearchCriteria.Op.NNULL); nicSearch.cp(); } UserVmSearch = createSearchBuilder(); UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN); UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); UserVmSearch.done(); } SearchCriteria<UserVmVO> sc = UserVmSearch.create(); if (states != null && states.length != 0) { sc.setParameters("states", (Object[])states); } sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); }

Target:
public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) { NetworkVO network = networkDao.findById(networkId); recreateUserVmSeach(network); SearchCriteria<UserVmVO> sc = UserVmSearch.create(); if (states != null && states.length != 0) { sc.setParameters("states", (Object[])states); } sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); }
Source:
protected void stopBackgroundDiscovery() { logger.debug("Stopping Astro device background discovery"); if (astroDiscoveryJob != null && !astroDiscoveryJob.isCancelled()) { astroDiscoveryJob.cancel(true); astroDiscoveryJob = null; logger.debug("Stopped Astro device background discovery"); } }

Target:
protected void stopBackgroundDiscovery() { logger.debug("Stopping Astro device background discovery"); if (astroDiscoveryJob != null && !astroDiscoveryJob.isCancelled()) { if (astroDiscoveryJob.cancel(true)) { astroDiscoveryJob = null; logger.debug("Stopped Astro device background discovery"); } } }
Source:
boolean poll(PutRequestRegistrationCallback requestFillCallback) { Iterator<Map.Entry<Integer, ChunkPutRequest>> inFlightRequestsIterator = correlationIdToChunkPutRequest.entrySet().iterator(); while (inFlightRequestsIterator.hasNext()) { Map.Entry<Integer, ChunkPutRequest> entry = inFlightRequestsIterator.next(); if (time.milliseconds() - entry.getValue().startTimeMs > routerConfig.routerRequestTimeoutMs) { operationTracker.onResponse(entry.getValue().replicaId, false); chunkException = new RouterException("Timed out waiting for responses", RouterErrorCode.OperationTimedOut); inFlightRequestsIterator.remove(); } else { break; } } if (completeIfDone()) { return true; } Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = new Port(replicaId.getDataNodeId().getPort(), PortType.PLAINTEXT); PutRequest putRequest = createPutRequest(); RequestInfo request = new RequestInfo(hostname, port, putRequest); int correlationId = putRequest.getCorrelationId(); correlationIdToChunkPutRequest.put(correlationId, new ChunkPutRequest(replicaId, time.milliseconds())); correlationIdToPutChunk.put(correlationId, this); requestFillCallback.registerRequestToSend(PutOperation.this, request); replicaIterator.remove(); } return false; }

Target:
void poll(PutRequestRegistrationCallback requestFillCallback) { Iterator<Map.Entry<Integer, ChunkPutRequestInfo>> inFlightRequestsIterator = correlationIdToChunkPutRequestInfo.entrySet().iterator(); while (inFlightRequestsIterator.hasNext()) { Map.Entry<Integer, ChunkPutRequestInfo> entry = inFlightRequestsIterator.next(); if (time.milliseconds() - entry.getValue().startTimeMs > routerConfig.routerRequestTimeoutMs) { operationTracker.onResponse(entry.getValue().replicaId, false); chunkException = new RouterException("Timed out waiting for responses", RouterErrorCode.OperationTimedOut); inFlightRequestsIterator.remove(); } else { break; } } checkAndMaybeComplete(); if (isComplete()) { return; } Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = new Port(replicaId.getDataNodeId().getPort(), PortType.PLAINTEXT); PutRequest putRequest = createPutRequest(); RequestInfo request = new RequestInfo(hostname, port, putRequest); int correlationId = putRequest.getCorrelationId(); correlationIdToChunkPutRequestInfo.put(correlationId, new ChunkPutRequestInfo(replicaId, time.milliseconds())); correlationIdToPutChunk.put(correlationId, this); requestFillCallback.registerRequestToSend(PutOperation.this, request); replicaIterator.remove(); } }
Source:
public ApiFuture<RestoredTableResult> restoreTableAsync(RestoreTableRequest request) { return ApiFutureUtil.transformAndAdapt( delegate.restoreTableAsync( request.toProto(instanceName.getProjectId(), instanceName.getInstanceId())), new Function<Operation, RestoredTableResult>() { @Override public RestoredTableResult apply(Operation operation) { try { return new RestoredTableResult( Table.fromProto( operation.getResponse().unpack(com.google.bigtable.admin.v2.Table.class)), ""); } catch (InvalidProtocolBufferException e) { return new RestoredTableResult( Table.fromProto(com.google.bigtable.admin.v2.Table.getDefaultInstance()), ""); } } }); }

Target:
public ApiFuture<RestoredTableResult> restoreTableAsync(RestoreTableRequest request) { return ApiFutureUtil.transformAndAdapt( delegate.restoreTableAsync( request.toProto(instanceName.getProjectId(), instanceName.getInstanceId())), new Function<Operation, RestoredTableResult>() { @Override public RestoredTableResult apply(final Operation operation) { try { Future<Operation> operationFuture = batchThreadPool.submit( new Callable<Operation>() { @Override public Operation call() throws Exception { return delegate.waitForOperation(operation); } }); return new RestoredTableResult( Table.fromProto( operationFuture .get() .getResponse() .unpack(com.google.bigtable.admin.v2.Table.class)), operation .getMetadata() .unpack(com.google.bigtable.admin.v2.RestoreTableMetadata.class) .getOptimizeTableOperationName()); } catch (IOException | InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }); }
Source:
public List<TrackingEventResponse> getTrackingEvents() { return trackingEvents; }

Target:
public List<TrackingEventResponse> getTrackingEvents() { return defensiveCopy(this.trackingEvents); }
Source:
private static void handleWarDeployment(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (isWarDeployment(deploymentUnit) && JPADeploymentMarker.isJPADeployment(deploymentUnit)) { final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); PersistenceUnitMetadataHolder holder; ArrayList<PersistenceUnitMetadataHolder> puList = new ArrayList<PersistenceUnitMetadataHolder>(1); String deploymentRootName = null; if (deploymentRoot != null && (holder = deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null && holder.getPersistenceUnits().size() > 0) { puList.add(holder); deploymentRootName = deploymentRoot.getRootName() } List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot resourceRoot : resourceRoots) { if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { if ((holder = resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null && holder.getPersistenceUnits().size() > 0) { puList.add(holder); } } } if (startEarly) { deploymentUnit.addToAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS, new WebNonTxEmCloserAction()); } JPA_LOGGER.tracef("install persistence unit definitions for war %s", deploymentRootName); addPuService(phaseContext, puList, startEarly, platform); } }

Target:
private static void handleWarDeployment(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (isWarDeployment(deploymentUnit) && JPADeploymentMarker.isJPADeployment(deploymentUnit)) { final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); PersistenceUnitMetadataHolder holder; ArrayList<PersistenceUnitMetadataHolder> puList = new ArrayList<PersistenceUnitMetadataHolder>(1); String deploymentRootName = null; if (deploymentRoot != null && (holder = deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null && holder.getPersistenceUnits().size() > 0) { puList.add(holder); deploymentRootName = deploymentRoot.getRootName(); } List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot resourceRoot : resourceRoots) { if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { if ((holder = resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null && holder.getPersistenceUnits().size() > 0) { puList.add(holder); } } } if (startEarly) { deploymentUnit.addToAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS, new WebNonTxEmCloserAction()); } JPA_LOGGER.tracef("install persistence unit definitions for war %s", deploymentRootName); addPuService(phaseContext, puList, startEarly, platform); } }
Source:
private Constraint loadCost(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong( (machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) ) .filter(((machineCapacity, usage) -> machineCapacity.getSafetyCapacity() < usage)) .penalizeLong(MrConstraints.LOAD_COST, HardSoftLongScore.ofSoft(1L), (machineCapacity, usage) -> usage - machineCapacity.getSafetyCapacity()); }

Target:
private Constraint loadCost(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong((machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) ) .filter(((machineCapacity, usage) -> machineCapacity.getSafetyCapacity() < usage)) .penalizeLong(MrConstraints.LOAD_COST, HardSoftLongScore.ONE_SOFT, (machineCapacity, usage) -> usage - machineCapacity.getSafetyCapacity()); }
Source:
protected Set<Value.Immutable<?>> api$getVanillaValues() { Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); if (this.target != null) { this.targetEntity().map(Value::asImmutable).ifPresent(vanillaValues::add); } vanillaValues.add(this.direction().asImmutable()); return vanillaValues; }

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.shooter().asImmutable()); this.targetEntity().map(Value::asImmutable).ifPresent(values::add); values.add(this.direction().asImmutable()); return values; }
Source:
public void setup() throws ParseException { useTemplate = false; filename = null; useWorkflow = false; workflowNotify = false; if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); if (commandLine.hasOption('t')) { useTemplate = true; } if (commandLine.hasOption('w')) { useWorkflow = true; if (commandLine.hasOption('n')) { workflowNotify = true; } } else if (commandLine.hasOption('n')) { throw new ParseException( "Invalid option 'n': (notify) can only be specified with the 'w' (workflow) option."); } validateOnly = commandLine.hasOption('v'); try { c = new Context(); c.turnOffAuthorisationSystem(); } catch (Exception e) { throw new ParseException("Unable to create a new DSpace Context: " + e.getMessage()); } try { if (commandLine.hasOption('e')) { EPerson eperson; String e = commandLine.getOptionValue('e'); if (e.indexOf('@') != -1) { eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(c, e); } else { eperson = EPersonServiceFactory.getInstance().getEPersonService().find(c, UUID.fromString(e)); } if (eperson == null) { throw new ParseException("Error, eperson cannot be found: " + e); } c.setCurrentUser(eperson); } } catch (Exception e) { throw new ParseException("Unable to find DSpace user: " + e.getMessage()); } change = false; }

Target:
public void setup() throws ParseException { useTemplate = false; filename = null; useWorkflow = false; workflowNotify = false; if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); if (!commandLine.hasOption('e')) { throw new ParseException("Required parameter -e missing!"); } if (commandLine.hasOption('t')) { useTemplate = true; } if (commandLine.hasOption('w')) { useWorkflow = true; if (commandLine.hasOption('n')) { workflowNotify = true; } } else if (commandLine.hasOption('n')) { throw new ParseException( "Invalid option 'n': (notify) can only be specified with the 'w' (workflow) option."); } validateOnly = commandLine.hasOption('v'); change = false; }
Source:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (true) { if (tasks.offer(POISON_PILL)) { break; } } try { executorThread.join(); } catch (InterruptedException e) { } } }

Target:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (!tasks.offer(POISON_PILL)) { } try { executorThread.join(); } catch (InterruptedException e) { } } }
Source:
private String getSelectStatement(List<String> tables, List<String> columns, List<String> wheres) { String schema = this.getSchema(); String sql = ""; if (tables.isEmpty() || columns.isEmpty()) { return sql; } sql = "select "; for (String string : columns) { sql = sql + string + ","; } sql = sql.substring(0, sql.length() - 1) + " \nfrom "; for (String string : tables) { sql = sql + string + ","; } if (!wheres.isEmpty()) { sql = sql.substring(0, sql.length() - 1) + " \nwhere "; for (String string : wheres) { sql = sql + string + " and "; } } return sql; }

Target:
private String getSelectStatement(List<String> tables, List<String> columns, List<String> wheres) { String sql = ""; if (tables.isEmpty() || columns.isEmpty()) { return sql; } sql = "select "; for (String string : columns) { sql = sql + string + ","; } sql = sql.substring(0, sql.length() - 1) + " \nfrom "; for (String string : tables) { sql = sql + string + ","; } if (!wheres.isEmpty()) { sql = sql.substring(0, sql.length() - 1) + " \nwhere "; for (String string : wheres) { sql = sql + string + " and "; } } return sql; }
Source:
public void testValidateExternalVnicProfileMappingEmptyInputIsValid() { final List<ExternalVnicProfileMapping> vnicProfileMappings = Collections.emptyList(); final Set<EngineMessage> actual = underTest.validateExternalVnicProfileMapping(vnicProfileMappings, CLUSTER_ID); assertThat(actual, empty()); }

Target:
public void testValidateExternalVnicProfileMappingEmptyInputIsValid() { doTest(emptyList(), isValid()); }
Source:
private static long importData( String title, int numRunners, InputIterable data, BatchingNeoStores stores, Supplier<EntityImporter> visitors, ExecutionMonitor executionMonitor, StatsProvider memoryStatsProvider ) throws IOException { LongAdder roughEntityCountProgress = new LongAdder(); ExecutorService pool = Executors.newFixedThreadPool( numRunners, new NamedThreadFactory( title + "Importer" ) ); IoMonitor writeMonitor = new IoMonitor( stores.getIoTracer() ); ControllableStep step = new ControllableStep( title, roughEntityCountProgress, Configuration.DEFAULT, writeMonitor, memoryStatsProvider ); StageExecution execution = new StageExecution( title, null, Configuration.DEFAULT, Collections.singletonList( step ), 0 ); InputIterator dataIterator = data.iterator(); for ( int i = 0; i < numRunners; i++ ) { pool.submit( new ExhaustingEntityImporterRunnable( execution, dataIterator, visitors.get(), roughEntityCountProgress ) ); } pool.shutdown(); executionMonitor.start( execution ); long startTime = currentTimeMillis(); long nextWait = 0; try { while ( !pool.awaitTermination( nextWait, TimeUnit.MILLISECONDS ) ) { executionMonitor.check( execution ); nextWait = executionMonitor.nextCheckTime() - currentTimeMillis(); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); throw new IOException( e ); } execution.assertHealthy(); step.markAsCompleted(); writeMonitor.stop(); executionMonitor.end( execution, currentTimeMillis() - startTime ); return roughEntityCountProgress.sum(); }

Target:
private static long importData( String title, int numRunners, InputIterable data, BatchingNeoStores stores, Supplier<EntityImporter> visitors, ExecutionMonitor executionMonitor, StatsProvider memoryStatsProvider ) throws IOException { LongAdder roughEntityCountProgress = new LongAdder(); ExecutorService pool = Executors.newFixedThreadPool( numRunners, new NamedThreadFactory( title + "Importer" ) ); IoMonitor writeMonitor = new IoMonitor( stores.getIoTracer() ); ControllableStep step = new ControllableStep( title, roughEntityCountProgress, Configuration.DEFAULT, writeMonitor, memoryStatsProvider ); StageExecution execution = new StageExecution( title, null, Configuration.DEFAULT, Collections.singletonList( step ), 0 ); long startTime = currentTimeMillis(); try ( InputIterator dataIterator = data.iterator() ) { for ( int i = 0; i < numRunners; i++ ) { pool.submit( new ExhaustingEntityImporterRunnable( execution, dataIterator, visitors.get(), roughEntityCountProgress ) ); } pool.shutdown(); executionMonitor.start( execution ); long nextWait = 0; try { while ( !pool.awaitTermination( nextWait, TimeUnit.MILLISECONDS ) ) { executionMonitor.check( execution ); nextWait = executionMonitor.nextCheckTime() - currentTimeMillis(); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); throw new IOException( e ); } } execution.assertHealthy(); step.markAsCompleted(); writeMonitor.stop(); executionMonitor.end( execution, currentTimeMillis() - startTime ); execution.assertHealthy(); return roughEntityCountProgress.sum(); }
Source:
public long getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += sizeOf(levelOffsets); result += tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }

Target:
public long getEstimatedSizeInBytes() { long result = INSTANCE_SIZE + sizeOf(levelOffsets) + tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }
Source:
public static RenderingContextBuilder fillContext(RenderingContextBuilder builder, ServletRequest request) { builder.param(REQUEST_KEY, request); if (request instanceof HttpServletRequest) { HttpServletRequest webRequest = (HttpServletRequest) request; String baseURL = VirtualHostHelper.getBaseURL(request); if (webRequest.getUserPrincipal() != null) { CoreSession session = SessionFactory.getSession(webRequest); builder.base(baseURL).session(session); } Locale locale = request.getLocale(); if (locale != null) { builder.locale(locale); } Enumeration<String> headerNames = webRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = webRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { builder.param(headerName, headerValues.nextElement()); } } } for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { builder.paramValues(parameter.getKey(), (Object[]) parameter.getValue()); } Enumeration<String> attributeNames = request.getAttributeNames(); while (attributeNames.hasMoreElements()) { String attributeName = attributeNames.nextElement(); Object attributeValue = request.getAttribute(attributeName); builder.param(attributeName, attributeValue); } return builder; }

Target:
public static RenderingContextBuilder fillContext(RenderingContextBuilder builder, ServletRequest request) { builder.param(REQUEST_KEY, request); if (request instanceof HttpServletRequest) { HttpServletRequest webRequest = (HttpServletRequest) request; String baseURL = VirtualHostHelper.getBaseURL(request); builder.base(baseURL); builder.sessionWrapperSupplier(() -> { CoreSession session = SessionFactory.getSession(webRequest); return session == null ? null : new RenderingContext.SessionWrapper(session, false); }); Locale locale = request.getLocale(); if (locale != null) { builder.locale(locale); } Enumeration<String> headerNames = webRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = webRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { builder.param(headerName, headerValues.nextElement()); } } } for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { builder.paramValues(parameter.getKey(), (Object[]) parameter.getValue()); } Enumeration<String> attributeNames = request.getAttributeNames(); while (attributeNames.hasMoreElements()) { String attributeName = attributeNames.nextElement(); Object attributeValue = request.getAttribute(attributeName); builder.param(attributeName, attributeValue); } return builder; }
Source:
private void fetchGalleryCollection() { updateProgressBar(true, true, 0); new GalleryCollectionFetchTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle) { @Override public void onGalleryResult(GalleryCollection result) { updateProgressBar(false, true, 0); if (cacheOnLoad && page != null) { page.setGalleryCollection(result); app.getPageCache().put(pageTitle, page, new PageCache.CachePutListener() { @Override public void onPutComplete() { } @Override public void onPutError(Throwable e) { Log.e(TAG, "Failed to add page to cache.", e); } }); } applyGalleryCollection(result); } @Override public void onCatch(Throwable caught) { Log.e(TAG, "Failed to fetch gallery collection.", caught); updateProgressBar(false, true, 0); FeedbackUtil.showError(GalleryActivity.this, caught); FeedbackUtil.showError(GalleryActivity.this, caught); } }.execute(); }

Target:
private void fetchGalleryCollection() { updateProgressBar(true, true, 0); new GalleryCollectionFetchTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle) { @Override public void onGalleryResult(GalleryCollection result) { updateProgressBar(false, true, 0); if (cacheOnLoad && page != null) { page.setGalleryCollection(result); app.getPageCache().put(pageTitle, page, new PageCache.CachePutListener() { @Override public void onPutComplete() { } @Override public void onPutError(Throwable e) { Log.e(TAG, "Failed to add page to cache.", e); } }); } applyGalleryCollection(result); } @Override public void onCatch(Throwable caught) { Log.e(TAG, "Failed to fetch gallery collection.", caught); updateProgressBar(false, true, 0); FeedbackUtil.showError(GalleryActivity.this, caught); } }.execute(); }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { try (IAnalysisModule module = createModule();) { if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; } }

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { IAnalysisModule module = createModule(); if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; }
Source:
private static String translateRef(String oldPrefix, String newPrefix, String ref) { return newPrefix + ref.substring(oldPrefix.length()); }

Target:
private static String translateRef(String oldPrefix, String newPrefix, String ref) { if (!ref.startsWith(oldPrefix)) throw new IllegalArgumentException(ref + " does not start with " + oldPrefix); return newPrefix + ref.substring(oldPrefix.length()); }
Source:
public void add(HttpHeader header, String value) { Objects.requireNonNull(header, "header"); if (value == null) throw new IllegalArgumentException("null value"); HttpField field = new HttpField(header, value); add(field); }

Target:
public void add(HttpHeader header, String value) { Objects.requireNonNull(header, "header must not be null"); if (value == null) throw new IllegalArgumentException("null value"); HttpField field = new HttpField(header, value); add(field); }
Source:
SearchRequest getNextPageParameters() { return this.nextPageParameters; }

Target:
public SearchRequest getNextPageParameters() { return this.nextPageParameters; }
Source:
private static void fillDistributionMap(Map<String, Long> distributionMap, URIStatus status) { for (FileBlockInfo fileBlockInfo : status.getFileBlockInfos()) { long length = fileBlockInfo.getBlockInfo().getLength(); for (BlockLocation blockLocation : fileBlockInfo.getBlockInfo().getLocations()) { distributionMap.put(blockLocation.getWorkerAddress().getHost(), distributionMap.getOrDefault( blockLocation.getWorkerAddress().getHost(), 0L) + length); } } }

Target:
private static void fillDistributionMap(Map<String, Long> distributionMap, URIStatus status) { for (FileBlockInfo fileBlockInfo : status.getFileBlockInfos()) { long length = fileBlockInfo.getBlockInfo().getLength(); for (BlockLocation blockLocation : fileBlockInfo.getBlockInfo().getLocations()) { distributionMap.compute(blockLocation.getWorkerAddress().getHost(), (hostName, totalLength) -> totalLength == null ? length : totalLength + length ); } } }
Source:
@Test void testRowCountUnionDistinct() { final String sql = "select x from (values 'a', 'b') as t(x)\n" + "union\n" + "select x from (values 'a', 'b') as t(x)"; checkRowCount(sql, 2D, 2D, 4D); }

Target:
@Test void testRowCountUnionDistinct() { String sql = "select x from (values 'a', 'b') as t(x)\n" + "union\n" + "select x from (values 'a', 'b') as t(x)"; checkRowCount(sql, 2D, 1D, 4D); sql = "select x from (values 'a', 'a') as t(x)\n" + "union\n" + "select x from (values 'a', 'a') as t(x)"; checkRowCount(sql, 2D, 1D, 4D); }
Source:
public void shouldMapList() { Source source = new Source(); source.setStringList( Arrays.asList( "Bob", "Alice" ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getStringList() ).containsExactly( "Bob", "Alice" ); }

Target:
public void shouldMapList() { Source source = new Source(); source.setStringStream( Arrays.asList( "Bob", "Alice" ).stream() ); Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getStringList() ).containsExactly( "Bob", "Alice" ); }
Source:
protected void doTestRenewAuth(boolean applyFix) throws IOException { getBlobStoreContext(applyFix); injectShortLivedTokenForSoftlayerAmsterdam(); context.getBlobStore().createContainerInLocation(null, testContainerName); assertContainerFound(); log.info("created container, now sleeping for expiration"); Time.sleep(Duration.TEN_SECONDS); if (!applyFix) { try { assertContainerFound(); Assert.fail("should fail as long as "+RetryOnRenew.class+" is not working"); } catch (AssertionError e) { log.info("failed, as expected: "+e); } getAuthCache().invalidateAll(); log.info("invalidated, should now succeed"); } assertContainerFound(); context.getBlobStore().deleteContainer(testContainerName); }

Target:
protected void doTestRenewAuth(boolean applyFix) throws IOException { getBlobStoreContext(applyFix); injectShortLivedTokenForKeystoneV1_1(); context.getBlobStore().createContainerInLocation(null, testContainerName); assertContainerFound(); log.info("created container, now sleeping for expiration"); Time.sleep(Duration.TEN_SECONDS); if (!applyFix) { try { assertContainerFound(); } catch (Exception e) { log.info("failed, as expected: "+e); } getAuthCache().invalidateAll(); log.info("invalidated, should now succeed"); } assertContainerFound(); context.getBlobStore().deleteContainer(testContainerName); }
Source:
private Map<Guid, Guid> mapDisks(DiskAttachments diskAttachments) { Map<Guid, Guid> diskToImageIds = null; if (diskAttachments.isSetDiskAttachments()) { diskToImageIds = diskAttachments.getDiskAttachments().stream() .map(DiskAttachment::getDisk) .filter(Objects::nonNull) .map(d -> (DiskImage) DiskMapper.map(d, null)) .collect(Collectors.toMap(BaseDisk::getId, DiskImage::getImageId)); } return diskToImageIds; }

Target:
private Map<Guid, Guid> mapDisks(DiskAttachments diskAttachments) { Map<Guid, Guid> diskToImageIds = null; if (diskAttachments.isSetDiskAttachments()) { diskToImageIds = diskAttachments.getDiskAttachments().stream() .map(DiskAttachment::getDisk) .filter(Objects::nonNull) .map(disk -> (DiskImage) DiskMapper.map(disk, null)) .collect(Collectors.toMap(BaseDisk::getId, DiskImage::getImageId)); } return diskToImageIds; }