auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isTattleTaleReportGenerationEnabled(GraphRewrite event) { <START> Boolean enableReport = (Boolean) event.getGraphContext().getOptionMap().get(EnableTattletaleReportOption.NAME); <END> Boolean disableReport = (Boolean) event.getGraphContext().getOptionMap().get(DisableTattletaleReportOption.NAME); Collection<String> targets = (Collection<String>) event.getGraphContext().getOptionMap().get(TargetOption.NAME); boolean eapTarget = targets != null && targets.stream().anyMatch(target -> target.startsWith("eap")); if (eapTarget && BooleanUtils.isTrue(disableReport) && BooleanUtils.isNotTrue(enableReport)) return false; else if (!eapTarget && BooleanUtils.isNotTrue(enableReport)) return false; return true; }</code><technical_language>convert this : boolean enableReport = (boolean) event.getGraphContext().getOptionMap().getOrDefault(EnableTattletaleReportOption.NAME, Boolean.FALSE); this avoid BooleanUtils clearer.... do</technical_language>

Target:
private boolean isTattleTaleReportGenerationEnabled(GraphRewrite event) { Boolean enableReport = (Boolean) event.getGraphContext().getOptionMap().getOrDefault(EnableTattletaleReportOption.NAME, Boolean.FALSE); Boolean disableReport = (Boolean) event.getGraphContext().getOptionMap().getOrDefault(DisableTattletaleReportOption.NAME, Boolean.FALSE); Collection<String> targets = (Collection<String>) event.getGraphContext().getOptionMap().getOrDefault(TargetOption.NAME, Collections.EMPTY_SET); boolean eapTarget = targets.stream().anyMatch(target -> target.startsWith("eap")); if (eapTarget && disableReport && !enableReport) return false; else if (!eapTarget && !enableReport) return false; return true; }
Source:
<code>protected void convertTable(Table table) { String tableKindId = table.getTableKindId(); if (tableKindId != null) { ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance(); RepresentationKind kind = <START> (PapyrusDiagram) manager.getRepresentationKindById(tableKindId); <END> if (UMLArchitectureContextIds.UML.equals(kind.getLanguage().getId())) return; } table.setTableKindId(UMLTableKinds.GENERIC_TABLE); }</code><technical_language>useless cast</technical_language>

Target:
protected void convertTable(Table table) { String tableKindId = table.getTableKindId(); if (tableKindId != null) { ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance(); RepresentationKind kind = manager.getRepresentationKindById(tableKindId); if (kind != null && UMLArchitectureContextIds.UML.equals(kind.getLanguage().getId())) return; } table.setTableKindId(UMLTableKinds.GENERIC_TABLE); }
Source:
<code><START> public XDocResourceKey(Project.NameKey <END> project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }</code><technical_language>this is needed</technical_language>

Target:
XDocResourceKey(Project.NameKey project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }
Source:
<code>private Object extractValue(Object object, Schema schema) { Schema.Type fieldType = schema.getType(); <START> switch (fieldType) { <END> case ARRAY: return convertArray(object, schema.getComponentSchema()); case BYTES: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: return object; case NULL: return null; default: throw new UnexpectedFormatException("field type " + fieldType + " is not supported."); } }</code><technical_language>happened handling of nullables</technical_language>

Target:
private Object extractValue(Object object, Schema schema) { if (schema.isNullable()) { if (object == null) { return null; } schema = schema.getNonNullable(); } Schema.Type fieldType = schema.getType(); switch (fieldType) { case ARRAY: return convertArray(object, schema.getComponentSchema()); case BYTES: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: return object; case NULL: return null; default: throw new UnexpectedFormatException("field type " + fieldType + " is not supported."); } }
Source:
<code>public Iterator<Entry<KeyType>> iterator(final boolean sorted) { final List<Iterator<Entry<KeyType>>> iterators = new ArrayList<>(groupers.size()); for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { iterators.add(grouper.iterator(sorted)); } } return Groupers.mergeIterators(iterators, sorted); <START> } <END></code><technical_language>this iterator(true) returns.. aggregate(key) is called.... is iterator returns unsorted result? (however, a problem iterator is generally called updates done)</technical_language>

