auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createDisabledImage() { <START> if (this.disabledImage != null && !this.disabledImage.isDisposed()) <END> disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }</code><technical_language>This right: building disabledImage image, need check image disabled. I following? if (this.image != null && !this.image.isDisposed()) { if (this.disabledImage != null && !this.disabledImage.isDisposed()) { this.disabledImage.dispose(); } disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }</technical_language>

Target:
private void createDisabledImage() { if (this.disabledImage == null || this.disabledImage.isDisposed()) if (this.image != null && !this.image.isDisposed()) disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }
Source:
<code><START> int wtf(String tag, String msg) { <END> if (enableLogging) return Log.wtf(tag, msg); return 0; }</code><technical_language>wtf</technical_language>

Target:
int wtf(String tag, String msg) { if (enableLogging && logLevel >= Log.ASSERT) return Log.wtf(tag, msg); return 0; }
Source:
<code>protected int run(List<String> nonFlagArgs) throws Exception { <START> if (0 == nonFlagArgs.size()) { <END> getPrintStream().printf("URI must be specified as an argument%n"); return FAILURE; } else if (nonFlagArgs.size() > 1) { getPrintStream().printf("Too many arguments: %s%n", nonFlagArgs.toString()); return FAILURE; } final KijiURI thisURI = KijiURI.newBuilder(nonFlagArgs.get(0)).build(); if (thisURI.getZookeeperQuorum() == null) { getPrintStream().printf("Specify a cluster with argument: kiji://zookeeper-quorum%n"); return FAILURE; } if (thisURI.getInstance() == null) { return listInstances(thisURI); } final Kiji kiji = Kiji.Factory.open(thisURI); try { if (thisURI.getTable() == null) { getPrintStream().println("Listing tables in kiji instance: " + thisURI); return listTables(kiji); } final KijiTable table = kiji.openTable(thisURI.getTable()); try { final KijiTableLayout tableLayout = table.getLayout(); getPrintStream().println("Listing columns in kiji table: " + thisURI); for (FamilyLayout family : tableLayout.getFamilies()) { for (ColumnLayout column : family.getColumns()) { getPrintStream().println(family.getName() + ":" + column.getName()); } } return SUCCESS; } finally { ResourceUtils.releaseOrLog(table); } } finally { ResourceUtils.releaseOrLog(kiji); } }</code><technical_language>isEmpty()</technical_language>

Target:
protected int run(List<String> nonFlagArgs) throws Exception { int status = SUCCESS; if (nonFlagArgs.isEmpty()) { getPrintStream().printf("URI was unspecified, reverting to default: %s%n", KConstants.DEFAULT_URI); return run(KijiURI.newBuilder(KConstants.DEFAULT_URI).build()); } else { for (String arg : nonFlagArgs) { status = Math.max(status, run(KijiURI.newBuilder(arg).build())); } return status; } }
Source:
<code>public void createBucketErrorInObjStore() throws Exception { ObjectStore spyObjectStore = Mockito.spy(objectStore); BDDMockito.willReturn(Optional.of(false)).given(spyObjectStore).createBucket(Mockito.any(Bucket.class)); Field objStoreField = RepoService.class.getDeclaredField("objectStore"); objStoreField.setAccessible(true); objStoreField.set(repoService, spyObjectStore); try { List<Audit> audit = null; <START> audit = sqlService.listAudit(bucket1.getBucketName(), null, null, null, null); <END> repoService.createBucket(bucket1.getBucketName(), CREATION_DATE_TIME_STRING); Assert.assertTrue(sqlService.listAudit(bucket1.getBucketName(), null, null, null, null).size() == audit.size()); Assert.fail(); } catch (RepoException e) { Assert.assertTrue(e.getType() == RepoException.Type.ServerError); Assert.assertTrue(e.getMessage().startsWith("Unable to create bucket in object store")); } sqlService.getReadOnlyConnection(); Assert.assertTrue(sqlService.getBucket(bucket1.getBucketName()) == null); sqlService.releaseConnection(); Assert.assertFalse(objectStore.bucketExists(bucket1).get()); }</code><technical_language>This moved previous line (replacing audit = null)</technical_language>

Target:
public void createBucketErrorInObjStore() throws Exception { ObjectStore spyObjectStore = Mockito.spy(objectStore); BDDMockito.willReturn(Optional.of(false)).given(spyObjectStore).createBucket(Mockito.any(Bucket.class)); Field objStoreField = RepoService.class.getDeclaredField("objectStore"); objStoreField.setAccessible(true); objStoreField.set(repoService, spyObjectStore); try { List<Audit> audit = sqlService.listAudit(bucket1.getBucketName(), null, null, null, null); repoService.createBucket(bucket1.getBucketName(), CREATION_DATE_TIME_STRING); Assert.assertTrue(sqlService.listAudit(bucket1.getBucketName(), null, null, null, null).size() == audit.size()); Assert.fail(); } catch (RepoException e) { Assert.assertTrue(e.getType() == RepoException.Type.ServerError); Assert.assertTrue(e.getMessage().startsWith("Unable to create bucket in object store")); } sqlService.getReadOnlyConnection(); Assert.assertTrue(sqlService.getBucket(bucket1.getBucketName()) == null); sqlService.releaseConnection(); Assert.assertFalse(objectStore.bucketExists(bucket1).get()); }
Source:
<code>public Base(final Request req) throws IOException { super(req); final InputStream stream = new RqLengthAware(req).body(); try { this.body = Channels.newChannel(stream); this.buffer = ByteBuffer.allocate( Math.min(8192, stream.available()) ); this.map = this.buildRequests(req); } finally { <START> if (this.body == null) { <END> stream.close(); } else { this.body.close(); } } }</code><technical_language>@xupyprmv null is anti-pattern</technical_language>

