auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SecondaryIndexTable(TransactionServiceClient transactionServiceClient, HTableInterface hTable, byte[] secondaryIndex) { secondaryIndexTableName = TableName.valueOf(hTable.getName().getNameAsString() + ".idx"); HTable secondaryIndexHTable = null; HBaseAdmin hBaseAdmin = null; try { hBaseAdmin = new HBaseAdmin(hTable.getConfiguration()); if (!hBaseAdmin.tableExists(secondaryIndexTableName)) { hBaseAdmin.createTable(new HTableDescriptor(secondaryIndexTableName)); } secondaryIndexHTable = new HTable(hTable.getConfiguration(), secondaryIndexTableName); } catch (Exception e) { Throwables.propagate(e); } finally { try { hBaseAdmin.close(); } catch (Exception e) { Throwables.propagate(e); } } this.secondaryIndex = secondaryIndex; this.transactionAwareHTable = new TransactionAwareHTable(hTable); this.secondaryIndexTable = new TransactionAwareHTable(secondaryIndexHTable); this.transactionContext = new TransactionContext(transactionServiceClient, transactionAwareHTable, secondaryIndexTable); }

Target:
public SecondaryIndexTable(TransactionServiceClient transactionServiceClient, HTableInterface hTable, byte[] secondaryIndex) { secondaryIndexTableName = TableName.valueOf(hTable.getName().getNameAsString() + ".idx"); HTable secondaryIndexHTable = null; try (HBaseAdmin hBaseAdmin = new HBaseAdmin(hTable.getConfiguration())) { if (!hBaseAdmin.tableExists(secondaryIndexTableName)) { hBaseAdmin.createTable(new HTableDescriptor(secondaryIndexTableName)); } secondaryIndexHTable = new HTable(hTable.getConfiguration(), secondaryIndexTableName); } catch (Exception e) { Throwables.propagate(e); } this.secondaryIndex = secondaryIndex; this.transactionAwareHTable = new TransactionAwareHTable(hTable); this.secondaryIndexTable = new TransactionAwareHTable(secondaryIndexHTable); this.transactionContext = new TransactionContext(transactionServiceClient, transactionAwareHTable, secondaryIndexTable); }
Source:
void walkInnerSymbols(ObjectType type, String innerNamespace) { for (String propName : getSortedPublicPropertyNames(type)) { String qualifiedName = innerNamespace + '.' + propName; if (provides.contains(qualifiedName)) continue; JSType pType = type.getPropertyType(propName); Set<JSType> incompatibleTypes = new LinkedHashSet<>(); incompatibleTypes.add(pType); collectIncompatibleSuperTypes(type, propName, incompatibleTypes); incompatibleTypes.remove(pType); if (!pType.isEnumType() && !incompatibleTypes.isEmpty()) { errors.add(JSError.make(currentSymbol.getNode(), CLUTZ_OVERRIDDEN_STATIC_FIELD, innerNamespace, propName)); continue; } if (pType.isEnumType()) { visitEnumType(propName, (EnumType) pType, incompatibleTypes); } else if (isTrueConstructor(pType)) { visitClassOrInterface(propName, (FunctionType) pType); } else if (isTypedef(pType)) { JSType registryType = typeRegistry.getType(qualifiedName); visitTypeAlias(registryType, propName); } } }

Target:
void walkInnerSymbols(ObjectType type, String innerNamespace) { for (String propName : getSortedPublicPropertyNames(type)) { String qualifiedName = innerNamespace + '.' + propName; if (provides.contains(qualifiedName)) continue; JSType pType = type.getPropertyType(propName); Set<JSType> incompatibleTypes = getIncompatibleSuperTypes(type, propName, pType); if (!pType.isEnumType() && !incompatibleTypes.isEmpty()) { errors.add(JSError.make(currentSymbol.getNode(), CLUTZ_OVERRIDDEN_STATIC_FIELD, innerNamespace, propName)); continue; } if (pType.isEnumType()) { visitEnumType(propName, (EnumType) pType, incompatibleTypes); } else if (isClassLike(pType)) { visitClassOrInterface(propName, (FunctionType) pType); } else if (isTypedef(pType)) { JSType registryType = typeRegistry.getType(qualifiedName); visitTypeAlias(registryType, propName); } } }
Source:
private void reportPurityError(String msgKeyPrefix, Pair<Tree, String> r) { String reason = r.second; @SuppressWarnings("compilermessages") @CompilerMessageKey String msgKey = msgKeyPrefix + reason; if (reason.equals("call")) { if (r.first instanceof MethodInvocationTree) { MethodInvocationTree mitree = (MethodInvocationTree) r.first; checker.reportError(r.first, msgKey, mitree.getMethodSelect()); } else { NewClassTree nctree = (NewClassTree) r.first; checker.reportError(r.first, msgKey, nctree.getIdentifier()); } } else { checker.reportError(r.first, msgKey); } }