Target:
public Iterator<Entry<KeyType>> iterator(final boolean sorted) { if (closed) { throw new ISE("Grouper is closed"); } final List<Iterator<Entry<KeyType>>> iterators = new ArrayList<>(groupers.size()); for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { iterators.add(grouper.iterator(sorted)); } } return Groupers.mergeIterators(iterators, sorted); }
Source:
<code>public final void run() { while(running){ while (isDataAvaid()) { final int[] data = nrfGetOneDataPacket(); executorService.execute(new Runnable() { public void run() { listener.dataRecived(data); } }); } try { DataPackage pkg = fifo.poll(25, TimeUnit.MILLISECONDS); if(pkg==null) continue; int retry = nrfSendData(pkg.chanel, pkg.power, pkg.maxRetry, pkg.addrWidth, pkg.txAddr, pkg.dataWidth, pkg.txData); pkg.sentTimestamp=System.currentTimeMillis(); pkg.retry = retry; setRxMode(this.localRFChanel, 5, this.localRFAddress); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } }</code><technical_language>if this fails... "running" updated false</technical_language>

Target:
public final void run() { while(running){ while (isDataAvaid()) { final int[] data = nrfGetOneDataPacket(); executorService.execute(new Runnable() { public void run() { listener.dataReceived(data); } }); } try { DataPackage pkg = fifo.poll(25, TimeUnit.MILLISECONDS); if(pkg==null) continue; int retry = nrfSendData(pkg.chanel, pkg.power, pkg.maxRetry, pkg.addrWidth, pkg.txAddr, pkg.dataWidth, pkg.txData); pkg.sentTimestamp=System.currentTimeMillis(); pkg.retry = retry; } catch (InterruptedException e) { e.printStackTrace(); } finally{ setRxMode(this.localRFChanel, 5, this.localRFAddress); } } }
Source:
<code>default TimestampedLockResponse acquireLocksForWrites(LockRequest lockRequest) { <START> return TimestampedLockResponse.of(getFreshTimestamp(), lock(lockRequest)); <END> }</code><technical_language>This is 1.5 RPCs, is more normal path</technical_language>

Target:
default TimestampedLockResponse acquireLocksForWrites(LockRequest lockRequest) { return TimestampedLockResponse.of(null, lock(lockRequest)); }
Source:
<code>public CompletableFuture<Void> addEvent(final Event event) { return CompletableFuture.runAsync(new Runnable() { @Override public void run() { try { <START> LOG.debug("run: calling onEvent on for event {}", m_listener.getName(), event.toStringSimple()); <END> Map<String,String> mdc = Logging.getCopyOfContextMap(); try { m_listener.onEvent(event); } finally { Logging.setContextMap(mdc); } } catch (Throwable t) { LOG.warn("run: an unexpected error occured during ListenerThread {}", m_listener.getName(), t); } } }, m_delegateThread); }</code><technical_language>This statement wrapped in a if (LOG.isDebugEnabled()) { } block avoid calling Event#toStringSimple() unnecessarily</technical_language>

Target:
public CompletableFuture<Void> addEvent(final Event event) { return CompletableFuture.runAsync(new Runnable() { @Override public void run() { try { if (LOG.isDebugEnabled()) LOG.debug("run: calling onEvent on for event {}", m_listener.getName(), event.toStringSimple()); Map<String,String> mdc = Logging.getCopyOfContextMap(); try { m_listener.onEvent(event); } finally { Logging.setContextMap(mdc); } } catch (Throwable t) { LOG.warn("run: an unexpected error occured during ListenerThread {}", m_listener.getName(), t); } } }, m_delegateThread); }
Source:
<code>public static Optional<Unit> getUnit(String cssSize) { if (cssSize == null) { throw new IllegalArgumentException("The parameter can't be null"); } <START> Stream<Unit> units = getUnits().filter(unit -> cssSize.endsWith(unit.toString())); return units.findFirst(); <END> }</code><technical_language>suggestion return getUnits().filter(unit -> cssSize.endsWith(unit.toString())).findFirst();</technical_language>

Target:
public static Optional<Unit> getUnit(String cssSize) { if (cssSize == null) { throw new IllegalArgumentException("The parameter can't be null"); } return getUnits().filter(unit -> cssSize.endsWith(unit.toString())).findFirst(); }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } VDSGroup cluster = getVdsGroup(); <START> if (cluster == null) { <END> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (!cluster.supportsGlusterService()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_DOES_NOT_SUPPORT_GLUSTER); return false; } if (!GlusterFeatureSupported.glusterSnapshot(cluster.getcompatibility_version())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); return false; } GlusterVolumeEntity volume = getGlusterVolume(); if (volume == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID); } else if (volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } if (getDbFacade().getGlusterVolumeSnapshotDao().getByName(getGlusterVolumeId(), snapshot.getSnapshotName()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_SNAPSHOT_ALREADY_EXISTS); } return true; }</code><technical_language>required get here. failed in super class</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } VDSGroup cluster = getVdsGroup(); if (!GlusterFeatureSupported.glusterSnapshot(cluster.getcompatibility_version())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); return false; } GlusterVolumeEntity volume = getGlusterVolume(); if (volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } if (getDbFacade().getGlusterVolumeSnapshotDao().getByName(getGlusterVolumeId(), snapshot.getSnapshotName()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_SNAPSHOT_ALREADY_EXISTS); } return true; }
Source:
<code>public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderAsObservable() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final TestSubscriber<DeleteResults<TestItem>> testSubscriber = new TestSubscriber<DeleteResults<TestItem>>(); storIOContentResolver .delete() .objects(items) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); <START> testSubscriber.assertError(StorIOException.class); <END> verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }</code><technical_language>Please add assertion for exception type message, expected exception</technical_language>

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderAsObservable() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final TestSubscriber<DeleteResults<TestItem>> testSubscriber = new TestSubscriber<DeleteResults<TestItem>>(); storIOContentResolver .delete() .objects(items) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); TestUtils.checkException(testSubscriber, StorIOException.class, IllegalStateException.class); verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }
Source:
<code>public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { <START> nanosecond = 0; <END> } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond ); }</code><technical_language>if condition be: if ( !isNanosecondPrecisionSupported() )</technical_language>