Target:
public Base(final Request req) throws IOException { super(req); final InputStream stream = new RqLengthAware(req).body(); try { this.body = Channels.newChannel(stream); try { this.buffer = ByteBuffer.allocate( Math.min(8192, stream.available()) ); this.map = this.buildRequests(req); } finally { this.body.close(); } } finally { stream.close(); } }
Source:
<code>public void suspendProcessInstanceCmdExecutorTest() { SuspendProcessInstanceCmd suspendProcessInstanceCmd = new SuspendProcessInstanceCmd("x"); <START> assertThat(suspendProcessInstanceCmdExecutor).isNotNull(); <END> assertThat(suspendProcessInstanceCmdExecutor.getHandledType()).isEqualTo(SuspendProcessInstanceCmd.class); suspendProcessInstanceCmdExecutor.execute(suspendProcessInstanceCmd); verify(processEngine).suspend(suspendProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<SuspendProcessInstanceResults>>any()); }</code><technical_language>removed</technical_language>

Target:
public void suspendProcessInstanceCmdExecutorTest() { SuspendProcessInstanceCmd suspendProcessInstanceCmd = new SuspendProcessInstanceCmd("x"); assertThat(suspendProcessInstanceCmdExecutor.getHandledType()).isEqualTo(SuspendProcessInstanceCmd.class); suspendProcessInstanceCmdExecutor.execute(suspendProcessInstanceCmd); verify(processEngine).suspend(suspendProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<SuspendProcessInstanceResults>>any()); }
Source:
<code>public void multiRestriction1() throws Exception { List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(KieServices.Factory.get().getCommands().newInsert(new Person("multi"))); commands.add(KieServices.Factory.get().getCommands().newFireAllRules()); <START> session.execute(KieServices.Factory.get().getCommands().newBatchExecution(commands, null)); <END> Assertions.assertThat(firedRules.isRuleFired("or1")).isTrue(); }</code><technical_language>Reuse code</technical_language>

Target:
public void multiRestriction1() throws Exception { List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(getCommands().newInsert(new Person("multi"))); commands.add(getCommands().newFireAllRules()); session.execute(getCommands().newBatchExecution(commands, null)); Assertions.assertThat(firedRules.isRuleFired("or1")).isTrue(); }
Source:
<code>Mono<Response<RecognizePiiEntitiesResult>> recognizePiiEntitiesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return recognizeBatchPiiEntitiesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) <START> .map(response -> { Iterator<RecognizePiiEntitiesResult> piiEntitiesResultIterator = response.getValue().iterator(); RecognizePiiEntitiesResult piiEntitiesResult = null; if (response.getStatusCode() == 200 && piiEntitiesResultIterator.hasNext()) { piiEntitiesResult = piiEntitiesResultIterator.next(); if (piiEntitiesResult.isError()) { toTextAnalyticsException(piiEntitiesResult.getError(), logger); } } return new SimpleResponse<>(response, piiEntitiesResult); }); <END> }</code><technical_language>This piece of code is repeated in of error mappers. Avoid duplication extract this out a common method</technical_language>

Target:
Mono<Response<RecognizePiiEntitiesResult>> recognizePiiEntitiesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return recognizeBatchPiiEntitiesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(Transforms::processSingleResponseErrorResult); }
Source:
<code>public void updateSubscriptionsForRepartitioning(final EventType eventType, final int partitions) throws NakadiBaseException { final List<Subscription> subscriptions = subscriptionRepository.listSubscriptions( ImmutableSet.of(eventType.getName()), Optional.empty(), 0, 1000); for (final Subscription subscription : subscriptions) { final ZkSubscriptionClient zkClient = subscriptionClientFactory.createClient(subscription, LogPathBuilder.build(subscription.getId(), "repartition")); zkClient.repartitionTopology(eventType.getName(), partitions); zkClient.closeSubscriptionStreams( <START> () -> LOG.info("subscription streams were closed, after repartitioning"), 60000); <END> } }</code><technical_language>a constant (and in line 567?)</technical_language>

Target:
public void updateSubscriptionsForRepartitioning(final EventType eventType, final int partitions) throws NakadiBaseException { final List<Subscription> subscriptions = subscriptionRepository.listSubscriptions( ImmutableSet.of(eventType.getName()), Optional.empty(), 0, repartitioningSubscriptionsLimit); for (final Subscription subscription : subscriptions) { final ZkSubscriptionClient zkClient = subscriptionClientFactory.createClient(subscription, LogPathBuilder.build(subscription.getId(), "repartition")); zkClient.repartitionTopology(eventType.getName(), partitions); zkClient.closeSubscriptionStreams( () -> LOG.info("subscription streams were closed, after repartitioning"), TimeUnit.SECONDS.toMillis(nakadiSettings.getMaxCommitTimeout())); } }
Source:
<code>DefaultUriSource(URI uri) { <START> this.uri = Preconditions.notNull(uri, "uri must not be null"); <END> }</code><technical_language>uri null -> URI null</technical_language>

Target:
DefaultUriSource(URI uri) { this.uri = Preconditions.notNull(uri, "URI must not be null"); }
Source:
<code>private void contextualizeCompressionSettings() { final RequestConfig.Builder builder = RequestConfig.copy(context.getRequestConfig()); <START> builder.setContentCompressionEnabled(allowGZip || allowDeflate); <END> context.setRequestConfig(builder.build()); }</code><technical_language>Is is case settings longer independent? If bother maintaining independent settings</technical_language>