Target:
private void reportPurityError(String msgKeyPrefix, Pair<Tree, String> r) { String reason = r.second; @SuppressWarnings("compilermessages") @CompilerMessageKey String msgKey = msgKeyPrefix + reason; if (reason.equals("call")) { if (r.first.getKind() == Tree.Kind.METHOD_INVOCATION) { MethodInvocationTree mitree = (MethodInvocationTree) r.first; checker.reportError(r.first, msgKey, mitree.getMethodSelect()); } else { NewClassTree nctree = (NewClassTree) r.first; checker.reportError(r.first, msgKey, nctree.getIdentifier()); } } else { checker.reportError(r.first, msgKey); } }
Source:
public void testHashCode() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); assertNotEquals(null, blobCitationEntry); assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); }

Target:
public void testHashCode() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); assertNotNull(blobCitationEntry); assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); }
Source:
public void scanForRepoChanges() throws IOException { refs.refresh(); getAllRefs(); if (!isBare()) getIndex(); }

Target:
public void scanForRepoChanges() throws IOException { getAllRefs(); if (!isBare()) getIndex(); }
Source:
public DAnalysisSessionImpl(DAnalysis mainDAnalysis) { Preconditions.checkNotNull(mainDAnalysis); this.sessionResource = mainDAnalysis.eResource(); Preconditions.checkNotNull(this.sessionResource, Messages.DAnalysisSessionImpl_noRessourceErrorMsg); this.transactionalEditingDomain = Preconditions.checkNotNull(TransactionUtil.getEditingDomain(mainDAnalysis), Messages.DAnalysisSessionImpl_noEditingDomainErrorMsg); this.mainDAnalysis = mainDAnalysis; this.saver = new Saver(this); this.interpreter = new SessionInterpreter(); this.representationsChangeAdapter = new RepresentationsChangeAdapter(this); super.getAnalyses().add(mainDAnalysis); super.getResources().add(sessionResource); setAnalysisSelector(DAnalysisSelectorService.getSelector(this)); setResourceCollector(new LocalResourceCollector(getTransactionalEditingDomain().getResourceSet())); setDeferSaveToPostCommit(true); setSaveInExclusiveTransaction(true); getTransactionalEditingDomain().addResourceSetListener(new DRepresentationChangeListener(this)); }

Target:
public DAnalysisSessionImpl(DAnalysis mainDAnalysis) { Preconditions.checkNotNull(mainDAnalysis); this.sessionResource = mainDAnalysis.eResource(); Preconditions.checkNotNull(this.sessionResource, Messages.DAnalysisSessionImpl_noRessourceErrorMsg); this.transactionalEditingDomain = Preconditions.checkNotNull(TransactionUtil.getEditingDomain(mainDAnalysis), Messages.DAnalysisSessionImpl_noEditingDomainErrorMsg); this.mainDAnalysis = mainDAnalysis; this.saver = new Saver(this); this.interpreter = new SessionInterpreter(); this.representationsChangeAdapter = new RepresentationsChangeAdapter(this); super.getAnalyses().add(mainDAnalysis); super.getResources().add(sessionResource); setAnalysisSelector(DAnalysisSelectorService.getSelector(this)); setResourceCollector(new LocalResourceCollector(getTransactionalEditingDomain().getResourceSet())); setDeferSaveToPostCommit(true); setSaveInExclusiveTransaction(true); dRepresentationChangeListener = new DRepresentationChangeListener(this); getTransactionalEditingDomain().addResourceSetListener(dRepresentationChangeListener); }
Source:
public Translation enchantment$getTranslation() { return this.translation; }

Target:
public Translation getTranslation() { if (this.translation == null) { this.translation = new SpongeTranslation(shadow$getName()); } return this.translation; }
Source:
public void setSearchFilter(int index, SearchFilter searchFilter) { if (index < 0 || index >= this.getCount()) { throw new IllegalArgumentException("index is out of range." + ":" + index); } this.searchFilters.add(index, searchFilter); }

Target:
public void setSearchFilter(int index, SearchFilter searchFilter) { if (index < 0 || index >= this.getCount()) { throw new IllegalArgumentException( String.format("index %d is out of range [0..%d[.", index, this.getCount()) ); } this.searchFilters.add(index, searchFilter); }
Source:
public long getModificationDate() { if (getResource().isAccessible()) { return super.getModificationDate(); } return timestamp; }

Target:
public long getModificationDate() { return timestamp; }
Source:
public void deleteProjectFeatureFlag() throws Exception { final ProjectFeatureFlag featureFlag = gd.getFeatureFlagService().createProjectFeatureFlag(project, new ProjectFeatureFlag("settingName1")); gd.getFeatureFlagService().deleteProjectFeatureFlag(featureFlag); gd.getFeatureFlagService().getProjectFeatureFlag(project, "settingName1"); }

Target:
public void deleteProjectFeatureFlag() throws Exception { final ProjectFeatureFlag featureFlag = gd.getFeatureFlagService().createProjectFeatureFlag(project, new ProjectFeatureFlag("settingName1")); gd.getFeatureFlagService().deleteProjectFeatureFlag(featureFlag); try { gd.getFeatureFlagService().getProjectFeatureFlag(project, "settingName1"); fail(); } catch (GoodDataException e) { assertThat(e.getMessage(), containsString("Unable to get project feature flag:")); } }
Source:
public Entity getEntity() { return entity; }

