auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCompletionPerPrefixFirstChar() { for (ContentProposal prefix : availablePrefixes) { String firstChar = prefix.getProposal().substring(0, 1); List<ContentProposal> proposals = getProposals(firstChar); ContentProposalConverter converter = new ContentProposalConverter(firstChar); assertEquals("Proposals should contains only one proposal", 1, proposals.size()); assertTrue("Proposals should be contained by available prefixes", availablePrefixes.containsAll(proposals)); for (ContentProposal proposal : proposals) { IContentProposal jfaceProposal = converter.convertToJFaceContentProposal(proposal); assertEquals("", proposal.getProposal(), firstChar + jfaceProposal.getContent()); assertEquals("JFace proposal cursor position is not well computed", proposal.getCursorPosition() - (proposal.getProposal().length() - jfaceProposal.getContent().length()), jfaceProposal.getCursorPosition()); } } }

Target:
public void testCompletionPerPrefixFirstChar() { for (ContentProposal emptyExpression : availableEmptyExpressions) { String firstChar = emptyExpression.getProposal().substring(0, 1); List<ContentProposal> proposals = getProposals(firstChar); ContentProposalConverter converter = new ContentProposalConverter(firstChar); assertEquals("Proposals should contains only one proposal", 1, proposals.size()); assertTrue("Proposals should be contained by available empty expressions", availableEmptyExpressions.containsAll(proposals)); ContentProposal proposal = proposals.get(0); IContentProposal jfaceProposal = converter.convertToJFaceContentProposal(proposal); assertEquals("", proposal.getProposal(), firstChar + jfaceProposal.getContent()); assertEquals("JFace proposal cursor position is not well computed", proposal.getCursorPosition() - (proposal.getProposal().length() - jfaceProposal.getContent().length()), jfaceProposal.getCursorPosition()); } }
Source:
public void observePIP(@Observes ProcessInjectionPoint<PoorWorker, String> pip) { listOfProducerEvents.add(pip); }

Target:
public void observePIP(@Observes ProcessInjectionPoint<PoorWorker, String> pip) { ActionSequence.addAction(PRODUCER_SEQ, "PIP"); }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running UsersToDeleteThread - " + new Date()); try { run(); } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running UsersToDeleteThread - " + new Date()); run(); }
Source:
private void fillInMetadata(DepositMetadata depositMetadata, Workflow workflow, WorkflowVersion workflowVersion) { depositMetadata.setTitle(workflow.getWorkflowPath()); depositMetadata.setUploadType(DepositMetadata.UploadTypeEnum.SOFTWARE); String description = workflow.getDescription(); String descriptionStr = (description == null || description.isEmpty()) ? "no description" : workflow.getDescription(); depositMetadata.setDescription(descriptionStr); DepositMetadata.AccessRightEnum accessRight = (depositMetadata.getAccessRight() == null) ? DepositMetadata.AccessRightEnum.OPEN : depositMetadata.getAccessRight(); depositMetadata.setAccessRight(accessRight); if (accessRight == DepositMetadata.AccessRightEnum.OPEN || accessRight == DepositMetadata.AccessRightEnum.EMBARGOED) { String license = (depositMetadata.getLicense() == null || depositMetadata.getLicense().isEmpty()) ? "CC-BY-4.0" : depositMetadata.getLicense(); depositMetadata.setLicense(license); } depositMetadata.setVersion(workflowVersion.getName()); setMetadataKeywords(depositMetadata, workflow); setMetadataRelatedIdentifiers(depositMetadata, workflow); setMetadataCreator(depositMetadata, workflow); setMetadataPublicationDate(depositMetadata, workflowVersion); setMetadataCommunities(depositMetadata); }

Target:
private void fillInMetadata(DepositMetadata depositMetadata, Workflow workflow, WorkflowVersion workflowVersion) { depositMetadata.setTitle(workflow.getWorkflowPath()); depositMetadata.setUploadType(DepositMetadata.UploadTypeEnum.SOFTWARE); String description = workflow.getDescription(); String descriptionStr = (description == null || description.isEmpty()) ? "no description" : workflow.getDescription(); depositMetadata.setDescription(descriptionStr); depositMetadata.setVersion(workflowVersion.getName()); setMetadataKeywords(depositMetadata, workflow); setMetadataRelatedIdentifiers(depositMetadata, workflow); setMetadataCreator(depositMetadata, workflow); setMetadataPublicationDate(depositMetadata, workflowVersion); setMetadataCommunities(depositMetadata); }
Source:
private SerializedValue getSerializedValue(RestAction<?> action, Object object) throws ActionException { String bodyClass = action.getBodyClass(); List<String> contentTypes = action.getClientProducedContentTypes(); if (bodyClass != null) { Serialization serialization = findSerialization(bodyClass, contentTypes); if (serialization != null) { return serialize(serialization, object, bodyClass, contentTypes); } } throw new ActionException("Unable to serialize request body. No serializer found."); }