Target:
private void contextualizeCompressionSettings() { final RequestConfig.Builder builder = RequestConfig.copy(getContext().getRequestConfig()); builder.setContentCompressionEnabled(allowCompression); context.setRequestConfig(builder.build()); }
Source:
<code>private void loadFile(File file) throws ConfigurationException { Configuration config = null; try { config = Configuration.loadFile(file); String name = config.getString(NAME); ExtensionEntry alreadyLoded = loadedEntries.get(name); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + name); } ExtensionEntry entry = <START> new ExtensionEntry(file, config.getBoolean(ENABLED, true), name, config.getString(SERVICE), config); <END> loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } }</code><technical_language>extension entry get file config, extract needs? check if loaded instead of sequence</technical_language>

Target:
private void loadFile(File file) throws ConfigurationException { Configuration config = null; try { config = Configuration.loadFile(file); ExtensionEntry entry = new ExtensionEntry(file, config); ExtensionEntry alreadyLoded = loadedEntries.get(entry.getName()); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + entry.getName()); } loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } }
Source:
<code>@Test public void checkVersion() throws Exception { HgExe hgexe = new HgExe( this.mercurialInstallation, null, this.launcher, j.jenkins, this.listener, this.vars); String version = hgexe.version(); assertNotNull(version); assertTrue(version.length() >= 3); <START> assertTrue(version.length() <= 8); END> }</code><technical_language>IIRC is for dev builds long version strings. I advise checking new VersionNumber(version).compareTo(new VersionNumber("1.0")) >= 0 is parsable</technical_language>

Target:
@Test public void checkVersion() throws Exception { HgExe hgexe = new HgExe( this.mercurialInstallation, null, this.launcher, j.jenkins, this.listener, this.vars); String version = hgexe.version(); assertNotNull(version); assertTrue(new VersionNumber(version).compareTo(new VersionNumber("1.0")) >= 0); }
Source:
<code><START> public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { <END> this.player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); this.uuid = PlayerHelper.getUUIDFromPlayer(player).toString(); this.network = NetworkHelper.getSoulNetwork(uuid); }</code><technical_language>Instead of setting calling super in command, this method final create a new abstract execution method this calls. This method handle printing</technical_language>

Target:
public final void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (!getName().equals("get")) { if (args.length == 1 && (args[0].equals("?") || args[0].equals("help"))) { sender.sendMessage(new TextComponentTranslation(getHelp())); return; } this.player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); this.uuid = PlayerHelper.getUUIDFromPlayer(player).toString(); this.network = NetworkHelper.getSoulNetwork(uuid); } subExecute(server, sender, args); }
Source:
<code>private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = DbFacade.getInstance().getVdsDynamicDao().get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: <START> log.info("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", <END> getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); break; default: if (isMaintenanceCommandExecuted(childCmdIds)) { log.info("Host '{}' failed to move to maintenance mode. Upgrade process is terminated.", getHostName(parameters.getVdsId())); rootCommand.setCommandStatus(CommandStatus.FAILED); } break; } }</code><technical_language>logged error</technical_language>

Target:
private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = DbFacade.getInstance().getVdsDynamicDao().get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: log.error("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); break; default: if (isMaintenanceCommandExecuted(childCmdIds)) { log.error("Host '{}' failed to move to maintenance mode. Upgrade process is terminated.", getHostName(parameters.getVdsId())); rootCommand.setCommandStatus(CommandStatus.FAILED); } break; } }
Source:
<code>public double getSolarRechargeTime() { if( null == spectralClass || null == subtype ) { <START> return 183; <END> } return StarUtil.getSolarRechargeTime(spectralClass, subtype); }</code><technical_language>Is a reference for this constant</technical_language>

Target:
public double getSolarRechargeTime() { if( null == spectralClass || null == subtype ) { return 176; } return StarUtil.getSolarRechargeTime(spectralClass, subtype); }
Source:
<code>protected Builder() { id("hpcloud-compute") .name("HP Cloud Compute Services") .apiMetadata(new NovaApiMetadata().toBuilder() .identityName("${tenantName}:${accessKey}") <START> .credentialName("${secret}") <END> .version("2") .endpointName("identity service url ending in /v2.0/") .defaultEndpoint("<LINK_2>") .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(MappedAuthenticationApiModule.class) .add(KeystoneAuthenticationModule.class) .add(ZoneModule.class) .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(HPCloudComputeServiceContextModule.class).build()) .build()) .homepage(URI.create("<LINK_0>")) .console(URI.create("<LINK_1>")) .linkedServices("hpcloud-compute", "hpcloud-objectstorage") .iso3166Codes("US-NV", "US-VA") .endpoint("<LINK_2>") .defaultProperties(HPCloudComputeProviderMetadata.defaultProperties()); }</code><technical_language>Is "secret" "secretKey"</technical_language>

Target:
protected Builder() { id("hpcloud-compute") .name("HP Cloud Compute Services") .apiMetadata(new NovaApiMetadata().toBuilder() .identityName("${tenantName}:${accessKey}") .credentialName("${secretKey}") .version("2") .endpointName("identity service url ending in /v2.0/") .defaultEndpoint("<LINK_2>") .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(MappedAuthenticationApiModule.class) .add(KeystoneAuthenticationModule.class) .add(ZoneModule.class) .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(HPCloudComputeServiceContextModule.class).build()) .build()) .homepage(URI.create("<LINK_0>")) .console(URI.create("<LINK_1>")) .linkedServices("hpcloud-compute", "hpcloud-objectstorage") .iso3166Codes("US-NV", "US-VA") .endpoint("<LINK_2>") .defaultProperties(HPCloudComputeProviderMetadata.defaultProperties()); }
Source:
<code>public void testAnyOrderedReading() throws Exception { ArrayDeque<Object> expectedOutput = new ArrayDeque<>(); expectedOutput.add(new StreamRecord<>("[1]: Hello-1")); expectedOutput.add(new StreamRecord<>("[2]: 1")); expectedOutput.add(new StreamRecord<>("[1]: Hello-2")); expectedOutput.add(new StreamRecord<>("[2]: 2")); expectedOutput.add(new StreamRecord<>("[1]: Hello-3")); expectedOutput.add(new StreamRecord<>("[2]: 3")); expectedOutput.add(new StreamRecord<>("[2]: 4")); <START> testBase(new TestAnyModeMultipleInputStreamOperator.Factory(), false, expectedOutput, true); <END> }</code><technical_language>easy operators doing. a generic operator, pass a InputSelectable, is defined place expected output</technical_language>