Target:
public Entity getEntity() { return this.entity; }
Source:
public MemberDescription(String memberId, Optional<String> groupInstanceId, String clientId, String host, MemberAssignment assignment) { this.memberId = memberId == null ? "" : memberId; this.groupInstanceId = groupInstanceId; this.clientId = clientId == null ? "" : clientId; this.host = host == null ? "" : host; this.assignment = assignment == null ? new MemberAssignment(Collections.<TopicPartition>emptySet()) : assignment; }

Target:
MemberDescription(String memberId, Optional<String> groupInstanceId, String clientId, String host, MemberAssignment assignment) { this.memberId = memberId == null ? "" : memberId; this.groupInstanceId = groupInstanceId; this.clientId = clientId == null ? "" : clientId; this.host = host == null ? "" : host; this.assignment = assignment == null ? new MemberAssignment(Collections.emptySet()) : assignment; }
Source:
public boolean performNextOperation(int completedChildren) { if (completedChildren == getParameters().getDiskUpdatePhases().size()) { return false; } UpdateVmDiskParameters.Phase nextPhase = getParameters().getDiskUpdatePhases().get(completedChildren); switch (nextPhase) { case EXTEND_DISK: log.info("Start extend disk"); executeDiskExtend(); break; case AMEND_DISK: log.info("Start amend disk"); amendDiskImage(); break; case UPDATE_DISK: default: log.info("Start DB update disk"); performDiskUpdate(); if (getParameters().getDiskUpdatePhases().size() == completedChildren + 1) { return false; } } return true; }