Target:
private SerializedValue getSerializedValue(RestAction<?> action, Object object) throws ActionException { String bodyClass = action.getBodyClass(); if (bodyClass != null) { List<ContentType> contentTypes = action.getClientProducedContentTypes(); Serialization serialization = findSerialization(bodyClass, contentTypes); if (serialization != null) { return serialize(serialization, object, bodyClass, contentTypes); } } throw new ActionException("Unable to serialize request body. No serializer found."); }
Source:
public ExternalDatabaseStatus getStatus(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { LOGGER.debug("DB Instance does not exists: {}", ex.getMessage()); return ExternalDatabaseStatus.DELETED; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .map(i -> getExternalDatabaseStatus(i.getDBInstanceStatus())) .findFirst() .get(); }

Target:
public ExternalDatabaseStatus getStatus(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { LOGGER.debug("DB Instance does not exist: {}", ex.getMessage()); return ExternalDatabaseStatus.DELETED; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .map(i -> getExternalDatabaseStatus(i.getDBInstanceStatus())) .findFirst() .get(); }
Source:
private static StringSchemaInfo getStringSchemaInfo(TSnowflakeOutputProperties outputProperties, Schema mainSchema, List<Field> columns) { boolean isUpperCase = false; boolean upsert = false; if (outputProperties != null) { isUpperCase = outputProperties.convertColumnsAndTableToUppercase.getValue(); upsert = UPSERT.equals(outputProperties.outputAction.getValue()); } List<String> keyStr = new ArrayList<>(); List<String> columnsStr = new ArrayList<>(); int i = 0; for (Field overlapField : columns) { Field f; if ((f = overlapField) == null && (Boolean.valueOf((f = mainSchema.getFields().get(i)).getProp(SnowflakeAvroRegistry.TALEND_FIELD_AUTOINCREMENTED)))) { i++; continue; } i++; String dbColumnName = f.getProp(SchemaConstants.TALEND_COLUMN_DB_COLUMN_NAME); if (dbColumnName == null) { dbColumnName = f.name(); } String fName = isUpperCase ? dbColumnName.toUpperCase() : dbColumnName; columnsStr.add(fName); if (null != f.getProp(SchemaConstants.TALEND_COLUMN_IS_KEY)) { keyStr.add(fName); } } if (upsert) { keyStr.clear(); keyStr.add(outputProperties.upsertKeyColumn.getValue()); } return new StringSchemaInfo(keyStr, columnsStr); }

Target:
private static StringSchemaInfo getStringSchemaInfo(TSnowflakeOutputProperties outputProperties, Schema mainSchema, List<Field> columns) { boolean isUpperCase = false; boolean upsert = false; if (outputProperties != null) { isUpperCase = outputProperties.convertColumnsAndTableToUppercase.getValue(); upsert = UPSERT.equals(outputProperties.outputAction.getValue()); } List<String> keyStr = new ArrayList<>(); List<String> columnsStr = new ArrayList<>(); int i = 0; for (Field overlapField : columns) { Field f = overlapField == null ? mainSchema.getFields().get(i) : overlapField; i++; if (Boolean.valueOf(f.getProp(SnowflakeAvroRegistry.TALEND_FIELD_AUTOINCREMENTED))) { continue; } String dbColumnName = f.getProp(SchemaConstants.TALEND_COLUMN_DB_COLUMN_NAME); if (dbColumnName == null) { dbColumnName = f.name(); } String fName = isUpperCase ? dbColumnName.toUpperCase() : dbColumnName; columnsStr.add(fName); if (null != f.getProp(SchemaConstants.TALEND_COLUMN_IS_KEY)) { keyStr.add(fName); } } if (upsert) { keyStr.clear(); keyStr.add(outputProperties.upsertKeyColumn.getValue()); } return new StringSchemaInfo(keyStr, columnsStr); }
Source:
private void assertNextIterations(TestNavigatable navigatable, TestContext context, int startingElement) { TreeItem previousSelection = (TreeItem)context.getItem(startingElement); for (int expectedElement = startingElement + 1; expectedElement <= context.getNumberOfNodes(); expectedElement++) { TreeItem nextItem = navigatable.getNextItem(previousSelection); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("Error with configuration: Starting iteration point=").append( startingElement).append(", previsous item=").append(previousSelection.getText()); assertNotNull(messageBuilder.toString(), nextItem); assertEquals(messageBuilder.toString(), expectedElement, Integer.valueOf(nextItem.getText()) .intValue()); previousSelection = nextItem; } assertNull(navigatable.getNextItem(previousSelection)); }

Target:
private void assertNextIterations(TestNavigatable navigatable, TestContext context, int startingElement) { TreeItem previousSelection = context.getItem(startingElement); for (int expectedElement = startingElement + 1; expectedElement <= context.getNumberOfNodes(); expectedElement++) { TreeItem nextItem = navigatable.getNextItem(previousSelection); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("Error with configuration: Starting iteration point=").append( startingElement).append(", previsous item=").append(previousSelection.getText()); assertNotNull(messageBuilder.toString(), nextItem); assertEquals(messageBuilder.toString(), expectedElement, Integer.valueOf(nextItem.getText()) .intValue()); previousSelection = nextItem; } assertNull(navigatable.getNextItem(previousSelection)); }
Source:
public synchronized Map<String, Object> getScopeElements() { if (elements == null) { elements = new HashMap<>(); elements.put("audio", audioManager); elements.put("voice", voiceManager); } return elements; }

Target:
public Map<String, Object> getScopeElements() { Map<String, Object> elements = new HashMap<>(); elements.put("audio", audioManager); elements.put("voice", voiceManager); return Collections.unmodifiableMap(elements); }
Source:
private void initialize(List<LogSegment> segmentsToLoad, long segmentCapacityInBytes) throws IOException { if (segmentsToLoad.size() == 0) { segmentsToLoad = Collections.singletonList(checkArgsAndGetFirstSegment(segmentCapacityInBytes)); } long totalSegments = -1; for (LogSegment segment : segmentsToLoad) { if (segment.getName().isEmpty()) { totalSegments = 1; } else { totalSegments = totalSegments == -1 ? capacityInBytes / segment.getCapacityInBytes() : totalSegments; } segmentsByName.put(segment.getName(), segment); } remainingUnallocatedSegments.set(totalSegments - segmentsByName.size()); activeSegment = segmentsByName.lastEntry().getValue(); }

Target:
private void initialize(List<LogSegment> segmentsToLoad, long segmentCapacityInBytes) throws IOException { if (segmentsToLoad.size() == 0) { segmentsToLoad = Collections.singletonList(checkArgsAndGetFirstSegment(segmentCapacityInBytes)); } LogSegment firstSegment = segmentsToLoad.get(0); long totalSegments = firstSegment.getName().isEmpty() ? 1 : capacityInBytes / firstSegment.getCapacityInBytes(); for (LogSegment segment : segmentsToLoad) { segmentsByName.put(segment.getName(), segment); } remainingUnallocatedSegments.set(totalSegments - segmentsByName.size()); activeSegment = segmentsByName.lastEntry().getValue(); }
Source:
public void test() { Expression actual = expression("NOT(orderkey = 3 AND custkey = 3 AND orderkey < 10)"); SymbolAliases symbolAliases = SymbolAliases.builder() .put("X", new SymbolReference("orderkey")) .put("Y", new SymbolReference("custkey")) .build(); ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); assertTrue(verifier.process(actual, expression("NOT(X = 3 AND Y = 3 AND X < 10)"))); assertThrows(() -> verifier.process(actual, expression("NOT(X = 3 AND Y = 3 AND Z < 10)"))); assertFalse(verifier.process(actual, expression("NOT(X = 3 AND X = 3 AND X < 10)"))); RowExpressionVerifier rowExpressionVerifier = new RowExpressionVerifier(symbolAliases, metadata, TEST_SESSION); assertTrue(rowExpressionVerifier.process(expression("NOT(X = 3 AND Y = 3 AND X < 10)"), translate(actual))); assertThrows(() -> rowExpressionVerifier.process(expression("NOT(X = 3 AND Y = 3 AND Z < 10)"), translate(actual))); assertFalse(rowExpressionVerifier.process(expression("NOT(X = 3 AND X = 3 AND X < 10)"), translate(actual))); }

Target:
public void test() { Expression actual = expression("NOT(orderkey = 3 AND custkey = 3 AND orderkey < 10)"); SymbolAliases symbolAliases = SymbolAliases.builder() .put("X", new SymbolReference("orderkey")) .put("Y", new SymbolReference("custkey")) .build(); ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); RowExpressionVerifier rowExpressionVerifier = new RowExpressionVerifier(symbolAliases, metadata, TEST_SESSION); assertTrue(process(actual, expression("NOT(X = 3 AND Y = 3 AND X < 10)"), symbolAliases, metadata)); assertThrows(() -> verifier.process(actual, expression("NOT(X = 3 AND Y = 3 AND Z < 10)"))); assertThrows(() -> rowExpressionVerifier.process(expression("NOT(X = 3 AND Y = 3 AND Z < 10)"), translate(actual))); assertFalse(process(actual, expression("NOT(X = 3 AND X = 3 AND X < 10)"), symbolAliases, metadata)); }
Source:
public boolean equals(Object o) { return reflectionEquals(this, o); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TpcdsDataSource that = (TpcdsDataSource) o; return scaleFactor == that.scaleFactor && table == that.table; }
Source:
protected void deactivate() { threadPool.shutdown(); logger.info("jetty thread pool shutdown"); }

