auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { RemoveAllPRMessage message = spy(new RemoveAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); <START> try { message.doLocalRemoveAll(partitionedRegion, mock(InternalDistributedMember.class), true); fail("Expect PrimaryBucketException"); } catch (Exception e) { assertThat(e instanceof PrimaryBucketException); } <END> InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }</code><technical_language>This replaced assertThatThrownBy(() -> message.doLocalRemoveAll(partitionedRegion, mock(InternalDistributedMember.class), true)).isInstanceOf(PrimaryBucketException.class); a bit neater</technical_language>

Target:
public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { RemoveAllPRMessage message = spy(new RemoveAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); assertThatThrownBy(() -> message.doLocalRemoveAll(partitionedRegion, mock(InternalDistributedMember.class), true)).isInstanceOf(PrimaryBucketException.class); InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }
Source:
<code>public String toString() { if (parameters != null) { String parity = "N"; String flowControl = "N"; if (parameters.parity == 1) parity = "O"; else if (parameters.parity == 2) parity = "E"; else if (parameters.parity == 3) parity = "M"; else if (parameters.parity == 4) parity = "S"; if (parameters.flowControl == 1 || parameters.flowControl == 2 || parameters.flowControl == 3) flowControl = "H"; else if (parameters.flowControl == 4 || parameters.flowControl == 8 || parameters.flowControl == 12) flowControl = "S"; <START> return port.toString() + " - " + baudRate + "/" + parameters.dataBits + <END> "/" + parity + "/" + parameters.stopBits + "/" + flowControl; } else return port.toString() + " - " + baudRate + "/8/N/1/N"; }</code><technical_language>port field is a string, toString() called is needed</technical_language>

Target:
public String toString() { if (parameters != null) { String parity = "N"; String flowControl = "N"; if (parameters.parity == 1) parity = "O"; else if (parameters.parity == 2) parity = "E"; else if (parameters.parity == 3) parity = "M"; else if (parameters.parity == 4) parity = "S"; if (parameters.flowControl == 1 || parameters.flowControl == 2 || parameters.flowControl == 3) flowControl = "H"; else if (parameters.flowControl == 4 || parameters.flowControl == 8 || parameters.flowControl == 12) flowControl = "S"; return port + " - " + baudRate + "/" + parameters.dataBits + "/" + parity + "/" + parameters.stopBits + "/" + flowControl; } else return port + " - " + baudRate + "/8/N/1/N"; }
Source:
<code>public RiakResponse head(String bucket, String key, FetchMeta fm) throws IOException { if(fm != null) { <START> fm = new FetchMeta(fm.getR(), fm.getPr(), fm.getNotFoundOK(), fm.getBasicQuorum(), true, <END> fm.getReturnDeletedVClock(), fm.getIfModifiedSince(), fm.getIfModifiedVClock()); } else { fm = FetchMeta.head(); } return fetch(bucket, key, fm); }</code><technical_language>builder syntax here</technical_language>

Target:
public RiakResponse head(String bucket, String key, FetchMeta fm) throws IOException { if(fm != null) { fm = FetchMeta.Builder.from(fm).headOnly(true).build(); } else { fm = FetchMeta.head(); } return fetch(bucket, key, fm); }
Source:
<code>public void assertEmptyErrorListConstructorFailure() throws Exception { try { new MultipleFailureException(Collections.<Throwable>emptyList()); <START> fail(); <END> } catch (Exception expected) { assertThat(expected, instanceOf(IllegalArgumentException.class)); assertTrue(expected.getMessage().equals("Argument error list cannot be empty")); } }</code><technical_language>fail()method throws AssertionError is Exception. ExpectedException change catch clause catch exact exception expecting</technical_language>

Target:
public void assertEmptyErrorListConstructorFailure() throws Exception { try { new MultipleFailureException(Collections.<Throwable>emptyList()); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Argument error list cannot be empty")); } }
Source:
<code>private CompletableFuture<Boolean> addRepository() { TextInputDialog dialog = new TextInputDialog(); dialog.setHeaderText("Add a new repository"); dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> { String repositoryId = Utility.removeAllWhitespace(newValue); if (!repositoryId.equals(newValue)) { dialog.getEditor().setText(repositoryId); return; } }); Optional<String> userInput = dialog.showAndWait(); if (!userInput.isPresent()) { <START> return Futures.unit(false); <END> } String repoId = userInput.get(); return repoValidator.apply(repoId) .thenCompose(valid -> { if (!valid) { Platform.runLater(() -> DialogMessage.showErrorDialog("Cannot add to repository list", repoId + " is not a valid GitHub repository.")); return Futures.unit(false); } Platform.runLater(() -> addRepositoryToState(repoId)); return Futures.unit(true); }).exceptionally(e -> { Platform.runLater(() -> DialogMessage.showErrorDialog("Error checking the validity of " + repoId, "Please try again.")); return withResult(false).apply(e); }); }</code><technical_language>CompletableFuture.completedFuture (from standard library) here. This unit method is a bit of a legacy thing</technical_language>

Target:
private CompletableFuture<Boolean> addRepository() { TextInputDialog dialog = new TextInputDialog(); dialog.setHeaderText("Add a new repository"); dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> { String repositoryId = Utility.removeAllWhitespace(newValue); if (!repositoryId.equals(newValue)) { dialog.getEditor().setText(repositoryId); return; } }); Optional<String> userInput = dialog.showAndWait(); if (!userInput.isPresent()) { return CompletableFuture.completedFuture(false); } String repoId = userInput.get(); return repoValidator.apply(repoId) .thenCompose(valid -> { if (!valid) { Platform.runLater(() -> DialogMessage.showErrorDialog("Cannot add to repository list", repoId + " is not a valid GitHub repository.")); return Futures.unit(false); } Platform.runLater(() -> addRepositoryToState(repoId)); return CompletableFuture.completedFuture(true); }).exceptionally(e -> { Platform.runLater(() -> DialogMessage.showErrorDialog("Error checking the validity of " + repoId, "Please try again.")); return withResult(false).apply(e); }); }
Source:
<code>public Configuration getWorkerServiceConfiguration(final String contextId) { return Tang.Factory.getTang() .newConfigurationBuilder(ServiceConfiguration.CONF .set(ServiceConfiguration.SERVICES, <START> staleness > 0 ? SSPParameterWorkerImpl.class : ParameterWorkerImpl.class) <END> .set(ServiceConfiguration.ON_TASK_STARTED, TaskStartHandler.class) .set(ServiceConfiguration.ON_TASK_STOP, TaskStopHandler.class) .build()) .bindImplementation(ParameterWorker.class, staleness > 0 ? SSPParameterWorkerImpl.class : ParameterWorkerImpl.class) .bindImplementation(AsyncWorkerHandler.class, AsyncWorkerHandlerImpl.class) .bindImplementation(ServerResolver.class, DynamicServerResolver.class) .bindNamedParameter(NumServers.class, Integer.toString(numServers)) .bindNamedParameter(NumPartitions.class, Integer.toString(numPartitions)) .bindNamedParameter(EndpointId.class, contextId) .bindNamedParameter(ParameterWorkerNumThreads.class, Integer.toString(workerNumThreads)) .bindNamedParameter(WorkerQueueSize.class, Integer.toString(workerQueueSize)) .bindNamedParameter(WorkerExpireTimeout.class, Long.toString(workerExpireTimeout)) .bindNamedParameter(WorkerKeyCacheSize.class, Integer.toString(workerKeyCacheSize)) .bindNamedParameter(WorkerLogPeriod.class, Long.toString(workerLogPeriod)) .build(); }</code><technical_language>= 0 instead of > 0</technical_language>