Target:
public boolean performNextOperation(int completedChildren) { if (completedChildren == getParameters().getDiskUpdatePhases().size()) { return false; } UpdateVmDiskParameters.Phase nextPhase = getParameters().getDiskUpdatePhases().get(completedChildren); switch (nextPhase) { case EXTEND_DISK: log.info("Start to extend disk id '{}')", getOldDisk().getId()); executeDiskExtend(); break; case AMEND_DISK: log.info("Start to amend disk id '{}')", getOldDisk().getId()); amendDiskImage(); break; case UPDATE_DISK: log.info("Start to update general fields of disk id '{}')", getOldDisk().getId()); performDiskUpdate(); return false; } return true; }
Source:
private Response createGovernanceAsset(String assetType, DetachedGenericArtifact genericArtifact, String baseURL) throws RegistryException { String shortName = Util.getShortName(assetType); if (validateAssetType(shortName)){ if (isContentType(shortName, genericArtifact)) { String[][] propertyArray = new String[2][2]; propertyArray[0][0] = "version"; propertyArray[0][1] = genericArtifact.getAttribute(OVERVIEW_VERSION); propertyArray[1][0] = "resource.source"; propertyArray[1][1] = "GovernanceAPI"; Registry registry = getUserRegistry(); boolean isSuccessful = importResourceWithRegistry(registry, genericArtifact.getAttribute("overview_path") + genericArtifact.getAttribute(OVERVIEW_VERSION), genericArtifact.getAttribute("overview_name"), genericArtifact.getAttribute("overview_type"), null, genericArtifact.getAttribute("overview_url"), null, propertyArray); if (isSuccessful) { return Response.status(Response.Status.CREATED).build(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } else { try { GenericArtifactManager manager = getGenericArtifactManager(shortName); GenericArtifact artifact = genericArtifact.makeRegistryAware(manager); manager.addGenericArtifact(artifact); URI link = new URL(Util.generateLink(assetType, artifact.getId(), baseURL, false)).toURI(); return Response.created(link).build(); } catch (MalformedURLException | URISyntaxException e) { throw new GovernanceException(e); } } } return validationFail(shortName); }

Target:
private Response createGovernanceAsset(String assetType, DetachedGenericArtifact genericArtifact, String baseURL) throws RegistryException { String shortName = Util.getShortName(assetType); if (validateAssetType(shortName)){ if (isContentType(shortName, genericArtifact)) { String[][] propertyArray = new String[2][2]; propertyArray[0][0] = CommonConstants.VERSION; propertyArray[0][1] = genericArtifact.getAttribute(CommonConstants.OVERVIEW_VERSION); propertyArray[1][0] = CommonConstants.RESOURCE_SOURCE; propertyArray[1][1] = CommonConstants.GOVERNANCE_API; Registry registry = getUserRegistry(); boolean isSuccessful = importResourceWithRegistry(registry, genericArtifact.getAttribute(CommonConstants.OVERVIEW_PATH) + genericArtifact .getAttribute(CommonConstants.OVERVIEW_VERSION), genericArtifact.getAttribute(CommonConstants.OVERVIEW_NAME), genericArtifact.getAttribute(CommonConstants.OVERVIEW_TYPE), null, genericArtifact.getAttribute(CommonConstants.OVERVIEW_URL), null, propertyArray); if (isSuccessful) { return Response.status(Response.Status.CREATED).build(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } else { try { GenericArtifactManager manager = getGenericArtifactManager(shortName); GenericArtifact artifact = genericArtifact.makeRegistryAware(manager); manager.addGenericArtifact(artifact); URI link = new URL(Util.generateLink(assetType, artifact.getId(), baseURL, false)).toURI(); return Response.created(link).build(); } catch (MalformedURLException | URISyntaxException e) { throw new GovernanceException(e); } } } return validationFail(shortName); }
Source:
public synchronized TransactionalRequestResult initializeTransactions() { boolean isEpochBump = this.producerIdAndEpoch != ProducerIdAndEpoch.NONE; return handleCachedTransactionRequestResult(() -> { transitionTo(State.INITIALIZING); InitProducerIdRequestData requestData = new InitProducerIdRequestData() .setTransactionalId(transactionalId) .setTransactionTimeoutMs(transactionTimeoutMs) .setProducerId(this.producerIdAndEpoch.producerId) .setProducerEpoch(this.producerIdAndEpoch.epoch); InitProducerIdHandler handler = new InitProducerIdHandler(new InitProducerIdRequest.Builder(requestData), isEpochBump); enqueueRequest(handler); return handler.result; }, State.INITIALIZING); }

Target:
public synchronized TransactionalRequestResult initializeTransactions() { return initializeTransactions(ProducerIdAndEpoch.NONE); }
Source:
private Layout correctWrongEpochs(PollReport pollReport, Layout layout) { Map<String, Long> wrongEpochs = pollReport.getWrongEpochs(); if (wrongEpochs.isEmpty()) { return layout; } log.debug("Correct wrong epochs. Poll report: {}", pollReport); try { final Layout oldLayout = layout; Map<String, CompletableFuture<Layout>> layoutCompletableFutureMap = layout .getLayoutServers() .stream() .collect(Collectors.toMap(Function.identity(), server -> getLayoutFromServer(oldLayout, server)) ); Optional<Layout> latestLayout = fetchLatestLayout(layoutCompletableFutureMap); if (!latestLayout.isPresent()) { log.error("Can't get a layout from any server in the cluster. Layout servers: {}, wrong epochs: {}", layout.getLayoutServers(), wrongEpochs ); throw new IllegalStateException("Error in correcting server epochs. Local node is disconnected"); } Layout newManagementLayout = latestLayout.get(); serverContext.saveManagementLayout(newManagementLayout); sealMinServerSet(wrongEpochs, newManagementLayout); updateTrailingLayoutServers(newManagementLayout, layoutCompletableFutureMap); return newManagementLayout; } catch (QuorumUnreachableException e) { log.error("Error in correcting server epochs", e); } return serverContext.copyManagementLayout(); }

Target:
private Layout correctWrongEpochs(PollReport pollReport, Layout layout) { Map<String, Long> wrongEpochs = pollReport.getWrongEpochs(); if (wrongEpochs.isEmpty()) { return layout; } log.debug("Correct wrong epochs. Poll report: {}", pollReport); try { final Layout oldLayout = layout; Map<String, CompletableFuture<Layout>> layoutCompletableFutureMap = layout .getLayoutServers() .stream() .collect(Collectors.toMap(Function.identity(), server -> getLayoutFromServer(oldLayout, server)) ); Optional<Layout> latestLayout = fetchLatestLayout(layoutCompletableFutureMap); if (!latestLayout.isPresent()) { log.error("Can't get a layout from any server in the cluster. Layout servers: {}, wrong epochs: {}", layout.getLayoutServers(), wrongEpochs ); throw new IllegalStateException("Error in correcting server epochs. Local node is disconnected"); } Layout newManagementLayout = serverContext.saveManagementLayout(latestLayout.get()); sealWithLatestLayout(wrongEpochs, newManagementLayout); updateTrailingLayoutServers(newManagementLayout, layoutCompletableFutureMap); return newManagementLayout; } catch (QuorumUnreachableException e) { log.error("Error in correcting server epochs", e); } return serverContext.copyManagementLayout(); }
Source:
public synchronized void close() throws IOException { if (closed) { return; } try { flushInternal(true); threadExecutor.shutdown(); } catch (IOException e) { throw wrapException(path, e.getMessage(), e); } finally { lastError = new IOException(FSExceptionMessages.STREAM_IS_CLOSED); buffer = null; bufferIndex = 0; closed = true; writeOperations.clear(); if (!threadExecutor.isShutdown()) { threadExecutor.shutdownNow(); } } LOG.debug("Closing AbfsOutputStream ", toString()); }

Target:
public synchronized void close() throws IOException { if (closed) { return; } try { flushInternal(true); threadExecutor.shutdown(); } catch (IOException e) { throw wrapException(path, e.getMessage(), e); } finally { lastError = new IOException(FSExceptionMessages.STREAM_IS_CLOSED); buffer = null; bufferIndex = 0; closed = true; writeOperations.clear(); if (!threadExecutor.isShutdown()) { threadExecutor.shutdownNow(); } } if (LOG.isDebugEnabled()) { LOG.debug("Closing AbfsOutputStream ", toString()); } }
Source:
protected void joinTestJobs() { try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( monitor -> Job.getJobManager().join(TestJob.FAMILY_TEST_JOB, monitor)); } catch (InterruptedException | InvocationTargetException e) { e.printStackTrace(); } }

Target:
protected void joinTestJobs() { try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( monitor -> Job.getJobManager().join(TestJob.FAMILY_TEST_JOB, monitor)); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
Source:
public StapNewWizardPage(ISelection selection) { super("wizardPage"); setTitle("Systemtap Script"); setDescription("This wizard creates a new systemtap script."); this.selection = selection; }

Target:
public StapNewWizardPage(ISelection selection) { super(Messages.getString("StapNewWizardPage.WizardPage")); setTitle(Messages.getString("StapNewWizardPage.Title")); setDescription(Messages.getString("StapNewWizardPage.setDescription")); this.selection = selection; }
Source:
public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException { com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest modifyColumnRequest = com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest .of(tableName.getNameAsString()); modifyColumnRequest.addFamily(columnFamilyDesc.getNameAsString(), buildGarbageCollectionRule(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); modifyColumns(modifyColumnRequest); }

Target:
public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException { ModifyColumnFamiliesRequest request = ModifyColumnFamiliesRequest.of(tableName.getNameAsString()); request.addFamily(columnFamilyDesc.getNameAsString(), buildGarbageCollectionRule(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); modifyColumns(request); }
Source:
private void runImpl() throws IOException { Transport tn = Transport.open(git, uri); PushResult res; try { res = pushVia(tn); } finally { try { tn.close(); } catch (Throwable e2) { log.warn("Unexpected error while closing " + uri, e2); } } for (RemoteRefUpdate u : res.getRemoteUpdates()) { switch (u.getStatus()) { case OK: case UP_TO_DATE: case NON_EXISTING: break; case NOT_ATTEMPTED: case AWAITING_REPORT: case REJECTED_NODELETE: case REJECTED_NONFASTFORWARD: case REJECTED_REMOTE_CHANGED: log.error(String.format("Failed replicate of %s to %s: status %s", u.getRemoteName(), uri, u.getStatus())); break; case REJECTED_OTHER_REASON: if ("non-fast-forward".equals(u.getMessage())) { log.error(String.format("Failed replicate of %s to %s" + ", remote rejected non-fast-forward push." + " Check receive.denyNonFastForwards variable in config file" + " of destination repository.", u.getRemoteName(), uri)); } else if ("failed to lock".equals(u.getMessage())) { throw new RemoteRepositoryException(uri, u.getMessage()); } else { log.error(String.format( "Failed replicate of %s to %s, reason: %s", u.getRemoteName(), uri, u.getMessage())); } break; } } }

Target:
private void runImpl() throws IOException { Transport tn = Transport.open(git, uri); PushResult res; try { res = pushVia(tn); } finally { try { tn.close(); } catch (Throwable e2) { log.warn("Unexpected error while closing " + uri, e2); } } for (RemoteRefUpdate u : res.getRemoteUpdates()) { switch (u.getStatus()) { case OK: case UP_TO_DATE: case NON_EXISTING: break; case NOT_ATTEMPTED: case AWAITING_REPORT: case REJECTED_NODELETE: case REJECTED_NONFASTFORWARD: case REJECTED_REMOTE_CHANGED: log.error(String.format("Failed replicate of %s to %s: status %s", u.getRemoteName(), uri, u.getStatus())); break; case REJECTED_OTHER_REASON: if ("non-fast-forward".equals(u.getMessage())) { log.error(String.format("Failed replicate of %s to %s" + ", remote rejected non-fast-forward push." + " Check receive.denyNonFastForwards variable in config file" + " of destination repository.", u.getRemoteName(), uri)); } else if ("failed to lock".equals(u.getMessage())) { throw new LockFailureException(uri, u.getMessage()); } else { log.error(String.format( "Failed replicate of %s to %s, reason: %s", u.getRemoteName(), uri, u.getMessage())); } break; } } }
Source:
static RuntimeException launderCacheLoaderException(Exception e) { if (!(e instanceof javax.cache.integration.CacheLoaderException)) { return new javax.cache.integration.CacheLoaderException("Exception in CacheLoader", e); } else { return new PersistenceException(e); } }

Target:
static RuntimeException launderCacheLoaderException(Exception e) { if (!(e instanceof CacheLoaderException)) { return new CacheLoaderException("Exception in CacheLoader", e); } else { return new PersistenceException(e); } }
Source:
private SafeHtml createBondTooltipMessage(HostInterfaceLineModel lineModel, InterfaceStatus interfaceStatus) { Bond bond = (Bond) lineModel.getInterface(); StringBuilder bondProperties = new StringBuilder(messages.bondStatus(interfaceStatus.toString())); boolean isBond4 = BondMode.BOND4.equals(BondMode.parseBondMode(bond.getBondOptions())); if (InterfaceStatus.UP.equals(interfaceStatus) && isBond4) { bondProperties.append("\n").append(createActiveBondTooltipMessage(bond, lineModel)); } if ((bond.getActiveSlave() != null) && (bond.getActiveSlave().length() > 0)) { bondProperties.append("\n"); bondProperties.append(messages.bondActiveSlave(bond.getActiveSlave())); } return new SafeHtmlBuilder().appendEscapedLines(bondProperties.toString()).toSafeHtml(); }

Target:
private SafeHtml createBondTooltipMessage(HostInterfaceLineModel lineModel, InterfaceStatus interfaceStatus) { Bond bond = (Bond) lineModel.getInterface(); StringBuilder bondProperties = new StringBuilder(messages.bondStatus(interfaceStatus.toString())); boolean isBond4 = BondMode.BOND4.equals(BondMode.parseBondMode(bond.getBondOptions())); if (InterfaceStatus.UP.equals(interfaceStatus) && isBond4) { bondProperties.append("\n").append(createActiveBondTooltipMessage(bond, lineModel)); } if ((bond.getActiveSlave() != null) && (bond.getActiveSlave().length() > 0)) { bondProperties.append("\n").append(messages.bondActiveSlave(bond.getActiveSlave())); } return new SafeHtmlBuilder().appendEscapedLines(bondProperties.toString()).toSafeHtml(); }
Source:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } BalancerStrategyFactory factory= null; if (COST.equals(config.getCoordinatorBalancerStrategy())) factory = new CostBalancerStrategyFactory(); else if (RANDOM.equals(config.getCoordinatorBalancerStrategy())) factory= new RandomBalancerStrategyFactory(); else if (COST_MULTI.equals(config.getCoordinatorBalancerStrategy())) factory = new CostBalancerMultithreadStrategyFactory(config.getCostBalancerStrategyThreadCount()); DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); for (DruidCoordinatorHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }

Target:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } BalancerStrategyFactory factory = new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads()); DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); for (DruidCoordinatorHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }
Source:
public void testFail() { final boolean[] flags = new boolean[4]; TmfEventRequest request = setupTestRequest(flags); request.fail(null); assertTrue("isCompleted", request.isCompleted()); assertTrue("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertTrue("handleCompleted", flags[0]); assertFalse("handleSuccess", flags[1]); assertTrue("handleFailure", flags[2]); assertFalse("handleCancel", flags[3]); }

Target:
public void testFail() { final boolean[] flags = new boolean[4]; TmfEventRequest request = setupTestRequest(flags); request.fail(new IllegalArgumentException("Bad argument")); final Throwable failCause = request.getFailCause(); assertTrue("isCompleted", request.isCompleted()); assertTrue("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertNotNull("Cause of failure", failCause); assertEquals("Cause of failure message", "Bad argument", failCause.getCause().getMessage()); assertTrue("handleCompleted", flags[0]); assertFalse("handleSuccess", flags[1]); assertTrue("handleFailure", flags[2]); assertFalse("handleCancel", flags[3]); }
Source:
public AsyncFuture<Void> sendBatches(Collection<Batch> batches) { final ArrayList<Metric> metrics = new ArrayList<>(); batches.forEach(batch -> batch.getPoints().forEach( point -> metrics.add(convertBatchMetric(batch, point)))); return sendMetrics(metrics); }

Target:
public AsyncFuture<Void> sendBatches(Collection<Batch> batches) { final ArrayList<Metric> metrics = new ArrayList<>(); batches.forEach(batch -> { batch.getPoints().forEach(point -> { metrics.add(convertBatchMetric(batch, point)); }); }); return sendMetrics(metrics); }
Source:
static <T> Try<T> ofSupplier(Supplier<? extends T> supplier) { try { return new Success<>(supplier.get()); } catch (Throwable t) { return new Failure<>(t); } }

Target:
static <T> Try<T> ofSupplier(Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return of(supplier::get); }
Source:
public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException { try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (SProcessDefinitionReadException | IOException | XMLParseException e) { throw new SProcessDefinitionNotFoundException(e, processDefinitionId); } }

Target:
public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException, SProcessDefinitionReadException { try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (IOException | XMLParseException e) { throw new SProcessDefinitionReadException(e); } }
Source:
public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); int oid = getTypeInfo().getPGArrayType(typeName.toLowerCase()); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); }

Target:
public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); int oid = getTypeInfo().getPGArrayType(typeName); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); }
Source:
public Response invoke(String application, String entityToken, String effectorName, String timeout, Map<String, String> parameters) { final EntityLocal entity = brooklyn().getEntity(application, entityToken); Maybe<Effector<?>> effector = EffectorUtils.findEffectorDeclared(entity, effectorName); if (effector.isAbsentOrNull()) throw WebResourceUtils.notFound("Entity '%s' has no effector with name '%s'", entityToken, effectorName); log.info("REST invocation of " + entity + "." + effector.get() + " " + parameters); Task<?> t = entity.invoke(effector.get(), parameters); try { Object result = null; if (timeout == null || timeout.isEmpty() || "never".equalsIgnoreCase(timeout)) { result = t.get(); } else { long timeoutMillis = "always".equalsIgnoreCase(timeout) ? 0 : Time.parseTimeString(timeout); try { if (timeoutMillis == 0) throw new TimeoutException(); result = t.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { return Response.status(Response.Status.ACCEPTED).entity(TaskTransformer.taskSummary(t)).build(); } } return Response.status(Response.Status.ACCEPTED).entity(result).build(); } catch (Exception e) { throw Exceptions.propagate(e); } }

Target:
public Response invoke(String application, String entityToken, String effectorName, String timeout, Map<String, String> parameters) { final EntityLocal entity = brooklyn().getEntity(application, entityToken); Maybe<Effector<?>> effector = EffectorUtils.findEffectorDeclared(entity, effectorName); if (effector.isAbsentOrNull()) throw WebResourceUtils.notFound("Entity '%s' has no effector with name '%s'", entityToken, effectorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.INVOKE_EFFECTOR, Entitlements.EntityAndItem.of(entity, effector.get().getName()))) { throw WebResourceUtils.unauthorized("User '%s' is not authorized to invoke effector %s on entity %s", Entitlements.getEntitlementContext().user(), effector.get().getName(), entity); } log.info("REST invocation of " + entity + "." + effector.get() + " " + parameters); Task<?> t = entity.invoke(effector.get(), parameters); try { Object result = null; if (timeout == null || timeout.isEmpty() || "never".equalsIgnoreCase(timeout)) { result = t.get(); } else { long timeoutMillis = "always".equalsIgnoreCase(timeout) ? 0 : Time.parseTimeString(timeout); try { if (timeoutMillis == 0) throw new TimeoutException(); result = t.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { return Response.status(Response.Status.ACCEPTED).entity(TaskTransformer.taskSummary(t)).build(); } } return Response.status(Response.Status.ACCEPTED).entity(result).build(); } catch (Exception e) { throw Exceptions.propagate(e); } }
Source:
private Object getFromMetricsMessage(String groupName, String metricName) { if (metricsMessage.containsKey(groupName)) { return metricsMessage.get(groupName).get(metricName); } else { return null; } }

Target:
private Object getFromMetricsMessage(String groupName, String metricName) { if (metricsMessage.containsKey(groupName) && metricsMessage.get(groupName) != null) { return metricsMessage.get(groupName).get(metricName); } else { return null; } }
Source:
default P getClosestPointTo(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); final double[] segments = new double[] { triangle.getX1(), triangle.getY1(), triangle.getX2(), triangle.getY2(), triangle.getX2(), triangle.getY2(), triangle.getX3(), triangle.getY3(), triangle.getX3(), triangle.getY3(), triangle.getX1(), triangle.getY1(), }; final P point = getGeomFactory().newPoint(); final P tmp = getGeomFactory().newPoint(); double minDistance = Double.POSITIVE_INFINITY; final double ox1 = getX1(); final double oy1 = getY1(); final double ox2 = getX2(); final double oy2 = getY2(); final int magicFour = 4; for (int i = 0; i < segments.length; i += magicFour) { final double x1 = segments[i]; final double y1 = segments[i + 1]; final double x2 = segments[i + 2]; final double y2 = segments[i + 3]; final double distance = computeClosestPointToSegment(ox1, oy1, ox2, oy2, x1, y1, x2, y2, tmp); if (distance < minDistance) { minDistance = distance; point.set(tmp); } } return point; }