Target:
protected void deactivate() { try { if (commonHttpClient != null) { commonHttpClient.stop(); commonHttpClientFacade = null; commonHttpClient = null; threadPool = null; logger.info("jetty shared http client stopped"); } } catch (Exception e) { logger.error("error while stopping jetty shared http client", e); } }
Source:
public void finish() { String shellText = getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsActive(shellText)); }

Target:
public void finish() { new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(this)); }
Source:
private Path generateArtifact(String id, String version) throws IOException { try { return generate(id, version); } catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e) { throw new IOException(e); } }

Target:
public Path generateArtifact(String id, String version) throws IOException { try { return generate(id, version); } catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e) { throw new IOException(e); } }
Source:
private Collection<Snapshot> getSnapshotsToBeExportedWithMemory() { if (getParameters().getCopyCollapse()) { Snapshot activeSnapshot = snapshotDao.get(getVmId(), SnapshotType.ACTIVE); return activeSnapshot.containsMemory() ? Collections.singleton(activeSnapshot) : Collections.emptyList(); } else { return snapshotDao.getAll(getVmId()).stream().filter(s -> s.containsMemory()).collect(Collectors.toList()); } }

Target:
private Collection<Snapshot> getSnapshotsToBeExportedWithMemory() { if (getParameters().getCopyCollapse()) { Snapshot activeSnapshot = snapshotDao.get(getVmId(), SnapshotType.ACTIVE); return activeSnapshot.containsMemory() ? Collections.singleton(activeSnapshot) : Collections.emptyList(); } else { return snapshotDao.getAll(getVmId()).stream().filter(Snapshot::containsMemory).collect(Collectors.toList()); } }
Source:
public String toString() { return "IotasSource{" + "declaredStreams=" + outputStreams + "} " + super.toString(); }

Target:
public String toString() { return "IotasSource{" + "outputStreams=" + outputStreams + "} " + super.toString(); }
Source:
private void schedulePeriodicWorks() { m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { if (m_statsManager != null) { m_statsManager.sendNotification(); } } }, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { ((RealVoltDB)VoltDB.instance()).getFLC().checkCounter(System.currentTimeMillis()); } }, 0, 10, TimeUnit.SECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(false, false); } }, 0, 5, TimeUnit.SECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, false); } }, 0, 1, TimeUnit.MINUTES)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, true); } }, 0, 6, TimeUnit.MINUTES)); EnterpriseMaintenance em = EnterpriseMaintenance.get(); if (em != null) { em.setupMaintenaceTasks(); } GCInspector.instance.start(m_periodicPriorityWorkThread, m_gcStats); }