Target:
public Configuration getWorkerServiceConfiguration(final String contextId) { return Tang.Factory.getTang() .newConfigurationBuilder(ServiceConfiguration.CONF .set(ServiceConfiguration.SERVICES, staleness < 0 ? ParameterWorkerImpl.class : SSPParameterWorkerImpl.class) .set(ServiceConfiguration.ON_TASK_STARTED, TaskStartHandler.class) .set(ServiceConfiguration.ON_TASK_STOP, TaskStopHandler.class) .build()) .bindImplementation(ParameterAccessor.class, SSPParameterAccessorImpl.class) .bindImplementation(ParameterWorker.class, staleness < 0 ? ParameterWorkerImpl.class : SSPParameterWorkerImpl.class) .bindImplementation(AsyncWorkerHandler.class, AsyncWorkerHandlerImpl.class) .bindImplementation(ServerResolver.class, DynamicServerResolver.class) .bindNamedParameter(NumServers.class, Integer.toString(numServers)) .bindNamedParameter(NumPartitions.class, Integer.toString(numPartitions)) .bindNamedParameter(EndpointId.class, contextId) .bindNamedParameter(ParameterWorkerNumThreads.class, Integer.toString(workerNumThreads)) .bindNamedParameter(WorkerQueueSize.class, Integer.toString(workerQueueSize)) .bindNamedParameter(WorkerExpireTimeout.class, Long.toString(workerExpireTimeout)) .bindNamedParameter(PullRetryTimeoutMs.class, Long.toString(pullRetryTimeoutMs)) .bindNamedParameter(WorkerKeyCacheSize.class, Integer.toString(workerKeyCacheSize)) .bindNamedParameter(WorkerLogPeriod.class, Long.toString(workerLogPeriod)) .build(); }
Source:
<code>public void should_get_answer_from_server_for_ts_request() throws Exception { eslintBridgeServer = createEslintBridgeServer(START_SERVER_SCRIPT); eslintBridgeServer.deploy(); eslintBridgeServer.startServer(context); <START> DefaultInputFile inputFile = TestInputFileBuilder.create("foo", "foo.js") <END> .setContents("alert('Fly, you fools!')") .build(); DefaultInputFile tsConfig = TestInputFileBuilder.create("foo", "tsconfig.json") .setContents("{\"compilerOptions\": {\"target\": \"es6\", \"allowJs\": true }}") .build(); EslintBridgeServer.TypeScriptAnalysisRequest request = new EslintBridgeServer.TypeScriptAnalysisRequest(inputFile, new EslintBridgeServer.Rule[0], Collections.singletonList(tsConfig.absolutePath())); assertThat(eslintBridgeServer.analyzeTypeScript(request)).isEqualTo(new EslintBridgeServer.AnalysisResponseIssue[0]); }</code><technical_language>foo.ts here</technical_language>

Target:
public void should_get_answer_from_server_for_ts_request() throws Exception { eslintBridgeServer = createEslintBridgeServer(START_SERVER_SCRIPT); eslintBridgeServer.deploy(); eslintBridgeServer.startServer(context); DefaultInputFile inputFile = TestInputFileBuilder.create("foo", "foo.ts") .setContents("alert('Fly, you fools!')") .build(); DefaultInputFile tsConfig = TestInputFileBuilder.create("foo", "tsconfig.json") .setContents("{\"compilerOptions\": {\"target\": \"es6\", \"allowJs\": true }}") .build(); TypeScriptAnalysisRequest request = new TypeScriptAnalysisRequest(inputFile, new Rule[0], singletonList(tsConfig.absolutePath())); assertThat(eslintBridgeServer.analyzeTypeScript(request).issues).isEmpty(); }
Source:
<code>private boolean hasScopeAnnotation(Class<?> clazz) { Annotation scopeAnnotation = null; for (Annotation annot : clazz.getAnnotations()) { <START> if (annot.annotationType().isAnnotationPresent(ScopeAnnotation.class)) { <END> Preconditions.checkState(scopeAnnotation == null, "Multiple scopes not allowed"); scopeAnnotation = annot; } } return scopeAnnotation != null; }</code><technical_language>add support for javax.inject.Scope annotation</technical_language>