Target:
default P getClosestPointTo(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); final double[] segments = new double[] { triangle.getX1(), triangle.getY1(), triangle.getX2(), triangle.getY2(), triangle.getX2(), triangle.getY2(), triangle.getX3(), triangle.getY3(), triangle.getX3(), triangle.getY3(), triangle.getX1(), triangle.getY1(), }; final P point = getGeomFactory().newPoint(); final P tmp = getGeomFactory().newPoint(); double minDistance = Double.POSITIVE_INFINITY; final double ox1 = getX1(); final double oy1 = getY1(); final double ox2 = getX2(); final double oy2 = getY2(); for (int i = 0; i < segments.length;) { final double x1 = segments[i++]; final double y1 = segments[i++]; final double x2 = segments[i++]; final double y2 = segments[i++]; final double distance = computeClosestPointToSegment(ox1, oy1, ox2, oy2, x1, y1, x2, y2, tmp); if (distance < minDistance) { minDistance = distance; point.set(tmp); } } return point; }
Source:
private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); log.info("Created keyspace: {}", UnsafeArg.of("keyspace", config.getKeyspaceOrThrow())); CassandraKeyValueServices.waitForSchemaVersions(config, client, "after adding the initial empty keyspace"); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }

Target:
private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); log.info("Created keyspace: {}", SafeArg.of("keyspace", config.getKeyspaceOrThrow())); CassandraKeyValueServices.waitForSchemaVersions(config, client, "after adding the initial empty keyspace"); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }
Source:
private void onBoardNew() { logger.info("Menu: Boards > New"); promptToSaveCurrentBoard(); List<PanelInfo> currentPanelInfos = panels.getCurrentPanelInfos(); panels.closeAllPanels(); boolean aborted = !onBoardSaveAs(); if (aborted) { panels.openPanels(currentPanelInfos); } }