Target:
private void schedulePeriodicWorks() { m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { if (m_statsManager != null) { m_statsManager.sendNotification(); } } }, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { ScheduledExecutorService es = VoltDB.instance().getSES(false); if (es != null && !es.isShutdown()) { es.submit(new Runnable() { @Override public void run() { long timestamp = System.currentTimeMillis(); m_flc.checkCounter(timestamp); } }); } } }, 0, 10, TimeUnit.SECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(false, false); } }, 0, 5, TimeUnit.SECONDS)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, false); } }, 0, 1, TimeUnit.MINUTES)); m_periodicWorks.add(scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, true); } }, 0, 6, TimeUnit.MINUTES)); EnterpriseMaintenance em = EnterpriseMaintenance.get(); if (em != null) { em.setupMaintenaceTasks(); } GCInspector.instance.start(m_periodicPriorityWorkThread, m_gcStats); }
Source:
public boolean isAlreadyVotedMessageVisible() { wait.forElementVisible(votedMessage); return votedMessage.isDisplayed(); }

Target:
public boolean isAlreadyVotedMessageVisible() { return isElementDisplayed(votedMessage); }
Source:
private void assignNewImage(URI pagesDirectory, String currentPngFile) { File temporaryTifFile = null; try { temporaryTifFile = File.createTempFile("tempTif_", ".tif"); } catch (IOException e) { logger.error(e.getMessage(), e); } if (this.image != null) { try { URI tifFile = this.currentTifFolder.resolve(this.image); logger.trace("tiffconverterpfad: {}", tifFile); if (!fileService.fileExist(tifFile)) { tifFile = serviceManager.getProcessService().getImagesTifDirectory(true, this.process) .resolve(this.image); Helper.setFehlerMeldung("formularOrdner:TifFolders", "", "image " + this.image + " does not exist in folder " + this.currentTifFolder + ", using image from " + new File(serviceManager.getProcessService().getImagesTifDirectory(true, this.process)) .getName()); } try (InputStream tifFileInputStream = fileService.read(tifFile)) { if (temporaryTifFile != null) { FileUtils.copyInputStreamToFile(tifFileInputStream, temporaryTifFile); this.imageHelper.scaleFile(temporaryTifFile.toURI(), pagesDirectory.resolve(currentPngFile), this.imageSize, this.imageRotation); logger.trace("scaleFile"); } } } catch (Exception e) { Helper.setFehlerMeldung("could not getById image folder", e); logger.error(e.getMessage(), e); } finally { if (temporaryTifFile != null) { try { if (!fileService.delete(temporaryTifFile.toURI())) { logger.error( "Error while deleting temporary tif file: " + temporaryTifFile.getAbsolutePath()); } } catch (IOException e) { logger.error("Error while deleting temporary tif file: " + e.getMessage()); } } } } }