Target:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond ); }
Source:
<code>@Override public <T> IgniteInternalFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync( Map<? extends K, ? extends EntryProcessor<K, V, T>> map, Object... args) { A.notNull(map, "map"); if (keyCheck) validateCacheKeys(map.keySet()); <START> checkKeysOrdered(map, "Invoke All"); <END> final boolean statsEnabled = ctx.statisticsEnabled(); final long start = statsEnabled ? System.nanoTime() : 0L; IgniteInternalFuture fut = updateAllAsync0(null, map, args, true, false, null); if (statsEnabled) fut.listen(new InvokeAllTimeStatClosure(metrics0(), start)); return fut; }</code><technical_language>"Invoke Sync" operation</technical_language>

Target:
@Override public <T> IgniteInternalFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync( Map<? extends K, ? extends EntryProcessor<K, V, T>> map, Object... args) { A.notNull(map, "map"); if (keyCheck) validateCacheKeys(map.keySet()); warnIfUnordered(map, BulkOperation.INVOKE); final boolean statsEnabled = ctx.statisticsEnabled(); final long start = statsEnabled ? System.nanoTime() : 0L; IgniteInternalFuture fut = updateAllAsync0(null, map, args, true, false, null); if (statsEnabled) fut.listen(new InvokeAllTimeStatClosure(metrics0(), start)); return fut; }
Source:
<code>public boolean isApplicable(@NotNull PsiElement[] elements) { if (!super.isApplicable(elements) || elements.length == 0) return false; GoType type = ((GoExpression)elements[0]).getGoType(null); <START> return type != null && type.textMatches("bool"); END> }</code><technical_language>extract GoTypeUtil#isBoolean</technical_language>

Target:
public boolean isApplicable(@NotNull PsiElement[] elements) { if (!super.isApplicable(elements)) return false; return GoTypeUtil.isBuiltinType(getExpression(elements).getGoType(null), "bool"); }
Source:
<code>private void saveMaps() throws IOException { for (Map.Entry<String, Tuple> entry : knownHolders.entrySet()) { File outFile = new File(dataDirectory, createFileName(entry)); <START> try (FileOutputStream fos = new FileOutputStream(outFile)) { <END> try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(entry.getKey()); oos.writeObject(entry.getValue()); } } } }</code><technical_language>Collapse</technical_language>

Target:
private void saveMaps() throws IOException { for (Map.Entry<String, Tuple> entry : knownHolders.entrySet()) { File outFile = new File(dataDirectory, createFileName(entry)); try (FileOutputStream fos = new FileOutputStream(outFile); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(entry.getKey()); oos.writeObject(entry.getValue()); } } }
Source:
<code>public void transform(StructuredRecord input, Emitter<KeyValue<byte[], byte[]>> emitter) throws Exception { Object key = input.get(kvTableConfig.keyField); Preconditions.checkArgument(key != null, "Key cannot be null."); <START> byte[] keyBytes = key instanceof String ? Bytes.toBytes((String) key) : (byte[]) key; <END> Object val = input.get(kvTableConfig.valueField); byte[] valBytes = val instanceof String ? Bytes.toBytes((String) val) : (byte[]) val; emitter.emit(new KeyValue<>(keyBytes, valBytes)); }</code><technical_language>get rid of ByteBuffer logic. previous logic applied if schema field's type is bytes. If schema field's type is string, cast a String do Bytes.toBytes() it</technical_language>