Target:
private boolean hasScopeAnnotation(Class<?> clazz) { Annotation scopeAnnotation = null; for (Annotation annot : clazz.getAnnotations()) { if (annot.annotationType().isAnnotationPresent(ScopeAnnotation.class) || annot.annotationType().isAnnotationPresent(Scope.class)) { Preconditions.checkState(scopeAnnotation == null, "Multiple scopes not allowed"); scopeAnnotation = annot; } } return scopeAnnotation != null; }
Source:
<code>if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { EsteemedInnovation.logger.info("[EI] Getting some fields from reflection for Tick Handling."); <START> itemInMainHandField = ReflectionHelper.getField("itemStackMainHand", "field_187467_d", ItemRenderer.class); <END> itemInOffHandField = ReflectionHelper.getField("itemStackOffHand", "field_187468_e", ItemRenderer.class); if (itemInMainHandField != null) { itemInMainHandField.setAccessible(true); } if (itemInOffHandField != null) { itemInOffHandField.setAccessible(true); } }</code><technical_language>Note (mostly myself): * Double check fields correct * ReflectionHelper usages</technical_language>

Target:
if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { EsteemedInnovation.logger.info("Getting some fields from reflection for Tick Handling."); itemInMainHandField = ReflectionHelper.getField("itemStackMainHand", "field_187467_d", ItemRenderer.class); itemInOffHandField = ReflectionHelper.getField("itemStackOffHand", "field_187468_e", ItemRenderer.class); if (itemInMainHandField != null) { itemInMainHandField.setAccessible(true); } if (itemInOffHandField != null) { itemInOffHandField.setAccessible(true); } }
Source:
<code>public String entityNotFoundExceptionErrorHandler(EntityNotFoundException e) { e.printStackTrace(); <START> return "judgmentNotFound"; <END> }</code><technical_language>more general I think, e.g. entityNotFound. if exception thrown other object types db</technical_language>

Target:
public String entityNotFoundExceptionErrorHandler(EntityNotFoundException e) { e.printStackTrace(); return "entityNotFound"; }
Source:
<code>private void insertOverflowEntryIfNeeded(long hash) { int zeros = numberOfLeadingZeros(hash, indexBitLength); <START> if (zeros > (Short.SIZE - indexBitLength)) { <END> int overflowZeros = zeros - (Short.SIZE - indexBitLength) - 1; int bucketIndex = computeIndex(hash, indexBitLength); short overflowEntry = (short) ((bucketIndex << (Short.SIZE - indexBitLength)) | (overflowZeros & valueMask(indexBitLength))); int position = searchOverflow(bucketIndex); if (position < 0) { if (numberOfOverflows + 1 > overflows.length) { overflows = Arrays.copyOf(overflows, overflows.length + 1); } int insertionPoint = -(position + 1); if (insertionPoint < numberOfOverflows) { System.arraycopy(overflows, insertionPoint, overflows, insertionPoint + 1, numberOfOverflows - insertionPoint); } overflows[insertionPoint] = overflowEntry; numberOfOverflows++; } else { int oldValue = extractValue(overflows[position]); if (overflowZeros > oldValue) { overflows[position] = overflowEntry; } } } }</code><technical_language>Introduce a variable for (Short.SIZE - indexBitLength)</technical_language>

Target:
private void insertOverflowEntryIfNeeded(long hash) { int zeros = numberOfLeadingZeros(hash, indexBitLength); int overflowBits = Short.SIZE - indexBitLength; if (zeros > overflowBits) { int overflowZeros = zeros - overflowBits - 1; int bucketIndex = computeIndex(hash, indexBitLength); short overflowEntry = (short) ((bucketIndex << overflowBits) | (overflowZeros & valueMask(indexBitLength))); int position = searchOverflow(bucketIndex); if (position < 0) { if (numberOfOverflows + 1 > overflows.length) { overflows = Arrays.copyOf(overflows, overflows.length + 1); } int insertionPoint = -(position + 1); if (insertionPoint < numberOfOverflows) { System.arraycopy(overflows, insertionPoint, overflows, insertionPoint + 1, numberOfOverflows - insertionPoint); } overflows[insertionPoint] = overflowEntry; numberOfOverflows++; } else { int oldValue = extractValue(overflows[position]); if (overflowZeros > oldValue) { overflows[position] = overflowEntry; } } } }
Source:
<code>public Builder withRole(String role) { <START> instructorAttributes.role = (role == null) <END> ? Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER : SanitizationHelper.sanitizeName(role); return this; }</code><technical_language>If default settings. java if (role != null) { role = SanitizationHelper.sanitizeName(role); }</technical_language>

Target:
public Builder withRole(String role) { if (role != null) { instructorAttributes.role = SanitizationHelper.sanitizeName(role); } return this; }
Source:
<code>protected void addStockIdColumn(final List<MeasurementVariable> plotDataSetColumns) { final Optional<MeasurementVariable> <START> designationColumn = plotDataSetColumns.stream().filter(measurementVariable -> measurementVariable.getName().equals("DESIGNATION")).findFirst(); <END> plotDataSetColumns.add(plotDataSetColumns.indexOf(designationColumn.get()) + 1, buildStockIdColumn()); }</code><technical_language>here, compare id TermId ? @cuenyad</technical_language>