Target:
public void testAnyOrderedReading() throws Exception { ArrayDeque<Object> expectedOutput = new ArrayDeque<>(); expectedOutput.add(new StreamRecord<>("[1]: Hello-1")); expectedOutput.add(new StreamRecord<>("[2]: 1")); expectedOutput.add(new StreamRecord<>("[1]: Hello-2")); expectedOutput.add(new StreamRecord<>("[2]: 2")); expectedOutput.add(new StreamRecord<>("[1]: Hello-3")); expectedOutput.add(new StreamRecord<>("[2]: 3")); expectedOutput.add(new StreamRecord<>("[2]: 4")); testInputSelection(new TestAnyModeMultipleInputStreamOperator.Factory(), false, expectedOutput, true); }
Source:
<code>public IIrsServer getIrsProxy() { if (getmIrsProxy() == null) { final StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId); if (storagePool.getStatus() != StoragePoolStatus.Uninitialized) { String host = TransactionSupport.executeInScope(TransactionScopeOption.Suppress, new TransactionMethod<String>() { @Override public String runInTransaction() { return gethostFromVds(); } }); if (host != null) { int clientTimeOut = Config.<Integer> getValue(ConfigValues.vdsTimeout) * 1000; int connectionTimeOut = Config.<Integer> getValue(ConfigValues.vdsConnectionTimeout) * 1000; int clientRetries = Config.<Integer> getValue(ConfigValues.vdsRetries); <START> privatemIrsProxy = TransportFactory.createIrsServer(getProtocol(), host, getmIrsPort(), clientTimeOut, connectionTimeOut, clientRetries); <END> runStoragePoolUpEvent(storagePool); } } } return getmIrsProxy(); }</code><technical_language>please change name of field? private m? :)</technical_language>

Target:
public IIrsServer getIrsProxy() { if (getmIrsProxy() == null) { final StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId); if (storagePool.getStatus() != StoragePoolStatus.Uninitialized) { String host = TransactionSupport.executeInScope(TransactionScopeOption.Suppress, new TransactionMethod<String>() { @Override public String runInTransaction() { return gethostFromVds(); } }); if (host != null) { int clientTimeOut = Config.<Integer> getValue(ConfigValues.vdsTimeout) * 1000; int connectionTimeOut = Config.<Integer> getValue(ConfigValues.vdsConnectionTimeout) * 1000; int clientRetries = Config.<Integer> getValue(ConfigValues.vdsRetries); irsProxy = TransportFactory.createIrsServer(getProtocol(), host, getmIrsPort(), clientTimeOut, connectionTimeOut, clientRetries); runStoragePoolUpEvent(storagePool); } } } return getmIrsProxy(); }
Source:
<code>protected IConnectionWrapper createConnection(IServer server) { IConnection openshiftCon = OpenShiftServerUtils.getConnection(server); <START> IResource resource = OpenShiftServerUtils.getResource(server); <END> String token = ((Connection)openshiftCon).getToken(); String projName = resource.getNamespace(); List<IPod> pods = ResourceUtils.getPodsFor(resource, resource.getProject().getResources(ResourceKind.POD)); if( pods.size() == 0 ) { return null; } String pod = pods.get(0).getName(); String host = server.getHost(); String url = "https://" + host + ":8443/api/v1/namespaces/" + projName + "/pods/https:" + pod + ":8778/proxy/jolokia/"; String headerKey = "Authorization"; String headerVal = "Bearer " + token; JolokiaConnectionWrapper cw = new JolokiaConnectionWrapper() { public IConnectionProvider getProvider() { return ExtensionManager.getProvider(PROVIDER_ID); } protected void verifyServerReachable() throws IOException { super.verifyServerReachable(); } }; cw.setId(server.getName()); cw.setUrl(url); cw.setType("POST"); cw.setIgnoreSSLErrors(true); HashMap<String, String> headers = new HashMap<String, String>(); headers.put(headerKey, headerVal); cw.setHeaders(headers); return cw; }</code><technical_language>if resource == null? I a NPE line 59 a result of it</technical_language>

Target:
protected IConnectionWrapper createConnection(IServer server) { IConnection openshiftCon = OpenShiftServerUtils.getConnection(server); IResource resource = OpenShiftServerUtils.getResource(server); if (resource == null) { return null; } String token = ((Connection)openshiftCon).getToken(); String projName = resource.getNamespace(); List<IPod> pods = ResourceUtils.getPodsFor(resource, resource.getProject().getResources(ResourceKind.POD)); if( pods.size() == 0 ) { return null; } String pod = pods.get(0).getName(); String host = server.getHost(); String url = "https://" + host + ":8443/api/v1/namespaces/" + projName + "/pods/https:" + pod + ":8778/proxy/jolokia/"; String headerKey = "Authorization"; String headerVal = "Bearer " + token; JolokiaConnectionWrapper cw = new JolokiaConnectionWrapper() { public IConnectionProvider getProvider() { return ExtensionManager.getProvider(PROVIDER_ID); } protected void verifyServerReachable() throws IOException { super.verifyServerReachable(); } }; cw.setId(server.getName()); cw.setUrl(url); cw.setType("POST"); cw.setIgnoreSSLErrors(true); HashMap<String, String> headers = new HashMap<String, String>(); headers.put(headerKey, headerVal); cw.setHeaders(headers); return cw; }
Source:
<code>private Request request() { Map<String, Object> request = new ArrayMap<>(); request.put("kind", mKind.name); Map<String, Object> metadata = new ArrayMap<>(); metadata.put("sender", mSender.getId()); <START> metadata.put("date-time", formatDate( <END> new Date())); request.put("metadata", new JSONObject(metadata)); request.put("message", new JSONObject(mConstructingMap)); return new Request(new JSONObject(request)); }</code><technical_language>datetime is collapsed</technical_language>