Target:
public void transform(StructuredRecord input, Emitter<KeyValue<byte[], byte[]>> emitter) throws Exception { Object key = input.get(kvTableConfig.keyField); Preconditions.checkArgument(key != null, "Key cannot be null."); byte[] keyBytes; Schema keyFieldSchema = input.getSchema().getField(kvTableConfig.keyField).getSchema(); if (keyFieldSchema.getType().equals(Schema.Type.STRING)) { keyBytes = Bytes.toBytes((String) key); } else if (keyFieldSchema.getType().equals(Schema.Type.BYTES)) { keyBytes = key instanceof ByteBuffer ? Bytes.toBytes((ByteBuffer) key) : (byte[]) key; } else if (keyFieldSchema.isNullable()) { throw new Exception( String.format("Key field %s cannot have nullable schema %s", kvTableConfig.keyField, keyFieldSchema)); } else { throw new Exception( String.format("Key field %s cannot have schema %s. It must of either String or Bytes", kvTableConfig.keyField, keyFieldSchema)); } Schema.Field valueFieldSchema = input.getSchema().getField(kvTableConfig.valueField); if (valueFieldSchema == null) { throw new Exception("Value Field " + kvTableConfig.valueField + " is missing in the input record"); } byte[] valBytes = null; Object val = input.get(kvTableConfig.valueField); if (val != null) { Schema.Type valueFieldType = valueFieldSchema.getSchema().isNullable() ? valueFieldSchema.getSchema().getNonNullable().getType() : valueFieldSchema.getSchema().getType(); if (valueFieldType.equals(Schema.Type.STRING)) { valBytes = Bytes.toBytes((String) val); } else if (valueFieldType.equals(Schema.Type.BYTES)) { valBytes = val instanceof ByteBuffer ? Bytes.toBytes((ByteBuffer) val) : (byte[]) val; } else { throw new Exception( String.format("Value field %s cannot have schema %s. It must of either String or Bytes", kvTableConfig.valueField, valueFieldSchema)); } } emitter.emit(new KeyValue<>(keyBytes, valBytes)); }
Source:
<code>public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { <START> log.unableToLoadDriver("org.apache.cassandra.cql.jdbc.CassandraDriver") ; <END> } }</code><technical_language>this thrown, generates exception</technical_language>

Target:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { throw log.unableToLoadDriver( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } }
Source:
<code>public int run(String[] args) throws Exception { if (args.length != 3) { log.error("Usage: " + this.getClass().getSimpleName() + "<nodeSize> <fluoProps> <input dir>"); System.exit(-1); } int nodeSize = Integer.parseInt(args[0]); FluoConfiguration props = new FluoConfiguration(new File(args[1])); Path input = new Path(args[2]); Job job = Job.getInstance(getConf()); job.setJarByClass(Load.class); job.getConfiguration().setInt(TRIE_NODE_SIZE_PROP, nodeSize); job.setInputFormatClass(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(job, input); job.setMapperClass(LoadMapper.class); job.setNumReduceTasks(0); job.setOutputFormatClass(FluoOutputFormat.class); FluoOutputFormat.configure(job, ConfigurationConverter.getProperties(props)); <START> job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", false); <END> boolean success = job.waitForCompletion(true); return success ? 0 : 1; }</code><technical_language>want newer equivalent mapreduce.map.speculative</technical_language>

Target:
public int run(String[] args) throws Exception { if (args.length != 3) { log.error("Usage: " + this.getClass().getSimpleName() + "<nodeSize> <fluoProps> <input dir>"); System.exit(-1); } int nodeSize = Integer.parseInt(args[0]); FluoConfiguration props = new FluoConfiguration(new File(args[1])); Path input = new Path(args[2]); Job job = Job.getInstance(getConf()); job.setJarByClass(Load.class); job.getConfiguration().setInt(TRIE_NODE_SIZE_PROP, nodeSize); job.setInputFormatClass(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(job, input); job.setMapperClass(LoadMapper.class); job.setNumReduceTasks(0); job.setOutputFormatClass(FluoOutputFormat.class); FluoOutputFormat.configure(job, ConfigurationConverter.getProperties(props)); job.getConfiguration().setBoolean("mapreduce.map.speculative", false); boolean success = job.waitForCompletion(true); return success ? 0 : 1; }
Source:
<code>public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { <START> return new ThriftConnectorIndex(client, sessionProperties.createHeaderFromSession(session), stats, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); <END> }</code><technical_language>This is long, wrap wrap arguments</technical_language>

Target:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { return new ThriftConnectorIndex( client, sessionProperties.toHeader(session), stats, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }
Source:
<code>public void shouldSuccessfullySendACaptureRequest() { PaymentProvider paymentProvider = getSmartpayPaymentProvider(); CardAuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertTrue(response.isSuccessful()); assertThat(response.getBaseResponse().isPresent(), is(true)); SmartpayAuthorisationResponse smartpayAuthorisationResponse = (SmartpayAuthorisationResponse) response.getBaseResponse().get(); String transactionId = smartpayAuthorisationResponse.getPspReference(); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); CaptureResponse captureGatewayResponse = paymentProvider.capture(CaptureGatewayRequest.valueOf(chargeEntity)); <START> assertTrue(captureGatewayResponse.isSuccessful()); <END> }</code><technical_language>Extra asserts</technical_language>

Target:
public void shouldSuccessfullySendACaptureRequest() { PaymentProvider paymentProvider = getSmartpayPaymentProvider(); CardAuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertTrue(response.isSuccessful()); assertThat(response.getBaseResponse().isPresent(), is(true)); SmartpayAuthorisationResponse smartpayAuthorisationResponse = (SmartpayAuthorisationResponse) response.getBaseResponse().get(); String transactionId = smartpayAuthorisationResponse.getPspReference(); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); CaptureResponse captureGatewayResponse = paymentProvider.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertTrue(captureGatewayResponse.isSuccessful()); MatcherAssert.assertThat(captureGatewayResponse.state(), Is.is(CaptureResponse.ChargeState.PENDING)); }
Source:
<code>private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> newContainers = new ArrayList<>(); final List<Container> nativeContainers = new ArrayList<>(); try { synchronized (clientLock) { if (client == null) { return newContainers; } nativeContainers.addAll(client.listContainers( DockerClient.ListContainersParam.allContainers())); } <START> for (Container nativeContainer : nativeContainers) { <END> if (nativeContainer.status() .startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(nativeContainer.id())) { loggingThreads.get(nativeContainer.id()).requestStop(); loggingThreads.remove(nativeContainer.id()); } } newContainers.add(new DockerContainer(this, nativeContainer)); } } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind(Messages.List_Docker_Containers_Failure, this.getName()), e); } finally { synchronized (containerLock) { this.containers = newContainers; this.containersLoaded = true; } } notifyContainerListeners(this.containers); return containers; }</code><technical_language>code needs locked modifying loggingThreads list. potential for disaster removes a loggingThread another access thread afterwards</technical_language>