Target:
protected void addStockIdColumn(final List<MeasurementVariable> plotDataSetColumns) { final Optional<MeasurementVariable> designationColumn = plotDataSetColumns.stream().filter(measurementVariable -> measurementVariable.getTermId() == TermId.DESIG.getId()).findFirst(); plotDataSetColumns.add(plotDataSetColumns.indexOf(designationColumn.get()) + 1, addTermIdColumn(TermId.STOCK_ID, VariableType.GERMPLASM_DESCRIPTOR,null, true)); }
Source:
<code>public Set<Type> getTypes() { <START> return Collections.singleton( BeanMetaDataClassNormalizer.class ); <END> }</code><technical_language>If this is in request handling path please a constant</technical_language>

Target:
public Set<Type> getTypes() { return TYPES; }
Source:
<code>public Future<Object> replicate( ReplicatedContent command, boolean trackResult ) throws InterruptedException, NoLeaderFoundException { OperationContext session = sessionPool.acquireSession(); DistributedOperation operation = new DistributedOperation( command, session.globalSession(), session.localOperationId() ); Progress progress = progressTracker.start( operation ); RetryStrategy.Timeout progressTimeout = progressRetryStrategy.newTimeout(); RetryStrategy.Timeout leaderTimeout = leaderRetryStrategy.newTimeout(); do { assertDatabaseNotShutdown(); try { outbound.send( leaderLocator.getLeader(), new RaftMessages.NewEntry.Request( me, operation ) ); leaderTimeout = leaderRetryStrategy.newTimeout(); progress.awaitReplication( progressTimeout.getMillis() ); progressTimeout.increment(); } catch ( InterruptedException e ) { progressTracker.abort( operation ); throw e; } catch ( NoLeaderFoundException e ) { log.debug( "Could not replicate operation " + operation + " because no leader was found. Retrying.", e ); <START> wait( leaderTimeout.getMillis() ); <END> leaderTimeout.increment(); } } while( !progress.isReplicated() ); BiConsumer<Object,Throwable> cleanup = ( ignored1, ignored2 ) -> sessionPool.releaseSession( session ); if( trackResult ) { progress.futureResult().whenComplete( cleanup ); } else { cleanup.accept( null, null ); } return progress.futureResult(); }</code><technical_language>Thread.sleep(leaderTimeout.getMillis())</technical_language>

Target:
public Future<Object> replicate( ReplicatedContent command, boolean trackResult ) throws InterruptedException { OperationContext session = sessionPool.acquireSession(); DistributedOperation operation = new DistributedOperation( command, session.globalSession(), session.localOperationId() ); Progress progress = progressTracker.start( operation ); RetryStrategy.Timeout progressTimeout = progressRetryStrategy.newTimeout(); RetryStrategy.Timeout leaderTimeout = leaderRetryStrategy.newTimeout(); do { assertDatabaseNotShutdown(); try { outbound.send( leaderLocator.getLeader(), new RaftMessages.NewEntry.Request( me, operation ) ); leaderTimeout = leaderRetryStrategy.newTimeout(); progress.awaitReplication( progressTimeout.getMillis() ); progressTimeout.increment(); } catch ( InterruptedException e ) { progressTracker.abort( operation ); throw e; } catch ( NoLeaderFoundException e ) { log.debug( "Could not replicate operation " + operation + " because no leader was found. Retrying.", e ); Thread.sleep( leaderTimeout.getMillis() ); leaderTimeout.increment(); } } while( !progress.isReplicated() ); BiConsumer<Object,Throwable> cleanup = ( ignored1, ignored2 ) -> sessionPool.releaseSession( session ); if( trackResult ) { progress.futureResult().whenComplete( cleanup ); } else { cleanup.accept( null, null ); } return progress.futureResult(); }
Source:
<code>protected Text getNext() { try { if (sequenceReader==null) { return null; } Writable key = (Writable) ReflectionUtils.newInstance( sequenceReader.getKeyClass(), fs.getConf()); Writable value = (Writable) ReflectionUtils.newInstance( sequenceReader.getValueClass(), fs.getConf()); if (sequenceReader.next(key, value)) { return (Text) value; } else { sequenceReader.close(); sequenceReader = getNextSequenceReader(); <START> if (sequenceReader!=null) { <END> return getNext(); } } return null; } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>getNext handles this case</technical_language>

Target:
private Text getNext() { try { if (sequenceReader == null) { return null; } Writable key = (Writable) ReflectionUtils.newInstance(sequenceReader.getKeyClass(), fs.getConf()); Writable value = (Writable) ReflectionUtils.newInstance(sequenceReader.getValueClass(), fs.getConf()); if (sequenceReader.next(key, value)) { return (Text) value; } else { sequenceReader.close(); sequenceReader = getNextSequenceReader(); if (sequenceReader != null) { return getNext(); } } return null; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>void testNoQuestionColumns() throws IOException { DataImporter dimp = new RawDataSpreadsheetImporter(); File file = createNoQuestionsSpreadsheet("/tmp/invalid1.xlsx"); Map<Integer,String> errors = dimp.validate(file); assertEquals(1, errors.size()); String err1 = errors.get(-11); <START> assertNotEquals(err1, null); <END> }</code><technical_language>more accurate assertEquals() copy error text here</technical_language>

Target:
public void testNoQuestionColumns() throws IOException { DataImporter dimp = new RawDataSpreadsheetImporter(); File file = createNoQuestionsSpreadsheet("/tmp/invalid1.xlsx"); Map<Integer,String> errors = dimp.validate(file); assertEquals(1, errors.size()); String err1 = errors.get(-11); assertEquals("No question columns found on any sheet.", err1); }
Source:
<code>public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; <START> final String column = "_data"; <END> final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndex(column); if (column_index != -1) { return cursor.getString(column_index); } } } finally { if (cursor != null) { cursor.close(); } } return null; }</code><technical_language>This MediaStore.Images.Media.DATA hard-coded</technical_language>