Target:
private void onBoardNew() { logger.info("Menu: Boards > New"); if (isCurrentBoardDirty() && isUserAgreeableToSavingBorad()) { saveBoard(); logger.info("Changes to the current board saved."); } else { logger.info("User abandoned unsaved changes."); } newBoard(); }
Source:
private static String mapFlagsToStringUsingAnnotation( int value, @Nullable ViewDebug.ExportedProperty annotation) { if (!canFlagsBeMappedToString(annotation)) { throw new IllegalStateException("Cannot map using this annotation"); } StringBuilder stringBuilder = new StringBuilder(); boolean atLeastOneFlag = false; for (ViewDebug.FlagToString flagToString : annotation.flagMapping()) { if (flagToString.outputIf() == ((value & flagToString.mask()) == flagToString.equals())) { if (atLeastOneFlag) { stringBuilder.append(" | "); } stringBuilder.append(flagToString.name()); atLeastOneFlag = true; } } if (atLeastOneFlag) { return stringBuilder.toString(); } else { return NONE_MAPPING; } }

Target:
private static String mapFlagsToStringUsingAnnotation( int value, @Nullable ViewDebug.ExportedProperty annotation) { if (!canFlagsBeMappedToString(annotation)) { throw new IllegalStateException("Cannot map using this annotation"); } StringBuilder stringBuilder = null; boolean atLeastOneFlag = false; for (ViewDebug.FlagToString flagToString : annotation.flagMapping()) { if (flagToString.outputIf() == ((value & flagToString.mask()) == flagToString.equals())) { if (stringBuilder == null) { stringBuilder = new StringBuilder(); } if (atLeastOneFlag) { stringBuilder.append(" | "); } stringBuilder.append(flagToString.name()); atLeastOneFlag = true; } } if (atLeastOneFlag) { return stringBuilder.toString(); } else { return NONE_MAPPING; } }
Source:
private ContextServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.CONTEXT_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.CONTEXT_SERVICE)) .setAddHandler(ContextServiceAdd.INSTANCE) .setRemoveHandler(ContextServiceRemove.INSTANCE) .addCapabilities(CAPABILITY)); }