Target:
private Request request() { Map<String, Object> request = new ArrayMap<>(); request.put("kind", mKind.name); Map<String, Object> metadata = new ArrayMap<>(); metadata.put("sender", mSender.getId()); metadata.put("datetime", formatDate( new Date())); request.put("metadata", new JSONObject(metadata)); request.put("message", new JSONObject(mConstructingMap)); return new Request(new JSONObject(request)); }
Source:
<code><START> protected void writeViaTable(TableName tableName, int rowCount) throws IOException { <END> List<Put> puts = new ArrayList<>(); for (int i = 0; i < rowCount; i++) { byte[] row = Bytes.toBytes("row_" + i); puts.add(new Put(row).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes(RandomStringUtils.randomAlphanumeric(8)))); } try (Table t = connection.getTable(tableName);) { t.put(puts); } }</code><technical_language>writeViaTable is protected checkTableRowCountViaDataflowResultReader is private? private if indented in this test class</technical_language>

Target:
private void writeViaTable(TableName tableName, int rowCount) throws IOException { List<Put> puts = new ArrayList<>(); for (int i = 0; i < rowCount; i++) { byte[] row = Bytes.toBytes("row_" + i); puts.add(new Put(row).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes(RandomStringUtils.randomAlphanumeric(8)))); } try (Table t = connection.getTable(tableName);) { t.put(puts); } }
Source:
<code><START> private final boolean acceptAsDataset(Oaf oafObj) { <END> if (oafObj.getEntity() != null && oafObj.getEntity().getResult() != null && oafObj.getEntity().getResult().getMetadata() != null && oafObj.getEntity().getResult().getMetadata().getResulttype() != null) { if (approvedDatasetResultTypes.contains(oafObj.getEntity().getResult().getMetadata().getResulttype().getClassid())) { return true; } } return false; }</code><technical_language>IDE final for private methods is needed</technical_language>

Target:
private boolean acceptAsDataset(Oaf oafObj) { return Optional.ofNullable(oafObj.getEntity()).map(OafProtos.OafEntity::getResult) .map(ResultProtos.Result::getMetadata).map(ResultProtos.Result.Metadata::getResulttype) .map(FieldTypeProtos.Qualifier::getClassid).map(classid -> approvedDatasetResultTypes.contains(classid)) .orElse(false); }
Source:
<code><START> void onErrorResponse(ReplicaId replicaId, RouterException exception) { <END> logger.info("Get exception: " + exception); operationTracker.onResponse(replicaId, TrackedRequestFinalState.fromRouterErrorCodeToFinalState(exception.getErrorCode())); setOperationException(exception); if (exception.getErrorCode() != RouterErrorCode.BlobDeleted && exception.getErrorCode() != RouterErrorCode.BlobExpired) { routerMetrics.routerRequestErrorCount.inc(); } routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).deleteRequestErrorCount.inc(); }</code><technical_language>This is method private</technical_language>

Target:
private void onErrorResponse(ReplicaId replicaId, RouterException exception) { operationTracker.onResponse(replicaId, TrackedRequestFinalState.fromRouterErrorCodeToFinalState(exception.getErrorCode())); setOperationException(exception); routerMetrics.routerRequestErrorCount.inc(); routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).deleteRequestErrorCount.inc(); }
Source:
<code>public static ImmutableMap<String, AppleToolchain> discoverAppleToolchains( Optional<Path> developerDir, ImmutableList<Path> extraDirs) throws IOException { ImmutableMap.Builder<String, AppleToolchain> toolchainIdentifiersToToolchainsBuilder = ImmutableMap.builder(); HashSet<Path> toolchainPaths = new HashSet<Path>(extraDirs); if (developerDir.isPresent()) { Path toolchainsDir = developerDir.get().resolve("Toolchains"); LOG.debug("Searching for Xcode toolchains under %s", toolchainsDir); toolchainPaths.add(toolchainsDir); } for (Path toolchains : toolchainPaths) { if (!Files.exists(toolchains)) { LOG.debug("Skipping toolchain search path %s that does not exist", toolchains); continue; } LOG.debug("Searching for Xcode toolchains in %s", toolchains); try (DirectoryStream<Path> toolchainStream = Files.newDirectoryStream(toolchains, "*.xctoolchain")) { List<Path> sortedToolchainPaths = new ArrayList<>(); toolchainStream.forEach(sortedToolchainPaths::add); <START> sortedToolchainPaths.sort(Comparator.comparing(Path::toString)); <END> for (Path toolchainPath : sortedToolchainPaths) { LOG.debug("Getting identifier for for Xcode toolchain under %s", toolchainPath); addIdentifierForToolchain(toolchainPath, toolchainIdentifiersToToolchainsBuilder); } } } return toolchainIdentifiersToToolchainsBuilder.build(); }</code><technical_language>sorting</technical_language>