Target:
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndex(column); if (column_index != -1) { return cursor.getString(column_index); } } } finally { if (cursor != null) { cursor.close(); } } return null; }
Source:
<code>private boolean createRepository(Attributes attributes) { String kind = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(IRepositoryConstants.PROPERTY_CONNECTOR_KIND)); String url = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(IRepositoryConstants.PROPERTY_URL)); if (kind != null && kind.length() > 0 && url != null && url.length() > 0) { <START> currentRepository = new TaskRepository(kind, url); <END> return true; } return false; }</code><technical_language>I for this return repository instead of setting field</technical_language>

Target:
private TaskRepository createRepository(Attributes attributes) { String kind = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(IRepositoryConstants.PROPERTY_CONNECTOR_KIND)); String url = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(IRepositoryConstants.PROPERTY_URL)); if (kind != null && kind.length() > 0 && url != null && url.length() > 0) { return new TaskRepository(kind, url); } return null; }
Source:
<code>private Adjacents updateAdjacents(Adjacents adj, ResourceRef subject, Set<ResourceRef> assertedAdjacents, Set<Publisher> sources) { Adjacents result = adj; if (subject.getId().equals(adj.getRef().getId())) { result = updateSubjectAdjacents(adj, assertedAdjacents, sources); } else if (sources.contains(adj.getSource())) { Set<Id> ids = assertedAdjacents .stream() .map(ResourceRef::getId) .distinct() <START> .collect(Collectors.toSet()); <END> if (ids.contains(adj.getRef().getId())) { result = adj.copyWithAfferent(subject); } else if (adj.hasAfferentAdjacent(subject)) { result = adj.copyWithoutAfferent(subject); } } return result; }</code><technical_language>Nitpick: do MoreCollectors.toImmutableSet()</technical_language>

Target:
private Adjacents updateAdjacents(Adjacents adj, ResourceRef subject, Set<ResourceRef> assertedAdjacents, Set<Publisher> sources) { Adjacents result = adj; if (subject.getId().equals(adj.getRef().getId())) { result = updateSubjectAdjacents(adj, assertedAdjacents, sources); } else if (sources.contains(adj.getSource())) { Set<Id> ids = assertedAdjacents .stream() .map(ResourceRef::getId) .distinct() .collect(MoreCollectors.toImmutableSet()); if (ids.contains(adj.getRef().getId())) { result = adj.copyWithAfferent(subject); } else if (adj.hasAfferentAdjacent(subject)) { result = adj.copyWithoutAfferent(subject); } } return result; }
Source:
<code>public Properties getAdditionalProps() { <START> Properties props = new Properties(); <END> for (Entry<String, String> prop : this.additionalProperties.entrySet()) { props.put(prop.getKey(), prop.getValue()); } return props; }</code><technical_language>putAll</technical_language>

Target:
public Properties getAdditionalProps() { Properties props = new Properties(); props.putAll(this.additionalProperties); return props; }
Source:
<code>public void visit(Edge edge) { for (StreamGrouping streamGrouping : edge.getStreamGroupings()) { try { StreamInfo streamInfo = streamCatalogService.getStreamInfo( Long.parseLong(streamGrouping.getStream().getId())); <START> topologyReprBuilder.addStreamInfo(streamInfo); <END> } catch (Exception e) { throw new RuntimeException( String.format("Unexpected exception thrown while trying to add the stream %d", streamGrouping.getStream().getId()), e); } } List<QueryParam> queryParams = new ArrayList<>(); queryParams.add(new QueryParam("fromId", edge.getFrom().getId())); queryParams.add(new QueryParam("toId", edge.getTo().getId())); try { Collection<TopologyEdge> topologyEdges = streamCatalogService.listTopologyEdges(queryParams); topologyReprBuilder.addEdge(topologyEdges.iterator().next()); } catch (Exception e) { throw new RuntimeException( String.format( "Unexpected exception while trying to retrieve topology edge from %s to %s", edge.getFrom().getId(), edge.getTo().getId()), e); } }</code><technical_language>skip this step, sources processors capture this already</technical_language>

Target:
public void visit(Edge edge) { List<QueryParam> queryParams = new ArrayList<>(); queryParams.add(new QueryParam("fromId", edge.getFrom().getId())); queryParams.add(new QueryParam("toId", edge.getTo().getId())); try { Collection<TopologyEdge> topologyEdges = streamCatalogService.listTopologyEdges(queryParams); topologyData.addEdge(topologyEdges.iterator().next()); } catch (Exception e) { throw new RuntimeException( String.format( "Unexpected exception while trying to retrieve topology edge from %s to %s", edge.getFrom().getId(), edge.getTo().getId()), e); } }
Source:
<code>protected MeasurementDetails doInBackground(Object... params) { <START> Context context = (Context) params[0]; <END> String measurementId = (String) params[1]; String ministryId = (String) params[2]; String mcc = (String) params[3]; String period = (String) params[4]; if(measurementId != null && ministryId != null && mcc != null && period != null) { try { GmaApiClient apiClient = GmaApiClient.getInstance(context); JSONObject results = apiClient.getDetailsForMeasurement(measurementId, ministryId, mcc, period); if(results == null) { Log.w(TAG, "No measurement details!"); return null; } MeasurementDetails measurementDetails = MeasurementsJsonParser.parseMeasurementDetails(results); measurementDetails.setMeasurementId(measurementId); measurementDetails.setMinistryId(ministryId); measurementDetails.setMcc(mcc); measurementDetails.setPeriod(period); return measurementDetails; } catch(ApiException e) { Log.e(TAG, "Failed to retrieve measurement details from API", e); return null; } } return null; }</code><technical_language>pass context object in execute, MeasurementDetailsActivity.this this a static class</technical_language>