Target:
private void assignNewImage(URI pagesDirectory, String currentPngFile) { File temporaryTifFile = null; try { temporaryTifFile = File.createTempFile("tempTif_", ".tif"); } catch (IOException e) { logger.error(e.getMessage(), e); } if (this.image != null) { try { URI tifFile = this.currentTifFolder.resolve(this.image); logger.trace("tiffconverterpfad: {}", tifFile); if (!fileService.fileExist(tifFile)) { tifFile = serviceManager.getProcessService().getImagesTifDirectory(true, this.process) .resolve(this.image); Helper.setFehlerMeldung("formularOrdner:TifFolders", "", "image " + this.image + " does not exist in folder " + this.currentTifFolder + ", using image from " + new File(serviceManager.getProcessService().getImagesTifDirectory(true, this.process)) .getName()); } try (InputStream tifFileInputStream = fileService.read(tifFile)) { if (temporaryTifFile != null) { FileUtils.copyInputStreamToFile(tifFileInputStream, temporaryTifFile); this.imageHelper.scaleFile(temporaryTifFile.toURI(), pagesDirectory.resolve(currentPngFile), this.imageSize, this.imageRotation); logger.trace("scaleFile"); } } } catch (IOException | ImageManipulatorException | ImageManagerException | RuntimeException e) { Helper.setErrorMessage("could not getById image folder", logger, e); } finally { if (temporaryTifFile != null) { try { if (!fileService.delete(temporaryTifFile.toURI())) { logger.error( "Error while deleting temporary tif file: " + temporaryTifFile.getAbsolutePath()); } } catch (IOException e) { logger.error("Error while deleting temporary tif file: " + e.getMessage()); } } } } }
Source:
public void setUp() throws Exception { super.setUp(); final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app"). entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName(), ImmutableMap.of("install.version", "1.0.0")))). locations(ImmutableSet.of("localhost")). build(); ClientResponse response = clientDeploy(simpleSpec); assertTrue(response.getStatus() >= 200 && response.getStatus() <= 299); application = response.getLocation(); waitForApplicationToBeRunning(application); }

Target:
public void setUp() throws Exception { super.setUp(); final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app"). entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName(), ImmutableMap.of("install.version", "1.0.0")))). locations(ImmutableSet.of("localhost")). build(); ClientResponse response = clientDeploy(simpleSpec); int status = response.getStatus(); assertTrue(status >= 200 && status <= 299, "expected HTTP Response of 2xx but got " + status); application = response.getLocation(); waitForApplicationToBeRunning(application); }
Source:
public ExpiringCacheAsync(long expiry) throws IllegalArgumentException { this.expiry = TimeUnit.MILLISECONDS.toNanos(expiry); if (expiry <= 0) { throw new IllegalArgumentException("Cache expire time must be greater than 0"); } }

Target:
public ExpiringCacheAsync(long expiry) throws IllegalArgumentException { if (expiry <= 0) { throw new IllegalArgumentException("Cache expire time must be greater than 0"); } this.expiry = TimeUnit.MILLISECONDS.toNanos(expiry); }
Source:
public static void declareExchange(Connection connection, String exchangeName, Hashtable<String, String> properties) throws IOException { Boolean exchangeAvailable = false; Channel channel = connection.createChannel(); String exchangeType = properties .get(RabbitMQConstants.EXCHANGE_TYPE); String durable = properties.get(RabbitMQConstants.EXCHANGE_DURABLE); String autoDelete = properties.get(RabbitMQConstants.EXCHANGE_AUTODELETE); try { channel.exchangeDeclarePassive(exchangeName); exchangeAvailable = true; } catch (IOException e) { log.info("Exchange :" + exchangeName + " not found.Declaring exchange."); } if (!exchangeAvailable) { if (!channel.isOpen()) { channel = connection.createChannel(); log.debug("Channel is not open. Creating a new channel."); } try { if (exchangeType != null && !exchangeType.equals("")) { if (durable != null && !durable.equals("")) { if (autoDelete != null && !autoDelete.isEmpty()) { channel.exchangeDeclare(exchangeName, exchangeType, Boolean.parseBoolean(durable), Boolean.parseBoolean(autoDelete), null); } else { channel.exchangeDeclare(exchangeName, exchangeType, Boolean.parseBoolean(durable)); } } else { channel.exchangeDeclare(exchangeName, exchangeType, true); } } else { channel.exchangeDeclare(exchangeName, "direct", true); } } catch (IOException e) { handleException("Error occurred while declaring exchange.", e); } } try { channel.close(); } catch (TimeoutException e) { log.error("Error occurred while closing connection.", e); } }

Target:
public static void declareExchange(Connection connection, String exchangeName, Hashtable<String, String> properties) throws IOException { Boolean exchangeAvailable = false; Channel channel = connection.createChannel(); String exchangeType = properties .getOrDefault(RabbitMQConstants.EXCHANGE_TYPE, RabbitMQConstants.EXCHANGE_TYPE_DEFAULT); String durable = properties .getOrDefault(RabbitMQConstants.EXCHANGE_DURABLE, RabbitMQConstants.EXCHANGE_DURABLE_DEFAULT); String autoDelete = properties .getOrDefault(RabbitMQConstants.EXCHANGE_AUTODELETE, RabbitMQConstants.EXCHANGE_AUTODELETE_DEFAULT); if (exchangeType.isEmpty()) { exchangeType = RabbitMQConstants.EXCHANGE_TYPE_DEFAULT; } if (durable.isEmpty()) { durable = RabbitMQConstants.EXCHANGE_DURABLE_DEFAULT; } if (autoDelete.isEmpty()) { autoDelete = RabbitMQConstants.EXCHANGE_AUTODELETE_DEFAULT; } try { channel.exchangeDeclarePassive(exchangeName); exchangeAvailable = true; } catch (IOException e) { log.info("Exchange :" + exchangeName + " not found.Declaring exchange."); } if (!exchangeAvailable) { if (!channel.isOpen()) { channel = connection.createChannel(); log.debug("Channel is not open. Creating a new channel."); } try { channel.exchangeDeclare(exchangeName, exchangeType, Boolean.parseBoolean(durable), Boolean.parseBoolean(autoDelete), null); } catch (IOException e) { handleException("Error occurred while declaring exchange.", e); } } try { channel.close(); } catch (TimeoutException e) { log.error("Error occurred while closing connection.", e); } }
Source:
private void removeListener(OrderedRealmCollection<T> data) { if (data instanceof RealmResults) { RealmResults realmResults = (RealmResults) data; realmResults.realm.handlerController.removeWeakChangeListener(listener); } else if (data instanceof RealmList) { RealmList realmList = (RealmList) data; realmList.realm.handlerController.removeWeakChangeListener(listener); } else { throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass()); } }

Target:
private void removeListener(OrderedRealmCollection<T> data) { BaseRealm realm = getRealm(data); if (realm != null && !realm.isClosed()) { realm.removeChangeListener(listener); } }
Source:
public void testCooperativeSubscription() { builder.addSource(null, "source1", null, null, null, "topic1"); builder.addSource(null, "source2", null, null, null, "topic2"); builder.addProcessor("processor", new MockProcessorSupplier(), "source1", "source2"); final Set<TaskId> prevTasks = mkSet( new TaskId(0, 1), new TaskId(1, 1), new TaskId(2, 1)); final Set<TaskId> standbyTasks = mkSet( new TaskId(0, 1), new TaskId(1, 1), new TaskId(2, 1), new TaskId(0, 2), new TaskId(1, 2), new TaskId(2, 2)); final UUID processId = UUID.randomUUID(); createMockTaskManager(prevTasks, standbyTasks, processId, builder); EasyMock.replay(taskManager); configureDefaultPartitionAssignor(); final Set<String> topics = mkSet("topic1", "topic2"); final Subscription subscription = new Subscription( new ArrayList<>(topics), partitionAssignor.subscriptionUserData(topics)); Collections.sort(subscription.topics()); assertEquals(asList("topic1", "topic2"), subscription.topics()); final SubscriptionInfo info = getInfo(processId, getTaskOffsetSums(prevTasks, standbyTasks), null); assertEquals(info, SubscriptionInfo.decode(subscription.userData())); }

Target:
public void testCooperativeSubscription() { builder.addSource(null, "source1", null, null, null, "topic1"); builder.addSource(null, "source2", null, null, null, "topic2"); builder.addProcessor("processor", new MockProcessorSupplier(), "source1", "source2"); final Set<TaskId> prevTasks = mkSet( new TaskId(0, 1), new TaskId(1, 1), new TaskId(2, 1)); final Set<TaskId> standbyTasks = mkSet( new TaskId(0, 1), new TaskId(1, 1), new TaskId(2, 1), new TaskId(0, 2), new TaskId(1, 2), new TaskId(2, 2)); createMockTaskManager(prevTasks, standbyTasks); configureDefaultPartitionAssignor(); final Set<String> topics = mkSet("topic1", "topic2"); final Subscription subscription = new Subscription( new ArrayList<>(topics), partitionAssignor.subscriptionUserData(topics)); Collections.sort(subscription.topics()); assertEquals(asList("topic1", "topic2"), subscription.topics()); final SubscriptionInfo info = getInfo(uuid1, prevTasks, standbyTasks); assertEquals(info, SubscriptionInfo.decode(subscription.userData())); }
Source:
boolean verifyOrCreateRemoteSpecialFolder(Account account, String folderName, Folder remoteFolder, MessagingListener listener, MessagingController controller) throws MessagingException { if (folderName.equals(account.getTrashFolderName()) || folderName.equals(account.getSentFolderName()) || folderName.equals(account.getDraftsFolderName())) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : controller.getListeners(listener)) { l.synchronizeMailboxFinished(account, folderName, 0, 0); } Timber.i("Done synchronizing folder %s", folderName); return false; } } } return true; }