Target:
public static ImmutableMap<String, AppleToolchain> discoverAppleToolchains( Optional<Path> developerDir, ImmutableList<Path> extraDirs) throws IOException { ImmutableMap.Builder<String, AppleToolchain> toolchainIdentifiersToToolchainsBuilder = ImmutableMap.builder(); HashSet<Path> toolchainPaths = new HashSet<Path>(extraDirs); if (developerDir.isPresent()) { Path toolchainsDir = developerDir.get().resolve("Toolchains"); LOG.debug("Searching for Xcode toolchains under %s", toolchainsDir); toolchainPaths.add(toolchainsDir); } for (Path toolchains : toolchainPaths) { if (!Files.exists(toolchains)) { LOG.debug("Skipping toolchain search path %s that does not exist", toolchains); continue; } LOG.debug("Searching for Xcode toolchains in %s", toolchains); try (DirectoryStream<Path> toolchainStream = Files.newDirectoryStream(toolchains, "*.xctoolchain")) { for (Path toolchainPath : ImmutableSortedSet.copyOf(toolchainStream)) { LOG.debug("Getting identifier for for Xcode toolchain under %s", toolchainPath); addIdentifierForToolchain(toolchainPath, toolchainIdentifiersToToolchainsBuilder); } } } return toolchainIdentifiersToToolchainsBuilder.build(); }
Source:
<code>public Iterable<Repo> repos( @NotNull(message = "Search keywords can't be NULL") final String keywords, @NotNull(message = "Sort field can't be NULL") final String sort, @NotNull(message = "Sort order can't be NULL") final String order) throws IOException { return new RtSearchPagination<Repo>( this.entry, "/search/repositories", keywords, sort, order, new RtPagination.Mapping<Repo>() { @Override public Repo map(final JsonObject object) { <START> return new RtRepo( <END> RtSearch.this.ghub, RtSearch.this.entry, new Coordinates.Simple(object.getString("full_name")) ); } } ); }</code><technical_language>RtSearch.this.ghub.repos().repo(new Coordinates.Simple(object.getString("full_name"))); In general, try avoid hard-coded dependencies, new calls</technical_language>

Target:
public Iterable<Repo> repos( @NotNull(message = "Search keywords can't be NULL") final String keywords, @NotNull(message = "Sort field can't be NULL") final String sort, @NotNull(message = "Sort order can't be NULL") final String order) throws IOException { return new RtSearchPagination<Repo>( this.request, "repositories", keywords, sort, order, new RtPagination.Mapping<Repo, JsonObject>() { @Override public Repo map(final JsonObject object) { return RtSearch.this.github().repos().get( new Coordinates.Simple(object.getString("full_name")) ); } } ); }
Source:
<code>protected Ref findBranch(String branchName) throws IOException { <START> return repository.exactRef(R_HEADS + branchName); <END> }</code><technical_language>unrelated change</technical_language>

Target:
protected Ref findBranch(String branchName) throws IOException { return repository.getRef(R_HEADS + branchName); }
Source:
<code><START> public void setUp() throws Exception { <END> currentContextClassLoader = Thread.currentThread().getContextClassLoader(); }</code><technical_language>omit public JUnit 5</technical_language>

Target:
static void setUp() { currentContextClassLoader = Thread.currentThread().getContextClassLoader(); }
Source:
<code>public void process(Exchange exchange) throws FrameworkProducerException { try { LOGGER.debug("Entering process method"); final Object operationValueObj = exchange.getIn().getHeader(OPERATION_HEADER_KEY); String operation; if (operationValueObj == null) { exchange.getIn().setBody(new ArrayList<Metacard>()); throw new FrameworkProducerException( String.format("Missing expected [%s] header!", OPERATION_HEADER_KEY)); } operation = operationValueObj.toString(); if (operation.trim().equalsIgnoreCase(CREATE_OPERATION)) { create(exchange); } else if (operation.trim().equalsIgnoreCase(UPDATE_OPERATION)) { update(exchange); } else if (operation.trim().equalsIgnoreCase(DELETE_OPERATION)) { delete(exchange); } else { exchange.getIn().setBody(new ArrayList<Metacard>()); LOGGER.debug( "Missing expected header \"operation:<CREATE|UPDATE|DELETE>\" but received {}", operation); } LOGGER.debug("Exiting process method"); } catch (ClassCastException cce) { exchange.getIn().setBody(new ArrayList<Metacard>()); LOGGER.debug("Received a non-String as the operation type"); } catch (SourceUnavailableException | IngestException e) { <START> exchange.getIn().setBody(new ArrayList<Metacard>()); <END> LOGGER.debug("Exception cataloging metacards", e); throw new FrameworkProducerException(e); } }</code><technical_language>delete this setBody call</technical_language>

Target:
public void process(Exchange exchange) throws FrameworkProducerException { try { LOGGER.debug("Entering process method"); final Object operationValueObj = exchange.getIn().getHeader(OPERATION_HEADER_KEY); String operation; if (operationValueObj == null) { exchange.getIn().setBody(new ArrayList<Metacard>()); throw new FrameworkProducerException( String.format("Missing expected [%s] header!", OPERATION_HEADER_KEY)); } operation = operationValueObj.toString(); if (operation.trim().equalsIgnoreCase(CREATE_OPERATION)) { create(exchange); } else if (operation.trim().equalsIgnoreCase(UPDATE_OPERATION)) { update(exchange); } else if (operation.trim().equalsIgnoreCase(DELETE_OPERATION)) { delete(exchange); } else { exchange.getIn().setBody(new ArrayList<Metacard>()); LOGGER.debug( "Missing expected header \"operation:<CREATE|UPDATE|DELETE>\" but received {}", operation); } LOGGER.debug("Exiting process method"); } catch (ClassCastException cce) { exchange.getIn().setBody(new ArrayList<Metacard>()); LOGGER.debug("Received a non-String as the operation type"); } catch (SourceUnavailableException | IngestException e) { LOGGER.debug("Exception cataloging metacards", e); throw new FrameworkProducerException(e); } }
Source:
<code>public void startGame(boolean isHost,String ipAddress) { <START> game = new SevenWondersGame(new Router(isHost)); <END> }</code><technical_language>Router creates SevenWondersGame now. do: (new Router(isHost)).getLocalGame();</technical_language>