Target:
protected MeasurementDetails doInBackground(Object... params) { String measurementId = (String) params[0]; String ministryId = (String) params[1]; String mcc = (String) params[2]; String period = (String) params[3]; if(measurementId != null && ministryId != null && mcc != null && period != null) { try { GmaApiClient apiClient = GmaApiClient.getInstance(MeasurementDetailsActivity.this); JSONObject results = apiClient.getDetailsForMeasurement(measurementId, ministryId, mcc, period); if(results == null) { Log.w(TAG, "No measurement details!"); return null; } MeasurementDetails measurementDetails = MeasurementsJsonParser.parseMeasurementDetails(results); measurementDetails.setMeasurementId(measurementId); measurementDetails.setMinistryId(ministryId); measurementDetails.setMcc(mcc); measurementDetails.setPeriod(period); return measurementDetails; } catch(ApiException e) { Log.e(TAG, "Failed to retrieve measurement details from API", e); return null; } } return null; }
Source:
<code><START> public Map<String, String> getJobMessageProperties() { <END> if (volume != null) { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } return jobProperties; }</code><technical_language>is a potential NPE jobProperties initialized. suggest changing to: @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); if (volume != null) { jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } } return jobProperties; }</technical_language>

Target:
public Map<String, String> getJobMessageProperties() { if(volume == null) { return super.getJobMessageProperties(); } if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); return jobProperties; }
Source:
<code><START> private Map<String, Object> buildVmGraphicsSpecParamsFromVm(Map<GraphicsType, GraphicsInfo> infos) { <END> Map<String, Object> specParamsFromVm = null; if (infos.containsKey(GraphicsType.SPICE)) { specParamsFromVm = new HashMap(); specParamsFromVm.put(VdsProperties.spiceFileTransferEnable, Boolean.toString(vm.isSpiceFileTransferEnabled())); specParamsFromVm.put(VdsProperties.spiceCopyPasteEnable, Boolean.toString(vm.isSpiceCopyPasteEnabled())); } return specParamsFromVm; }</code><technical_language>infos null? (the check in line 112 implies be)</technical_language>

Target:
private Map<String, Object> buildVmGraphicsSpecParamsFromVm(Map<GraphicsType, GraphicsInfo> infos) { Map<String, Object> specParamsFromVm = null; if (infos != null && infos.containsKey(GraphicsType.SPICE)) { specParamsFromVm = new HashMap(); specParamsFromVm.put(VdsProperties.spiceFileTransferEnable, Boolean.toString(vm.isSpiceFileTransferEnabled())); specParamsFromVm.put(VdsProperties.spiceCopyPasteEnable, Boolean.toString(vm.isSpiceCopyPasteEnabled())); } return specParamsFromVm; }
Source:
<code>public void saveNewSanStorage() { StorageModel storageModel = (StorageModel) getWindow(); final SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getCurrentStorageItem(); List<String> unkownStatusLuns = new ArrayList<>(); List<LUNs> usedStatusLuns = new ArrayList<>(); <START> for (LunModel lunModel : sanStorageModel.getAddedLuns()) { <END> if (lunModel.getStatus() == LunStatus.Used) { usedStatusLuns.add((LUNs) lunModel.getEntity()); } else if (lunModel.getStatus() == LunStatus.Unknown) { unkownStatusLuns.add(lunModel.getLunId()); } } if (!unkownStatusLuns.isEmpty()) { Guid hostId = sanStorageModel.getContainer().getHost().getSelectedItem().getId(); Model target = getWidgetModel() != null ? getWidgetModel() : sanStorageModel.getContainer(); Frontend.getInstance() .runQuery(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(hostId, sanStorageModel.getType(), true, unkownStatusLuns), new AsyncQuery(target, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue; if (response.getSucceeded()) { List<LUNs> checkedLuns = (ArrayList<LUNs>) response.getReturnValue(); postGetLunsMessages(sanStorageModel.getUsedLunsMessages(checkedLuns)); } else { sanStorageModel.setGetLUNsFailure( ConstantsManager.getInstance() .getConstants() .couldNotRetrieveLUNsLunsFailure()); } } }, true)); } else { postGetLunsMessages(sanStorageModel.getUsedLunsMessages(usedStatusLuns)); } }</code><technical_language>please export this method a function returns a map (the key is status, list of luns is status) shorten code here</technical_language>