Target:
boolean verifyOrCreateRemoteSpecialFolder(Account account, String folderName, Folder remoteFolder, MessagingListener listener, MessagingController controller) throws MessagingException { if ((folderName.equals(account.getTrashFolderName()) || folderName.equals(account.getSentFolderName()) || folderName.equals(account.getDraftsFolderName())) && !remoteFolder.exists() && !remoteFolder.create(FolderType.HOLDS_MESSAGES)) { for (MessagingListener l : controller.getListeners(listener)) { l.synchronizeMailboxFinished(account, folderName, 0, 0); } Timber.i("Done synchronizing folder %s", folderName); return false; } return true; }
Source:
public boolean hasFailedChecksum() { return !sourceMd5.equals(md5); }

Target:
public boolean hasFailedChecksum() { return isMissingSourceMd5() ? false : !sourceMd5.equals(md5); }
Source:
public Enumeration<URL> getResources(final String name) throws IOException { final Vector<URL> resources = new Vector<URL>(); final Enumeration<URL> parentResources = this.getParent().getResources(name); while (parentResources.hasMoreElements()) { resources.add(parentResources.nextElement()); } final Enumeration<URL> childResources = this.findResources(name); while (childResources.hasMoreElements()) { resources.add(childResources.nextElement()); } return resources.elements(); }

Target:
public Enumeration<URL> getResources(final String name) throws IOException { final Vector<URL> resources = new Vector<>(); final Enumeration<URL> parentResources = this.getParent().getResources(name); while (parentResources.hasMoreElements()) { resources.add(parentResources.nextElement()); } final Enumeration<URL> childResources = this.findResources(name); while (childResources.hasMoreElements()) { resources.add(childResources.nextElement()); } return resources.elements(); }
Source:
public GerritConstantsProperties() throws IOException { InputStream constantsStream = GerritTopMenus.class.getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES); if (constantsStream != null) { load(constantsStream); } else { log.error("Cannot locate Gerrit constants from classpath", GERRIT_CONSTANTS_PROPERTIES); } }

Target:
public GerritConstantsProperties() throws IOException { InputStream constantsStream = getClass().getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES); if (constantsStream != null) { try { load(constantsStream); } finally { constantsStream.close(); } } else { log.error("Cannot locate Gerrit constants from classpath", GERRIT_CONSTANTS_PROPERTIES); } }
Source:
public List<Class<? extends WindupRuleProvider>> getExecuteAfter() { Rules ann = this.getClass().getAnnotation(Rules.class); if(ann != null) return Arrays.asList(ann.after()); else return Collections.emptyList(); }

Target:
public List<Class<? extends WindupRuleProvider>> getExecuteAfter() { Rules rulesAnnotation = this.getClass().getAnnotation(Rules.class); if(rulesAnnotation != null) return Arrays.asList(rulesAnnotation.after()); else return Collections.emptyList(); }
Source:
public void testSTLineFromText() throws Exception { assertQuery("select ST_AsText(ST_LineFromText('LINESTRING EMPTY'))", "select 'MULTILINESTRING EMPTY'"); assertQuery("select ST_AsText(ST_LineFromText('LineString(1 1, 2 2, 1 3)'))", "select 'LINESTRING (1 1, 2 2, 1 3)'"); assertQueryFails("select ST_AsText(ST_LineFromText('MULTILineString EMPTY'))", "ST_LineFromText only applies to LineString. Input type is: MultiLineString"); assertQueryFails("select ST_AsText(ST_LineFromText('Polygon ((1 1, 1 4, 4 4, 4 1))'))", "ST_LineFromText only applies to LineString. Input type is: Polygon"); }

Target:
public void testSTLineFromText() throws Exception { assertFunction("ST_AsText(ST_LineFromText('LINESTRING EMPTY'))", VARCHAR, "MULTILINESTRING EMPTY"); assertFunction("ST_AsText(ST_LineFromText('LINESTRING (1 1, 2 2, 1 3)'))", VARCHAR, "LINESTRING (1 1, 2 2, 1 3)"); assertInvalidFunction("ST_AsText(ST_LineFromText('MULTILINESTRING EMPTY'))", "ST_LineFromText only applies to LINE_STRING. Input type is: MULTI_LINE_STRING"); assertInvalidFunction("ST_AsText(ST_LineFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'))", "ST_LineFromText only applies to LINE_STRING. Input type is: POLYGON"); }
Source:
public void should_pass_given_percent_of_samples() throws Exception { samplerConfiguration.setPercentage(0.3d); int numberOfSampledElements = countNumberOfSampledElements(); then(numberOfSampledElements).isCloseTo(30, withPercentage(30)); }