Target:
private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> updatedContainers = new ArrayList<>(); final List<Container> rawContainers = new ArrayList<>(); try { synchronized (clientLock) { if (client == null) { return updatedContainers; } rawContainers.addAll(client.listContainers( DockerClient.ListContainersParam.allContainers())); } for (Container nativeContainer : rawContainers) { if (nativeContainer.status() .startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(nativeContainer.id())) { loggingThreads.get(nativeContainer.id()).requestStop(); loggingThreads.remove(nativeContainer.id()); } } if (!nativeContainer.status() .equals(Messages.Removal_In_Progress_specifier)) { updatedContainers .add(new DockerContainer(this, nativeContainer)); } } } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind(Messages.List_Docker_Containers_Failure, this.getName()), e); } finally { synchronized (containerLock) { this.containers = updatedContainers; this.containersLoaded = true; } } notifyContainerListeners(this.containers); return containers; }
Source:
<code>public void resetProfile() { this.profile = new Profile(); <START> this.profile.setBirthday(LocalDate.parse("2000-01-01")); <END> }</code><technical_language>This automatically older 18 resetting profile</technical_language>

Target:
public void resetProfile() { this.profile = new Profile(); this.profile.setBirthday(LocalDate.now()); }
Source:
<code>public void tearDown() { try { Case.closeCurrentCase(); try { Thread.sleep(2000); } catch (InterruptedException ex) { } <START> FileUtils.deleteDirectory(CASE_DIR); <END> } catch (CaseActionException | IOException ex) { Exceptions.printStackTrace(ex); } assertFalse(CASE_DIR.exists()); }</code><technical_language>This delete frequently fails (it worked a times is failing consistantly for me) delete case dir in User\AppData\Local\Temp causing test fail</technical_language>

Target:
public void tearDown() { try { Case.closeCurrentCase(); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); } }
Source:
<code>public void aggregate() { long time = timeSelector.getLong(); if (time < firstTime) { firstTime = time; Object value = valueSelector.getObject(); if (value instanceof String) { firstValue = (String) value; } else if (value instanceof SerializablePairLongString) { firstValue = ((SerializablePairLongString) value).rhs; } else if (value != null) { throw new IllegalStateException( "Try to aggregate unsuported class type [" <START> + value.getClass().getName() + <END> "]. Supported class types: String or SerializablePairLongString" ); } if (firstValue != null && firstValue.length() > maxStringBytes) { firstValue = firstValue.substring(0, maxStringBytes); } } }</code><technical_language>getCanonicalName() instead</technical_language>

Target:
public void aggregate() { long time = timeSelector.getLong(); if (time < firstTime) { firstTime = time; Object value = valueSelector.getObject(); if (value != null) { if (value instanceof String) { firstValue = (String) value; } else if (value instanceof SerializablePairLongString) { firstValue = ((SerializablePairLongString) value).rhs; } else { throw new ISE( "Try to aggregate unsuported class type [%s].Supported class types: String or SerializablePairLongString", value.getClass().getCanonicalName() ); } if (firstValue != null && firstValue.length() > maxStringBytes) { firstValue = firstValue.substring(0, maxStringBytes); } } else { firstValue = null; } } }
Source:
<code>public void cancelTransference(OCFile file) { Account account = mFileActivity.getAccount(); FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder(); FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder(); if (downloaderBinder != null) { if (downloaderBinder.isDownloading(account, file)) { if (file.keepInSync()) { OCFile parent = mFileActivity.getStorageManager().getFileById(file.getParentId()); parent.setEtag(""); mFileActivity.getStorageManager().saveFile(parent); } downloaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Download for " + file + " not in progress. Cannot cancel " + file); } } if (uploaderBinder != null) { <START> if (uploaderBinder.isUploading(account, file)) { <END> uploaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Upload for " + file + " not in progress. Cannot cancel."); } } if(downloaderBinder == null && uploaderBinder == null) { Log_OC.w(TAG, "Neither downloaderBinder nor uploaderBinder set. Cannot cancel."); } }</code><technical_language>This is fine, curious. specific reason (bug) rewrite this part, tidying up</technical_language>