Target:
private ContextServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.CONTEXT_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.CONTEXT_SERVICE)) .setAddHandler(ContextServiceAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(ContextServiceAdd.INSTANCE)) .addCapabilities(CAPABILITY)); }
Source:
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VViewFactory.eINSTANCE.createControl())); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VTableFactory.eINSTANCE.createTableControl())); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VCompoundcontrolFactory.eINSTANCE.createCompoundControl())); }

Target:
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VViewFactory.eINSTANCE.createControl())); try { Class.forName("org.eclipse.emf.ecp.view.spi.table.model.VTableFactory"); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VTableFactory.eINSTANCE.createTableControl())); } catch (final ClassNotFoundException ex) { } try { Class.forName("org.eclipse.emf.ecp.view.spi.compoundcontrol.model.VCompoundcontrolFactory"); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VCompoundcontrolFactory.eINSTANCE.createCompoundControl())); } catch (final ClassNotFoundException ex) { } }
Source:
public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { boolean inSetup = !Jenkins.getInstance().getInstallState().isSetupComplete(); if(!inSetup && hasSomeUser()) { rsp.sendError(SC_UNAUTHORIZED,"First user was already created"); return; } String view = "firstUser.jelly"; User admin = null; if(inSetup) { admin = getUser(SetupWizard.initialSetupAdminUserName); view = "setupWizardFirstUser.jelly"; } User u = createAccount(req, rsp, false, view); if (u!=null) { tryToMakeAdmin(u); if(admin != null) { admin.delete(); } Jenkins.getInstance().setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); loginAndTakeBack(req, rsp, u); } }

Target:
public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { boolean inSetup = !Jenkins.getInstance().getInstallState().isSetupComplete(); if(!inSetup && hasSomeUser()) { rsp.sendError(SC_UNAUTHORIZED,"First user was already created"); return; } User admin = null; try { String view = "firstUser.jelly"; if(inSetup) { admin = getUser(SetupWizard.initialSetupAdminUserName); if(admin != null) { admin.delete(); } view = "setupWizardFirstUser.jelly"; } User u = createAccount(req, rsp, false, view); if (u!=null) { tryToMakeAdmin(u); if(admin != null) { admin = null; } Jenkins.getInstance().setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); loginAndTakeBack(req, rsp, u); } } finally { if(admin != null) { admin.save(); } } }