Target:
public void should_pass_given_percent_of_samples() throws Exception { int numberOfIterations = 10000; float percentage = 0.3f; samplerConfiguration.setPercentage(percentage); int numberOfSampledElements = countNumberOfSampledElements(numberOfIterations); then(numberOfSampledElements).isCloseTo((int) (numberOfIterations * percentage), withPercentage(3)); }
Source:
public ReplicaPolicy getReplicaPolicy() { if (replicaPolicy == null) { replicaPolicy = new ReplicaPolicy(networkHealthCheck, this); replicaPolicy.setQuorumSize(quorumSize); replicaPolicy.setVoteOnReplicationFailure(voteOnReplicationFailure); replicaPolicy.setVoteRetries(voteRetries); replicaPolicy.setVoteRetryWait(voteRetryWait); if (clusterName != null && clusterName.length() > 0) { replicaPolicy.setClusterName(clusterName); } if (groupName != null && groupName.length() > 0) { replicaPolicy.setGroupName(groupName); } replicaPolicy.setQuorumVoteWait(quorumVoteWait); } return replicaPolicy; }

Target:
public ReplicaPolicy getReplicaPolicy() { if (replicaPolicy == null) { replicaPolicy = new ReplicaPolicy(networkHealthCheck, this, quorumVoteWait); replicaPolicy.setQuorumSize(quorumSize); replicaPolicy.setVoteOnReplicationFailure(voteOnReplicationFailure); replicaPolicy.setVoteRetries(voteRetries); replicaPolicy.setVoteRetryWait(voteRetryWait); if (clusterName != null && clusterName.length() > 0) { replicaPolicy.setClusterName(clusterName); } if (groupName != null && groupName.length() > 0) { replicaPolicy.setGroupName(groupName); } } return replicaPolicy; }
Source:
public void setup() throws Exception { JmhJenkinsRule j = new JmhJenkinsRule(); webClient = j.createWebClient(); webClient.setJavaScriptEnabled(false); webClient.setThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setPrintContentOnFailingStatusCode(false); webClient.login("user33", "user33"); }

Target:
public void setup() throws Exception { JmhJenkinsRule j = new JmhJenkinsRule(); webClient = j.createWebClient(); webClient.setJavaScriptEnabled(false); webClient.setThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setPrintContentOnFailingStatusCode(false); webClient.login("mockUser", "mockUser"); }
Source:
public void removeMembership(CohortMembership cohortMembership) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.equals(cohortMembership)) .collect(Collectors.toList()); memberToRemoveList.forEach(m -> m.setEndDate(new Date())); }

Target:
public void removeMembership(CohortMembership cohortMembership) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.equals(cohortMembership) || m.getPatient().getPatientId().equals(cohortMembership.getPatient().getPatientId())) .collect(Collectors.toList()); memberToRemoveList.forEach(m -> m.setEndDate(new Date())); }
Source:
public Connection getsqlConnection() { dataSource = null; try{ if(isJndiLookup) { dataSource = (DataSource) InitialContext.doLookup("jdbc/DataSourcetoPublishHealthStatRDBMS"); } else { dataSource = (DataSource) DataSourceManager.getInstance() .getDataSourceRepository().getDataSource("DataSourcetoPublishHealthStatRDBMS") .getDSObject(); } if (dataSource != null) { connection = dataSource.getConnection(); } } catch (Exception e) { e.printStackTrace(); System.out.println("Error " + e.getMessage()); } return connection; }

Target:
public Connection getsqlConnection() throws RestAPIException { dataSource = null; try { if (isJndiLookup) { dataSource = (DataSource) InitialContext.doLookup("jdbc/DataSourcetoPublishHealthStatRDBMS"); } else { dataSource = (DataSource) DataSourceManager.getInstance() .getDataSourceRepository().getDataSource("DataSourcetoPublishHealthStatRDBMS") .getDSObject(); } if (dataSource != null) { connection = dataSource.getConnection(); } } catch (SQLException ex) { log.error("SQLException: ", ex); throw new RestAPIException(ex.getMessage(),ex); } catch (DataSourceException ex) { log.error("DataSourceException: ", ex); throw new RestAPIException(ex.getMessage(),ex); } catch (NamingException ex) { log.error("DataSourceException: ", ex); throw new RestAPIException(ex.getMessage(),ex); } return connection; }
Source:
public synchronized void loadGameVersionsFromPackageManager(GameSettings gameSettings, Path launcherDirectory, Path gameDirectory) { final Path cacheDirectory = launcherDirectory.resolve(DirectoryUtils.CACHE_DIR_NAME); packageManager.initLocalStorage(gameDirectory, cacheDirectory); packageManager.sync(); final List<TerasologyGameVersion> allInstalledGames = getInstalledGames(gameDirectory); for (GameJob job : GameJob.values()) { final List<TerasologyGameVersion> installedGames = allInstalledGames.stream() .filter(gameVersion -> gameVersion.getJob().equals(job)) .collect(Collectors.toList()); final List<Integer> installedBuildNumbers = installedGames.stream() .map(TerasologyGameVersion::getBuildNumber) .collect(Collectors.toList()); final List<TerasologyGameVersion> availableGames = packageManager.getPackageVersions(GamePackageType.byJobName(job.name())) .stream() .filter(buildNumber -> !installedBuildNumbers.contains(buildNumber)) .map(buildNumber -> getGameVersion(buildNumber, job, cacheDirectory)) .collect(Collectors.toList()); availableGames.addAll(installedGames); availableGames.sort(Comparator.comparing(TerasologyGameVersion::getBuildNumber).reversed()); availableGames.add(0, makeLatestFrom(availableGames.get(0))); gameVersionLists.put(job, availableGames); } }