Target:
public void cancelTransference(OCFile file) { Account account = mFileActivity.getAccount(); if (file.isFolder()) { OperationsService.OperationsServiceBinder opsBinder = mFileActivity.getOperationsServiceBinder(); if (opsBinder != null) { opsBinder.cancel(account, file); } } FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder(); FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder(); if (downloaderBinder != null) { if (downloaderBinder.isDownloading(account, file)) { if (file.isFavorite()) { OCFile parent = mFileActivity.getStorageManager().getFileById(file.getParentId()); parent.setEtag(""); mFileActivity.getStorageManager().saveFile(parent); } downloaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Download for " + file + " not in progress. Cannot cancel " + file); } } if (uploaderBinder != null) { if (uploaderBinder.isUploading(account, file)) { uploaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Upload for " + file + " not in progress. Cannot cancel."); } } if(downloaderBinder == null && uploaderBinder == null) { Log_OC.w(TAG, "Neither downloaderBinder nor uploaderBinder set. Cannot cancel."); } }
Source:
<code>private void persistCleanupToken() throws IOException, StoreException { if (endToken == null || ((StoreFindToken) endToken).isUninitialized()) { return; } final Timer.Context context = metrics.cleanupTokenFlushTime.time(); File tempFile = new File(dataDir, Cleanup_Token_Filename + ".tmp"); File actual = new File(dataDir, Cleanup_Token_Filename); FileOutputStream fileStream = new FileOutputStream(tempFile); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); <START> <END> try { writer.writeShort(version); writer.write(startTokenSafeToPersist.toBytes()); writer.write(endToken.toBytes()); writer.write(hardDeleteRecoveryRange.toBytes()); long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); tempFile.renameTo(actual); } catch (IOException e) { throw new StoreException("IO error while persisting cleanup tokens to disk " + tempFile.getAbsoluteFile(), StoreErrorCodes.IOError); } finally { writer.close(); context.stop(); } logger.debug("Completed writing cleanup tokens to file {}", actual.getAbsolutePath()); }</code><technical_language>avoid empty lines is a</technical_language>

Target:
private void persistCleanupToken() throws IOException, StoreException { if (endToken == null || ((StoreFindToken) endToken).isUninitialized()) { return; } final Timer.Context context = metrics.cleanupTokenFlushTime.time(); File tempFile = new File(dataDir, Cleanup_Token_Filename + ".tmp"); File actual = new File(dataDir, Cleanup_Token_Filename); FileOutputStream fileStream = new FileOutputStream(tempFile); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { writer.writeShort(Cleanup_Token_Version_V1); writer.write(startTokenSafeToPersist.toBytes()); writer.write(endToken.toBytes()); writer.write(hardDeleteRecoveryRange.toBytes()); long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); tempFile.renameTo(actual); } catch (IOException e) { throw new StoreException("IO error while persisting cleanup tokens to disk " + tempFile.getAbsoluteFile(), StoreErrorCodes.IOError); } finally { writer.close(); context.stop(); } logger.debug("Completed writing cleanup tokens to file {}", actual.getAbsolutePath()); }
Source:
<code><START> private void checkExtendedAttributesSupport() { <END> if (isMacOSX()) { throw new SkipException("filesystem does not support extended attributes on Mac OSX"); } }</code><technical_language>[minor] this need instance method, this static</technical_language>

Target:
protected void checkExtendedAttributesSupport() { if (isMacOSX()) { throw new SkipException("filesystem does not support extended attributes in Mac OSX"); } }
Source:
<code>public void connect(IDocument doc) { document = doc; document.setDocumentPartitioner(this); lld = document.getLegalLineDelimiters(); <START> partitions.clear(); pendingPartitions.clear(); <END> inputPartitions = new ArrayList<>(); queueJob = new QueueProcessingJob(); queueJob.setSystem(true); queueJob.setPriority(Job.INTERACTIVE); queueJob.setRule(console.getSchedulingRule()); }</code><technical_language>synchronized</technical_language>