Target:
public void startGame(boolean isHost,String ipAddress) { game = (new Router(isHost)).getLocalGame(); }
Source:
<code>protected boolean postFileToImpl(String fileName, String serviceUrl) { boolean result; resetResponse(); String url = getUrl(serviceUrl); String fitnesseFilesDir; String filePath; try { fitnesseFilesDir = getEnvironment().getFitNesseFilesSectionDir(); filePath = String.format("%s/%s", fitnesseFilesDir, fileName); File file = new File(filePath); <START> if(!isFile(file)) { <END> filePath = getFilePathFromWikiUrl(fileName); file = new File(filePath); } if(!isFile(file)) { throw new Exception("File " + fileName + " not found."); } getEnvironment().doHttpFilePost(url, response, headerValues, file); } catch (Throwable t) { throw new StopTestException("Unable to get response from POST to: " + url, t); } result = postProcessResponse(); return result; }</code><technical_language>I consistent paths upload files handled BrowserTest: if file is located in files directory path beging 'files/', expect a full path. means this method, start in files section. I.e. remove 4 lines above</technical_language>

Target:
protected boolean postFileToImpl(String fileName, String serviceUrl) { boolean result; resetResponse(); String url = getUrl(serviceUrl); try { String filePath = getFilePathFromWikiUrl(fileName); File file = new File(filePath); if(!isFile(file)) { throw new Exception("File " + fileName + " not found."); } getEnvironment().doHttpFilePost(url, response, headerValues, file); } catch (Throwable t) { throw new StopTestException("Unable to get response from POST to: " + url, t); } result = postProcessResponse(); return result; }
Source:
<code>public static void retrieveThumbnail(final IndexedFile item, final IOnResult<Boolean> callback) { if (item.getThumbnail() != null) { callback.onResult(true); return; } final File thumbFile = item.getThumbFile(); if (!thumbFile.exists()) { callback.onResult(false); return; } <START> new Thread(new Runnable() { <END> @Override public void run() { try { File thumbFile = item.getThumbFile(); File cache = Utils.getRandomCacheFile(); Utils.getMainCrypto().decrypt(thumbFile, cache, item.getName()); Bitmap bm = BitmapFactory.decodeFile(cache.getPath()); Utils.delete(cache); item.seThumbnail(bm); if (callback != null) { callback.onResult(true); } } catch (Exception e) { Utils.d("Failed to read thumbnail of item '" + item.getName() + "'. " + e.getMessage()); e.printStackTrace(); if (callback != null) { callback.onResult(false); } } } }).start(); }</code><technical_language>I AsyncTask this clearer</technical_language>

Target:
public static void retrieveThumbnail(final IndexedFile item, final IOnResult<Boolean> callback) { if (item.getThumbnail() != null) { callback.onResult(true); return; } if (mRetrievingThumbs.contains(item)) { callback.onResult(false); return; } final File thumbFile = item.getThumbFile(); if (!thumbFile.exists()) { callback.onResult(false); return; } mRetrievingThumbs.add(item); new Thread(new Runnable() { @Override public void run() { boolean result = false; while (mCreatingThumbs.contains(item)) { try { Thread.sleep(100); } catch (InterruptedException e) { } } try { File thumbFile = item.getThumbFile(); File cache = Utils.getRandomCacheFile(); Utils.getMainCrypto().decrypt(thumbFile, cache, item.getName()); Bitmap bm = BitmapFactory.decodeFile(cache.getPath()); Utils.delete(cache); item.setThumbnail(bm); result = true; } catch (Exception e) { Utils.d("Failed to read thumbnail of item '" + item.getName() + "'. " + e.getMessage()); e.printStackTrace(); } mRetrievingThumbs.remove(item); Utils.runCallbackOnMain(callback, result); } }).start(); }
Source:
<code>public static Job createWorkingBranch_Create(final TeamWorkFlowArtifact teamArt, final TransactionRecord parentTransactionId, boolean pend) throws OseeCoreException { final String branchName = Strings.truncate(TeamWorkFlowManager.getBranchName(teamArt), 195, true); Conditions.checkNotNull(teamArt, "Parent Team Workflow"); Conditions.checkNotNull(parentTransactionId, "Parent Branch"); IExceptionableRunnable runnable = new IExceptionableRunnable() { @Override public IStatus run(IProgressMonitor monitor) throws OseeCoreException { teamArt.setWorkingBranchCreationInProgress(true); BranchManager.createWorkingBranch(parentTransactionId, branchName, null, teamArt); teamArt.setWorkingBranchCreationInProgress(false); SkynetTransaction transaction = TransactionManager.createTransaction(AtsUtilCore.getAtsBranch(), "Create Reviews upon Transition"); createNecessaryBranchEventReviews(StateEventType.CreateBranch, teamArt, new Date(), AtsUsers.getSystemUser(), transaction); transaction.execute(); for (IAtsStateItemCore item : AtsStateItemCoreManager.getStateItems()) { item.workingBranchCreated(teamArt); } <START> return Status.OK_STATUS; <END> } }; Job job = Jobs.startJob(new CatchAndReleaseJob("Create Branch", runnable, Activator.class, Activator.PLUGIN_ID), true); if (pend) { try { job.join(); } catch (InterruptedException ex) { throw new OseeWrappedException(ex); } } return job; }</code><technical_language>some code duplication here..</technical_language>