Target:
public void saveNewSanStorage() { StorageModel storageModel = (StorageModel) getWindow(); final SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getCurrentStorageItem(); Map<LunStatus, List<LUNs>> lunsMapByStatus = getLunsMapByStatus(sanStorageModel.getAddedLuns()); if (!lunsMapByStatus.get(LunStatus.Unknown).isEmpty()) { Guid hostId = sanStorageModel.getContainer().getHost().getSelectedItem().getId(); Model target = getWidgetModel() != null ? getWidgetModel() : sanStorageModel.getContainer(); List<String> unkownStatusLuns = new ArrayList<>(); for (LUNs lun : lunsMapByStatus.get(LunStatus.Unknown)) { unkownStatusLuns.add(lun.getLUN_id()); } Frontend.getInstance() .runQuery(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(hostId, sanStorageModel.getType(), true, unkownStatusLuns), new AsyncQuery(target, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue; if (response.getSucceeded()) { List<LUNs> checkedLuns = (ArrayList<LUNs>) response.getReturnValue(); postGetLunsMessages(sanStorageModel.getUsedLunsMessages(checkedLuns)); } else { sanStorageModel.setGetLUNsFailure( ConstantsManager.getInstance() .getConstants() .couldNotRetrieveLUNsLunsFailure()); } } }, true)); } else { postGetLunsMessages(sanStorageModel.getUsedLunsMessages(lunsMapByStatus.get(LunStatus.Used))); } }
Source:
<code>public void testConcurrency() throws Exception { <START> conn.tableOperations().setProperty(table, "table.compaction.major.ratio", "1"); <END> conn.tableOperations().setProperty(table, "table.cache.block.enable", "true"); int numAccounts = 5000; TreeSet<Text> splits = new TreeSet<>(); splits.add(new Text(fmtAcct(numAccounts / 4))); splits.add(new Text(fmtAcct(numAccounts / 2))); splits.add(new Text(fmtAcct(3 * numAccounts / 4))); conn.tableOperations().addSplits(table, splits); AtomicBoolean runFlag = new AtomicBoolean(true); populate(env, numAccounts); Random rand = new Random(); Environment tenv = env; if (rand.nextBoolean()) { tenv = new FaultyConfig(env, (rand.nextDouble() * .4) + .1, .50); } List<Thread> threads = startTransfers(tenv, numAccounts, 20, runFlag); runVerifier(env, numAccounts, 100); runFlag.set(false); for (Thread thread : threads) { thread.join(); } log.debug("txCount : " + txCount.get()); Assert.assertTrue("txCount : " + txCount.get(), txCount.get() > 0); runVerifier(env, numAccounts, 1); }</code><technical_language>file constants for Accumulo props Fluo uses. ./modules/accumulo/src/main/java/org/apache/fluo/accumulo/util/AccumuloProps.java</technical_language>

Target:
public void testConcurrency() throws Exception { conn.tableOperations().setProperty(table, AccumuloProps.TABLE_MAJC_RATIO, "1"); conn.tableOperations().setProperty(table, AccumuloProps.TABLE_BLOCKCACHE_ENABLED, "true"); int numAccounts = 5000; TreeSet<Text> splits = new TreeSet<>(); splits.add(new Text(fmtAcct(numAccounts / 4))); splits.add(new Text(fmtAcct(numAccounts / 2))); splits.add(new Text(fmtAcct(3 * numAccounts / 4))); conn.tableOperations().addSplits(table, splits); AtomicBoolean runFlag = new AtomicBoolean(true); populate(env, numAccounts); Random rand = new Random(); Environment tenv = env; if (rand.nextBoolean()) { tenv = new FaultyConfig(env, (rand.nextDouble() * .4) + .1, .50); } List<Thread> threads = startTransfers(tenv, numAccounts, 20, runFlag); runVerifier(env, numAccounts, 100); runFlag.set(false); for (Thread thread : threads) { thread.join(); } log.debug("txCount : " + txCount.get()); Assert.assertTrue("txCount : " + txCount.get(), txCount.get() > 0); runVerifier(env, numAccounts, 1); }
Source:
<code>private static FenixDepartment getFenixDepartment(Department department, AcademicInterval interval) { String name = department.getNameI18n().getContent(); String acronym = department.getAcronym(); List<Employee> employees = Employee.getAllWorkingEmployees(department, interval.getBeginYearMonthDayWithoutChronology(), interval.getEndYearMonthDayWithoutChronology()); <START> Set<Person> employeePeople = employees.stream().filter(employee -> employee != null).map(Employee::getPerson).collect(Collectors.toSet()); <END> List<Teacher> teachers = department.getAllTeachers(interval); Set<Person> teacherPeople = teachers.stream().map(Teacher::getPerson).collect(Collectors.toSet()); employeePeople.removeAll(teacherPeople); List<FenixDepartment.FenixDepartmentMember> members = new ArrayList<>(); teacherPeople.stream().map(p -> getFenixDepartmentTeacher(department, p, interval)).forEach(members::add); employeePeople.stream().map(p -> getFenixDepartmentEmployee(department, p, interval)).forEach(members::add); return new FenixDepartment(name, acronym, members); }</code><technical_language>suggestion Set<Person> employeePeople = employees.stream().filter(Objects::nonNull).map(Employee::getPerson).collect(Collectors.toSet());</technical_language>

Target:
private static FenixDepartment getFenixDepartment(Department department, AcademicInterval interval) { String name = department.getNameI18n().getContent(); String acronym = department.getAcronym(); List<Employee> employees = Employee.getAllWorkingEmployees(department, interval.getBeginYearMonthDayWithoutChronology(), interval.getEndYearMonthDayWithoutChronology()); Set<Person> employeePeople = employees.stream().filter(Objects::nonNull).map(Employee::getPerson).collect(Collectors.toSet()); List<Teacher> teachers = department.getAllTeachers(interval); Set<Person> teacherPeople = teachers.stream().map(Teacher::getPerson).collect(Collectors.toSet()); employeePeople.removeAll(teacherPeople); List<FenixDepartment.FenixDepartmentMember> members = new ArrayList<>(); teacherPeople.stream().map(p -> getFenixDepartmentTeacher(department, p, interval)).forEach(members::add); employeePeople.stream().map(p -> getFenixDepartmentEmployee(department, p, interval)).forEach(members::add); return new FenixDepartment(name, acronym, members); }
Source:
<code>public IndexEntry next() { try { StoreKey key = getKeyAt(mmap, currentIdx); mmap.get(valueBuf); return new IndexEntry(key, new IndexValue(startOffset.getName(), ByteBuffer.wrap(valueBuf), getVersion())); } catch (Exception e) { logger.error("Failed to read index entry at " + currentIdx, e); } finally { currentIdx++; } <START> return null; <END> }</code><technical_language>This NullPointException if failed read index. Is this intended</technical_language>