Target:
public void connect(IDocument doc) { if (doc == document) { return; } synchronized (partitions) { disconnect(); if (doc != null) { inputPartitions = new ArrayList<>(); document = doc; lld = document.getLegalLineDelimiters(); if (lld == null) { lld = new String[0]; } } } }
Source:
<code>public void notifyTableChanged(String dbName, String tableName, long updateTime) { LOG.debug("Table changed: {}.{}, at {}", dbName, tableName, updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { <START> String key = TableName.getDbTable(dbName, tableName).toLowerCase(); <END> Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }</code><technical_language>I this point a tablename somewhere; constructing sense</technical_language>

Target:
public void notifyTableChanged(String dbName, String tableName, long updateTime) { LOG.debug("Table changed: {}.{}, at {}", dbName, tableName, updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { String key = (dbName.toLowerCase() + "." + tableName.toLowerCase()); Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }
Source:
<code>private String deployVlan(final String networkDomainId, final String vlanName, final DimensionDataCloudControlTemplateOptions templateOptions) { logger.debug("Creating a vlan %s in network domain '%s' ...", vlanName, networkDomainId); String defaultPrivateIPv4BaseAddress = firstNonNull(templateOptions.getDefaultPrivateIPv4BaseAddress(), DEFAULT_PRIVATE_IPV4_BASE_ADDRESS); Integer defaultPrivateIPv4PrefixSize = firstNonNull(templateOptions.getDefaultPrivateIPv4PrefixSize(), DEFAULT_PRIVATE_IPV4_PREFIX_SIZE); String vlanId = api.getNetworkApi() .deployVlan(networkDomainId, vlanName, "vlan created by jclouds", defaultPrivateIPv4BaseAddress, defaultPrivateIPv4PrefixSize); <START> boolean isVlanReady = retry(new VlanState(api.getNetworkApi(), State.NORMAL), timeouts.nodeRunning).apply(vlanId); <END> if (!isVlanReady) { String message = format("vlan(%s) is not ready within %d ms.", vlanId, timeouts.nodeRunning); throw new IllegalStateException(message); } return vlanId; }</code><technical_language>This is a small PR I introduce Guice-configured predicates stop initializing manually. properly configure predicates compute service module get injected needed. This done in a PR unifies removes static utils class</technical_language>

Target:
private String deployVlan(final String networkDomainId, final String vlanName, final DimensionDataCloudControlTemplateOptions templateOptions) { logger.debug("Creating a vlan %s in network domain '%s' ...", vlanName, networkDomainId); String defaultPrivateIPv4BaseAddress = firstNonNull(templateOptions.getDefaultPrivateIPv4BaseAddress(), DimensionDataCloudControlTemplateOptions.DEFAULT_PRIVATE_IPV4_BASE_ADDRESS); Integer defaultPrivateIPv4PrefixSize = firstNonNull(templateOptions.getDefaultPrivateIPv4PrefixSize(), DimensionDataCloudControlTemplateOptions.DEFAULT_PRIVATE_IPV4_PREFIX_SIZE); String vlanId = api.getNetworkApi() .deployVlan(networkDomainId, vlanName, "vlan created by jclouds", defaultPrivateIPv4BaseAddress, defaultPrivateIPv4PrefixSize); if (!vlanNormalPredicate.apply(vlanId)) { String message = format("vlan(%s) is not ready within %d ms.", vlanId, timeouts.nodeRunning); throw new IllegalStateException(message); } return vlanId; }
Source:
<code>public void delete(E plugin) { ApplicationService<Application, ApplicationDao<Application>> appService = this.applicationService; if (appService == null) { LOG.error("Plugin cannot be deleted, failed to autowire application service"); return; } List<Application> apps = appService.findAll(); Integer pluginId = plugin.getId(); for (Application app : apps) { List<Plugin> plugins = app.getPlugins(); if (plugins != null && plugins.contains(plugin)) { <START> if (LOG.isDebugEnabled()) { <END> String msg = String.format( "Remove plugin (id=%s) from application (id=%s)", pluginId, app.getId() ); LOG.debug(msg); } plugins.remove(plugin); appService.saveOrUpdate(app); } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Delete plugin (id=%s)", pluginId)); } super.delete(plugin); }</code><technical_language>I this check is blowing code... LOG.debug(...)!</technical_language>

Target:
public void delete(E plugin) { if (applicationService == null) { LOG.error("Plugin cannot be deleted, failed to autowire application service"); return; } List<Application> apps = applicationService.findAll(); Integer pluginId = plugin.getId(); for (Application app : apps) { List<Plugin> plugins = app.getPlugins(); if (plugins != null && plugins.contains(plugin)) { String msg = String.format( "Remove plugin (id=%s) from application (id=%s)", pluginId, app.getId() ); LOG.debug(msg); plugins.remove(plugin); applicationService.saveOrUpdate(app); } } LOG.debug(String.format("Delete plugin (id=%s)", pluginId)); super.delete(plugin); }
Source:
<code>private Host getHostFromSession(final HttpServletRequest request, final User user, final PageMode mode) throws DotSecurityException, DotDataException { final Object hostId = request.getSession().getAttribute(WebKeys.CMS_SELECTED_HOST_ID); if(mode.isAdmin && hostId !=null) { return this.hostAPI.find(hostId.toString(), user, mode.respectAnonPerms); } else { <START> return null; <END> } }</code><technical_language>return optional instead</technical_language>

Target:
private Optional<Host> getHostFromSession(final HttpServletRequest request, final User user, final PageMode mode) throws DotSecurityException, DotDataException { final Object hostId = request.getSession().getAttribute(WebKeys.CMS_SELECTED_HOST_ID); if(mode.isAdmin && hostId !=null) { final Host host = this.hostAPI.find(hostId.toString(), user, mode.respectAnonPerms); return Optional.ofNullable(host); } else { return Optional.empty(); } }
Source:
<code>public void evenTheSecundaryNameIsTaken() { doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), <START> eq("module1")); <END> doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq("module1-1")); String module = "module1"; String module_1 = "module1 [1]"; String module_2 = "module1 [2]"; doReturn(module_2).when(projectService).createProjectName(any(), eq(module)); WorkspaceProject project1 = mock(WorkspaceProject.class); doReturn(module).when(project1).getName(); List<WorkspaceProject> projects1 = new ArrayList<>(); projects1.add(project1); projects1.add(project1); doReturn(projects1).when(projectService).getAllWorkspaceProjectsByName(any(), eq("module1")); WorkspaceProject project2 = mock(WorkspaceProject.class); doReturn(module_1).when(project2).getName(); List<WorkspaceProject> projects2 = new ArrayList<>(); projects2.add(project2); doReturn(projects2).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module_1)); service.setupExamples(exampleOrganizationalUnit, exampleProjects); verify(projectScreenService).save(any(), modelCapture.capture(), any()); final ProjectScreenModel model = modelCapture.getValue(); assertEquals(module_2, model.getPOM().getName()); }</code><technical_language>Please move local variables top consistently test method (you've this module variable, "module1" literal 2 places</technical_language>

Target:
public void evenTheSecundaryNameIsTaken() { String module = "module1"; String module_1 = "module1 [1]"; String module_2 = "module1 [2]"; doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq(module)); doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq(module_1)); doReturn(module_2).when(projectService).createFreshProjectName(any(), eq(module)); WorkspaceProject project1 = mock(WorkspaceProject.class); doReturn(module).when(project1).getName(); List<WorkspaceProject> projects1 = new ArrayList<>(); projects1.add(project1); projects1.add(project1); doReturn(projects1).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module)); WorkspaceProject project2 = mock(WorkspaceProject.class); doReturn(module_1).when(project2).getName(); List<WorkspaceProject> projects2 = new ArrayList<>(); projects2.add(project2); doReturn(projects2).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module_1)); service.setupExamples(exampleOrganizationalUnit, exampleProjects); verify(projectScreenService).save(any(), modelCapture.capture(), any()); final ProjectScreenModel model = modelCapture.getValue(); assertEquals(module_2, model.getPOM().getName()); }
Source:
<code>public void open() { session.getUiElements().getMenu().openMenu(MainMenu.PERUN_ADMIN); <START> session.getUiElements().getBreadcrumbs().setLocation(0, "edit_keys", getUrlWithParameters()); <END> }</code><technical_language>This 'edit_keys' in a readable form. is displayed in breadcrumb. I 'Entityless attributes setting'</technical_language>