Target:
public static Job createWorkingBranch_Create(final TeamWorkFlowArtifact teamArt, final TransactionRecord parentTransactionId, boolean pend) throws OseeCoreException { final String branchName = Strings.truncate(TeamWorkFlowManager.getBranchName(teamArt), 195, true); Conditions.checkNotNull(teamArt, "Parent Team Workflow"); Conditions.checkNotNull(parentTransactionId, "Parent Branch"); IExceptionableRunnable runnable = new IExceptionableRunnable() { @Override public IStatus run(IProgressMonitor monitor) throws OseeCoreException { teamArt.setWorkingBranchCreationInProgress(true); BranchManager.createWorkingBranch(parentTransactionId, branchName, null, teamArt); teamArt.setWorkingBranchCreationInProgress(false); performPostBranchCreationTasks(teamArt); return Status.OK_STATUS; } }; Job job = Jobs.startJob(new CatchAndReleaseJob("Create Branch", runnable, Activator.class, Activator.PLUGIN_ID), true); if (pend) { try { job.join(); } catch (InterruptedException ex) { throw new OseeWrappedException(ex); } } return job; }
Source:
<code>private boolean isTxnRelatedEvent(final NotificationEvent event) { return ((event.getEventType().equals(MessageFactory.OPEN_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.COMMIT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ABORT_TXN_EVENT)) || <START> (event.getEventType().equals(MessageFactory.ALLOC_WRITE_ID_EVENT)) <END> ); }</code><technical_language>Allocate write ID is a DB/table related event if lookup this DB/table</technical_language>

Target:
private boolean isTxnRelatedEvent(final NotificationEvent event) { return ((event.getEventType().equals(MessageFactory.OPEN_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.COMMIT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ABORT_TXN_EVENT))); }
Source:
<code>public void isNotAGitRepoTest() throws Exception { Path myTmpDir = Files.createTempDirectory(testTmpFolder, "NotARepo", new FileAttribute<?>[] {}); context.addArg(getCommandName()); setCmdLocation(myTmpDir.toString()); <START> Object result = app.start(context); <END> assertOutputs("fatal: Can't find git repository\n", ""); assertEquals(ReturnCode.ERROR, result); }</code><technical_language>System.getProperty instead of "\n"</technical_language>

Target:
public void isNotAGitRepoTest() throws Exception { Path myTmpDir = Files.createTempDirectory(testTmpFolder, "NotARepo", new FileAttribute<?>[] {}); context.addArg(getCommandName()); setCmdLocation(myTmpDir.toString()); Object result = app.start(context); assertOutputs("fatal: Can't find git repository" + EOL, ""); assertEquals(ReturnCode.ERROR, result); }
Source:
<code>Task<Void> linkWithAsync( String authType, Map<String, String> authData) { <START> return linkWithAsync(authType, authData, getSessionToken()); <END> }</code><technical_language>enforce authType authData non-nil</technical_language>

Target:
Task<Void> linkWithAsync( String authType, Map<String, String> authData) { if (authType == null) { throw new IllegalArgumentException("Invalid authType: " + null); } return linkWithAsync(authType, authData, getSessionToken()); }
Source:
<code>public void interrupt() { final boolean differentThread = Thread.currentThread() != this; if (differentThread) checkAccess(); if (isInterrupted()) return; final AtomicInteger stateRef = this.stateRef; int oldVal, newVal; for (;;) { oldVal = stateRef.get(); if (oldVal == STATE_INTERRUPT_PENDING) { Messages.msg.tracef("Interrupting thread \"%s\" (already interrupted)", this); return; } else if (oldVal == STATE_INTERRUPT_IN_PROGRESS) { JDKSpecific.onSpinWait(); continue; } else { if (oldVal == STATE_INTERRUPT_DEFERRED) { newVal = STATE_INTERRUPT_PENDING; } else { newVal = STATE_INTERRUPT_IN_PROGRESS; } } if (stateRef.compareAndSet(oldVal, newVal)) { break; } } if (newVal == STATE_INTERRUPT_IN_PROGRESS) try { <START> doInterrupt(); <END> } finally { stateRef.set(STATE_MAYBE_INTERRUPTED); if (differentThread) { LockSupport.unpark(this); } } else { Messages.intMsg.tracef("Interrupting thread \"%s\" (deferred)", this); } }</code><technical_language>@dmlloyd JDK 8 core? endless loop</technical_language>

Target:
public void interrupt() { final boolean differentThread = Thread.currentThread() != this; if (differentThread) checkAccess(); if (isInterrupted()) return; final AtomicInteger stateRef = this.stateRef; int oldVal, newVal; int spins = 0; for (;;) { oldVal = stateRef.get(); if (oldVal == STATE_INTERRUPT_PENDING) { Messages.msg.tracef("Interrupting thread \"%s\" (already interrupted)", this); return; } else if (oldVal == STATE_INTERRUPT_IN_PROGRESS) { if (spins < MAX_INTERRUPT_SPINS) { JDKSpecific.onSpinWait(); spins++; } else { Thread.yield(); } continue; } else { if (oldVal == STATE_INTERRUPT_DEFERRED) { newVal = STATE_INTERRUPT_PENDING; } else { newVal = STATE_INTERRUPT_IN_PROGRESS; } } if (stateRef.compareAndSet(oldVal, newVal)) { break; } } if (newVal == STATE_INTERRUPT_IN_PROGRESS) try { doInterrupt(); } finally { stateRef.set(STATE_MAYBE_INTERRUPTED); if (differentThread) { LockSupport.unpark(this); } } else { Messages.intMsg.tracef("Interrupting thread \"%s\" (deferred)", this); } }
Source:
<code>public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails) { <START> this(metaDataStore, defaultConnectionDetails, null); <END> }</code><technical_language>empty map instead of null</technical_language>

Target:
public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails) { this(metaDataStore, defaultConnectionDetails, Collections.emptyMap()); }