Target:
public synchronized void loadGameVersionsFromPackageManager(GameSettings gameSettings, Path launcherDirectory, Path gameDirectory) { final Path cacheDirectory = launcherDirectory.resolve(DirectoryUtils.CACHE_DIR_NAME); packageManager.initLocalStorage(gameDirectory, cacheDirectory); packageManager.sync(); final List<TerasologyGameVersion> allInstalledGames = getInstalledGames(gameDirectory); for (GameJob job : GameJob.values()) { final List<TerasologyGameVersion> availableGames = packageManager.getPackageVersions(PackageBuild.byJobName(job.name())) .stream() .map(buildNumber -> getGameVersion(buildNumber, job, cacheDirectory)) .collect(Collectors.toList()); allInstalledGames.stream() .filter(gameVersion -> gameVersion.getJob().equals(job)) .forEach(installedGame -> { for (TerasologyGameVersion availableGame : availableGames) { if (availableGame.getBuildNumber().equals(installedGame.getBuildNumber())) { availableGame.setInstallationPath(installedGame.getInstallationPath()); availableGame.setGameJar(installedGame.getGameJar()); break; } } }); availableGames.sort(Comparator.comparing(TerasologyGameVersion::getBuildNumber).reversed()); availableGames.add(0, makeLatestFrom(availableGames.get(0))); gameVersionLists.put(job, availableGames); } }
Source:
private Map<TopicPartition, Long> prepareClose(final boolean clean) { final Map<TopicPartition, Long> checkpoint; switch (state()) { case CREATED: checkpoint = Collections.emptyMap(); break; case RUNNING: closeTopology(clean); if (clean) { stateMgr.flush(); recordCollector.flush(); checkpoint = checkpointableOffsets(); } else { checkpoint = null; executeAndMaybeSwallow(false, stateMgr::flush, "state manager flush", log); } break; case RESTORING: executeAndMaybeSwallow(clean, stateMgr::flush, "state manager flush", log); checkpoint = Collections.emptyMap(); break; case SUSPENDED: ENDED` do not need to checkpoint, since when suspending we've already committed the state checkpoint = null; break; case CLOSED: checkpoint = Collections.emptyMap(); break; default: throw new IllegalStateException("Unknown state " + state() + " while prepare closing active task " + id); } return checkpoint; }

Target:
private Map<TopicPartition, Long> prepareClose(final boolean clean) { final Map<TopicPartition, Long> checkpoint; switch (state()) { case CREATED: checkpoint = Collections.emptyMap(); break; case RUNNING: closeTopology(clean); if (clean) { stateMgr.flush(); recordCollector.flush(); checkpoint = checkpointableOffsets(); } else { checkpoint = null; executeAndMaybeSwallow(false, stateMgr::flush, "state manager flush", log); } break; case RESTORING: executeAndMaybeSwallow(clean, stateMgr::flush, "state manager flush", log); checkpoint = Collections.emptyMap(); break; case SUSPENDED: case CLOSED: checkpoint = null; break; default: throw new IllegalStateException("Unknown state " + state() + " while prepare closing active task " + id); } return checkpoint; }
Source:
public String getPathForHadoop() { return null; }

Target:
public String getPathForHadoop() { return String.format("gs://%s/%s", config.getBucket(), config.getPrefix()); }
Source:
private <K, V> Tuple<K, V> resolveDynamicContent(K key, V value) { final K adaptedKey; if (key instanceof String) { adaptedKey = (K) replaceDynamicContentInString((String) key); } else { adaptedKey = key; } final V adaptedValue; if (value instanceof String) { adaptedValue = (V) replaceDynamicContentInString((String) value); } else { adaptedValue = value; } return Tuple.createTuple(adaptedKey, adaptedValue); }

Target:
private <K, V> KeyValue<K, V> resolveDynamicContent(K key, V value) { final K adaptedKey = resolveDynamicContentIfRequired(key); final V adaptedValue = resolveDynamicContentIfRequired(value); return KeyValue.with(adaptedKey, adaptedValue); }
Source:
private List<TaskStatusEvent> events(final List<Long> timestamps) { final ImmutableList.Builder<TaskStatusEvent> builder = ImmutableList.builder(); final List<Long> copy = Lists.newArrayList(timestamps); copy.sort((t1, t2) -> { if (t1 > t2) { return 1; } else if (t1 < t2) { return -1; } return 0; }); for (final Long timestamp : copy) { final TaskStatus taskStatus = TaskStatus.newBuilder() .setJob(DUMMY_JOB) .setGoal(Goal.START) .setState(State.RUNNING) .build(); builder.add(new TaskStatusEvent(taskStatus, timestamp, "")); } return builder.build(); }

Target:
private List<TaskStatusEvent> events(final List<Long> timestamps) { final ImmutableList.Builder<TaskStatusEvent> builder = ImmutableList.builder(); final List<Long> copy = Lists.newArrayList(timestamps); Collections.sort(copy); for (final Long timestamp : timestamps) { final TaskStatus taskStatus = TaskStatus.newBuilder() .setJob(DUMMY_JOB) .setGoal(Goal.START) .setState(State.RUNNING) .build(); builder.add(new TaskStatusEvent(taskStatus, timestamp, "")); } return builder.build(); }