Target:
public IndexEntry next() { try { StoreKey key = getKeyAt(mmap, currentIdx); mmap.get(valueBuf); return new IndexEntry(key, new IndexValue(startOffset.getName(), ByteBuffer.wrap(valueBuf), getVersion())); } catch (Exception e) { String message = "Failed to read index entry at " + currentIdx; logger.error(message, e); throw new IllegalStateException(message, e); } finally { currentIdx++; } }
Source:
<code>private boolean isExcluded(Path file) { <START> if (excludes == null && excludes.length < 1) { <END> return false; } for (String exclude : excludes) { if (repoDir.toPath().relativize(file).toString().matches(exclude)) { getLog().info("Excluding " + file); return true; } } return false; }</code><technical_language>I meant || here, &&, right</technical_language>

Target:
private boolean isExcluded(Path file) { if (excludes == null || excludes.length < 1) { return false; } for (String exclude : excludes) { if (repoDir.toPath().relativize(file).toString().matches(exclude)) { getLog().info("Excluding " + file); return true; } } return false; }
Source:
<code><START> public boolean isInstanceOf(Object obj, Class<?> clz) { <END> if (obj == null || clz == null) { if (log.isLoggable(Level.FINEST)) { log.finest("isInstanceOf error: obj=" + obj + " clz=" + clz); } return false; } return clz.isAssignableFrom(obj.getClass()); }</code><technical_language>this called isAssignableFrom? is Clazz.class.isInstance(obj)</technical_language>

Target:
public boolean isInstanceOf(Object obj, Class<?> clz) { if (obj == null || clz == null) { if (log.isLoggable(Level.FINEST)) { log.finest("isInstanceOf error: obj=" + obj + " clz=" + clz); } return false; } return clz.isInstance(obj); }
Source:
<code>public String getFileTypeIdentifer() { <START> return "corpoateBilledCorporatePaidFlatInputFileType"; <END> }</code><technical_language>this defined in a constant</technical_language>

Target:
public String getFileTypeIdentifer() { return CuFPConstants.CORPORATE_BILLED_CORPORATE_PAID_FLAT_INPUT_FILE_TYPE; }
Source:
<code>public PlanNode visitTableFinish(TableFinishNode node, RewriteContext<Void> context) { Optional<DeleteNode> delete = findNode(node.getSource(), DeleteNode.class); if (!delete.isPresent()) { return context.defaultRewrite(node); } Optional<TableScanNode> tableScan = findNode(delete.get().getSource(), TableScanNode.class); if (!tableScan.isPresent()) { return context.defaultRewrite(node); } TableScanNode tableScanNode = tableScan.get(); if (!metadata.supportsMetadataDelete(session, tableScanNode.getTable())) { return context.defaultRewrite(node); } DeleteHandle currentDeleteHandle = delete.get().getTarget(); return new MetadataDeleteNode( idAllocator.getNextId(), <START> new DeleteHandle( <END> new TableHandle( currentDeleteHandle.getHandle().getConnectorId(), currentDeleteHandle.getHandle().getConnectorHandle(), currentDeleteHandle.getHandle().getTransaction(), tableScan.get().getTable().getLayout()), currentDeleteHandle.getSchemaTableName()), Iterables.getOnlyElement(node.getOutputSymbols())); }</code><technical_language>Curious: do similar <LINK_0></technical_language>

Target:
public PlanNode visitTableFinish(TableFinishNode node, RewriteContext<Void> context) { Optional<DeleteNode> delete = findNode(node.getSource(), DeleteNode.class); if (!delete.isPresent()) { return context.defaultRewrite(node); } Optional<TableScanNode> tableScan = findNode(delete.get().getSource(), TableScanNode.class); if (!tableScan.isPresent()) { return context.defaultRewrite(node); } TableScanNode tableScanNode = tableScan.get(); if (!metadata.supportsMetadataDelete(session, tableScanNode.getTable())) { return context.defaultRewrite(node); } return new MetadataDeleteNode( idAllocator.getNextId(), new DeleteHandle(tableScanNode.getTable(), delete.get().getTarget().getSchemaTableName()), Iterables.getOnlyElement(node.getOutputSymbols())); }
Source:
<code>public void serialize(JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { <START> jgen.setCharacterEscapes(JsonpCharacterEscapes.instance()); <END> jgen.writeRaw(_function); jgen.writeRaw('('); if (_value == null) { provider.defaultSerializeNull(jgen); } else if (_serializationType != null) { provider.findTypedValueSerializer(_serializationType, true, null).serialize(_value, jgen, provider); } else { Class<?> cls = _value.getClass(); provider.findTypedValueSerializer(cls, true, null).serialize(_value, jgen, provider); } jgen.writeRaw(')'); }</code><technical_language>This is safe: generator existing escapes user specified, this replace them</technical_language>

Target:
public void serialize(JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { CharacterEscapes currentCharacterEscapes = jgen.getCharacterEscapes(); if (currentCharacterEscapes == null) { jgen.setCharacterEscapes(JsonpCharacterEscapes.instance()); } try { jgen.writeRaw(_function); jgen.writeRaw('('); if (_value == null) { provider.defaultSerializeNull(jgen); } else if (_serializationType != null) { provider.findTypedValueSerializer(_serializationType, true, null).serialize(_value, jgen, provider); } else { Class<?> cls = _value.getClass(); provider.findTypedValueSerializer(cls, true, null).serialize(_value, jgen, provider); } jgen.writeRaw(')'); } finally { jgen.setCharacterEscapes(currentCharacterEscapes); } }