Target:
public void open() { session.getUiElements().getMenu().openMenu(MainMenu.PERUN_ADMIN); session.getUiElements().getBreadcrumbs().setLocation(0, "Entityless attributes setting", getUrlWithParameters()); }
Source:
<code>public void register(String name, HealthCheck healthCheck) { HealthCheck registered = null; synchronized (lock) { if (!healthChecks.containsKey(name)) { registered = healthCheck; if (healthCheck.getClass().isAnnotationPresent(Async.class)) { registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); } healthChecks.put(name, registered); } } if (registered == null) { throw new IllegalArgumentException("A health check named " + name + " already exists"); <START> } else { <END> onHealthCheckAdded(name, registered); } }</code><technical_language>move throwing exception containsKey check. more logical (we check health check exist, throw exception). java if (!healthChecks.containsKey(name)) { .... } else { throw new IllegalArgumentException("A health check named " + name + " exists"); } this allows remove null check invoking listeners, compiler guarantee registered null</technical_language>

Target:
public void register(String name, HealthCheck healthCheck) { HealthCheck registered; synchronized (lock) { if (healthChecks.containsKey(name)) { throw new IllegalArgumentException("A health check named " + name + " already exists"); } registered = healthCheck; if (healthCheck.getClass().isAnnotationPresent(Async.class)) { registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); } healthChecks.put(name, registered); } onHealthCheckAdded(name, registered); }
Source:
<code>public static void displayWarningMsg(Throwable exception) { final String warningMsg = exception.getMessage(); Display.getDefault().asyncExec(() -> { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Activator.getDefault().logWarning(warningMsg, exception); <START> MessageDialog.openError(shell, <END> exception.getClass().getSimpleName(), warningMsg); }); }</code><technical_language>is openWarning() ;)</technical_language>

Target:
public static void displayWarningMsg(Throwable exception) { final String warningMsg = exception.getMessage(); Display.getDefault().asyncExec(() -> { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Activator.getDefault().logWarning(warningMsg, exception); MessageDialog.openWarning(shell, exception.getClass().getSimpleName(), warningMsg); }); }