auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static BlobProperties getBlobPropertiesFromStream(DataInputStream stream) throws IOException { long version = stream.readShort(); BlobProperties toReturn; <START> if (version == Version1 || version == Version2) { <END> long ttl = stream.readLong(); boolean isPrivate = stream.readByte() == 1 ? true : false; long creationTime = stream.readLong(); long blobSize = stream.readLong(); String contentType = Utils.readIntString(stream); String ownerId = Utils.readIntString(stream); String serviceId = Utils.readIntString(stream); if (version == Version1) { toReturn = new SystemMetadata(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime); } else { short accountId = stream.readShort(); short containerId = stream.readShort(); short issuerAccountId = stream.readShort(); toReturn = new SystemMetadata(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime, accountId, containerId, issuerAccountId); } } else { throw new IllegalArgumentException("stream has unknown blob property version " + version); } return toReturn; }</code><technical_language>this is more readable a switch-case</technical_language>

Target:
public static BlobProperties getBlobPropertiesFromStream(DataInputStream stream) throws IOException { short version = stream.readShort(); BlobProperties toReturn; long ttl = stream.readLong(); boolean isPrivate = stream.readByte() == 1; long creationTime = stream.readLong(); long blobSize = stream.readLong(); String contentType = Utils.readIntString(stream); String ownerId = Utils.readIntString(stream); String serviceId = Utils.readIntString(stream); switch (version) { case Version1: toReturn = new BlobProperties(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime); break; case Version2: short accountId = stream.readShort(); short containerId = stream.readShort(); short issuerAccountId = stream.readShort(); toReturn = new BlobProperties(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime, accountId, containerId, issuerAccountId); break; default: throw new IllegalArgumentException("stream has unknown blob property version " + version); } return toReturn; }
Source:
<code>public Optional<Profession> getProfession() { <START> return profession; <END> }</code><technical_language>this</technical_language>

Target:
private Optional<Profession> getProfession() { return this.profession; }
Source:
<code>private boolean handleIntent(Intent intent) { Uri data = intent.getData(); if (data != null && data.getScheme().equals(CALLBACK_URI.getScheme()) && data.getHost().equals(CALLBACK_URI.getHost())) { Uri uri = Uri.parse(TOKEN_URL) .buildUpon() .appendQueryParameter(PARAM_CLIENT_ID, BuildConfig.CLIENT_ID) .appendQueryParameter(PARAM_CLIENT_SECRET, BuildConfig.CLIENT_SECRET) .appendQueryParameter(PARAM_CODE, data.getQueryParameter(PARAM_CODE)) .build(); new FetchTokenTask(uri).schedule(); return true; } <START> super.onNewIntent(intent); <END> return false; }</code><technical_language>This line removed, right? super method is called AFAICT</technical_language>

Target:
private boolean handleIntent(Intent intent) { Uri data = intent.getData(); if (data != null && data.getScheme().equals(CALLBACK_URI.getScheme()) && data.getHost().equals(CALLBACK_URI.getHost())) { Uri uri = Uri.parse(TOKEN_URL) .buildUpon() .appendQueryParameter(PARAM_CLIENT_ID, BuildConfig.CLIENT_ID) .appendQueryParameter(PARAM_CLIENT_SECRET, BuildConfig.CLIENT_SECRET) .appendQueryParameter(PARAM_CODE, data.getQueryParameter(PARAM_CODE)) .build(); new FetchTokenTask(uri).schedule(); return true; } return false; }
Source:
<code>public synchronized void start() { if (state != ACTIVATED) { return; } state = STARTING; manager.sendEvent(new ComponentEvent(ComponentEvent.STARTING_COMPONENT, this)); try { if (component != null) { Object ci = component.getInstance(); if (ci instanceof Component) { ((Component) ci).start(component); } } <START> log.trace("Component started: {}", name); <END> state = STARTED; manager.sendEvent(new ComponentEvent(ComponentEvent.COMPONENT_STARTED, this)); } catch (RuntimeException e) { log.error(String.format("Component %s notification of application started failed: %s", component.getName(), e.getMessage()), e); state = START_FAILURE; } }</code><technical_language>debug please</technical_language>

Target:
public synchronized void start() { if (state != ACTIVATED) { return; } state = STARTING; manager.sendEvent(new ComponentEvent(ComponentEvent.STARTING_COMPONENT, this)); try { if (component != null) { Object ci = component.getInstance(); if (ci instanceof Component) { ((Component) ci).start(component); } } log.debug("Component started: {}", name); state = STARTED; manager.sendEvent(new ComponentEvent(ComponentEvent.COMPONENT_STARTED, this)); } catch (RuntimeException e) { log.error(String.format("Component %s notification of application started failed: %s", component.getName(), e.getMessage()), e); state = START_FAILURE; } }
Source:
<code>public void handleDataDeleted(String dataPath) throws Exception { <START> throw new SamzaException("version update path has been deleted!."); <END> }</code><technical_language>[minor] typo, want period end</technical_language>

Target:
public void handleDataDeleted(String dataPath) throws Exception { throw new SamzaException("version update path has been deleted!"); }
Source:
<code><START> public CoAPConnectedLightingDiscovery() throws IllegalArgumentException { <END> super(SUPPORTED_THING_TYPES_UIDS, 10); }</code><technical_language>need declare unchecked exception here</technical_language>

Target:
public CoAPConnectedLightingDiscovery() { super(SUPPORTED_THING_TYPES_UIDS, 10); }
Source:
<code>protected Object visitBindExpression(BindExpression node, Object context) { List<Object> values = node.getValues().stream() .map(value -> process(value, context)) .collect(toImmutableList()); Object function = process(node.getFunction(), context); if (hasUnresolvedValue(values) || hasUnresolvedValue(function)) { ImmutableList.Builder builder = ImmutableList.builder(); for (int i = 0; i < values.size(); i++) { <START> builder.add(toExpression(values.get(i), expressionTypes.get(node.getValues().get(i)))); <END> } return new BindExpression( builder.build(), toExpression(function, expressionTypes.get(node.getFunction()))); } return MethodHandles.insertArguments((MethodHandle) function, 0, values.toArray()); }</code><technical_language>ImmutableList.Builder<...>. a warning IntelliJ passed builder.build() newExpression</technical_language>

Target:
protected Object visitBindExpression(BindExpression node, Object context) { List<Object> values = node.getValues().stream() .map(value -> process(value, context)) .collect(toImmutableList()); Object function = process(node.getFunction(), context); if (hasUnresolvedValue(values) || hasUnresolvedValue(function)) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (int i = 0; i < values.size(); i++) { builder.add(toExpression(values.get(i), type(node.getValues().get(i)))); } return new BindExpression( builder.build(), toExpression(function, type(node.getFunction()))); } return MethodHandles.insertArguments((MethodHandle) function, 0, values.toArray()); }
Source:
<code>public QueueQueryImpl(final boolean durable, final boolean temporary, final int consumerCount, final long messageCount, final SimpleString filterString, final SimpleString address, final SimpleString name, <START> final boolean exists, <END> final boolean autoCreateQueues) { this(durable, temporary, consumerCount, messageCount, filterString, address, name, exists, autoCreateQueues, -1, false, false, RoutingType.MULTICAST, null, null, null, null, null, null, null, null, null, null, null, null, null, null); }</code><technical_language>wont this a breaking change removing api's if is CORE api directly? I appreciate hidden for JMS users</technical_language>

Target:
public QueueQueryImpl(final boolean durable, final boolean temporary, final int consumerCount, final long messageCount, final SimpleString filterString, final SimpleString address, final SimpleString name, final boolean exists, final boolean autoCreateQueues) { this(durable, temporary, consumerCount, messageCount, filterString, address, name, exists, autoCreateQueues, -1, false, false, RoutingType.MULTICAST); }
Source:
<code>protected void updateStatsRow(Object rowKey, Object[] rowValues) { long leader; List<Long> sites = new ArrayList<Long>(); if (rowKey.equals(MpInitiator.MP_INIT_PID)) { leader = getHSIdForMultiPartitionInitiator(); sites.add(leader); } else { <START> if (!m_iv2Masters.pointInTimeCache().containsKey(rowKey)) { <END> return; } leader = m_iv2Masters.pointInTimeCache().get(rowKey); sites.addAll(getReplicasForPartition((Integer)rowKey)); } rowValues[columnNameToIndex.get("Partition")] = rowKey; rowValues[columnNameToIndex.get("Sites")] = CoreUtils.hsIdCollectionToString(sites); rowValues[columnNameToIndex.get("Leader")] = CoreUtils.hsIdToString(leader); }</code><technical_language>early return checking leader == null</technical_language>

Target:
protected void updateStatsRow(Object rowKey, Object[] rowValues) { long leader; List<Long> sites = new ArrayList<Long>(); if (rowKey.equals(MpInitiator.MP_INIT_PID)) { leader = getHSIdForMultiPartitionInitiator(); sites.add(leader); } else { Long leaderInCache = m_iv2Masters.pointInTimeCache().get(rowKey); if (leaderInCache == null) { return; } leader = leaderInCache; sites.addAll(getReplicasForPartition((Integer)rowKey)); } rowValues[columnNameToIndex.get("Partition")] = rowKey; rowValues[columnNameToIndex.get("Sites")] = CoreUtils.hsIdCollectionToString(sites); rowValues[columnNameToIndex.get("Leader")] = CoreUtils.hsIdToString(leader); }
Source:
<code>public TaskCounts getTaskCounts(String jobId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { JobGetTaskCountsOptions options = new JobGetTaskCountsOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); <START> return this.parentBatchClient.protocolLayer().jobs().getTaskCounts(jobId, options).taskCounts(); <END> }</code><technical_language>This change return types TaskCountsResult model another method added exposing taskSlotCounts</technical_language>

Target:
public TaskCounts getTaskCounts(String jobId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { return getTaskCountsResult(jobId, additionalBehaviors).taskCounts(); }
Source:
<code>public void throwsCatchedException() { new Runnable() { @Override @Parallel(threads = ParallelizerTest.COUNT) public void run() { throw new IllegalArgumentException(); } } <START> .run(); <END> }</code><technical_language>here, leave previous line</technical_language>

Target:
public void throwsCatchedException() { new Runnable() { @Override @Parallel(threads = Tv.TEN) public void run() { throw new IllegalArgumentException(); } } .run(); }
Source:
<code>public StreamlineEvent entity(Result result) { Map<String, Object> fieldsAndValues = new HashMap<>(); for(Map.Entry<byte[], byte[]> entry: result.getFamilyMap(CF_FIELDS).entrySet()) { fieldsAndValues.put(Bytes.toString(entry.getKey()), Bytes.toString(entry.getValue())); } String dataSourceId = Bytes.toString(result.getFamilyMap(CF_DATASOURCE_ID).firstEntry().getKey()); <START> return StreamlineEventImpl.builder().fieldsAndValues(fieldsAndValues).dataSourceId(dataSourceId).build(); <END> }</code><technical_language>Ok return event a ID queried for now. Other option is add a wrapper event takes returns "id" delegates other calls underlying event</technical_language>

Target:
public StreamlineEvent entity(Result result) { String id = Bytes.toString(result.getRow()); Map<String, Object> fieldsAndValues = new HashMap<>(); for(Map.Entry<byte[], byte[]> entry: result.getFamilyMap(CF_FIELDS).entrySet()) { fieldsAndValues.put(Bytes.toString(entry.getKey()), Bytes.toString(entry.getValue())); } String dataSourceId = Bytes.toString(result.getFamilyMap(CF_DATASOURCE_ID).firstEntry().getKey()); StreamlineEventImpl event = StreamlineEventImpl.builder().fieldsAndValues(fieldsAndValues).dataSourceId(dataSourceId).build(); return new StreamlineEventWithID(event, id); }
Source:
<code>private void resolveParents(ClassDef classDef) { Symbol symbol = classDef.name().symbol(); if (symbol == null || !Symbol.Kind.CLASS.equals(symbol.kind())) { return; } ClassSymbolImpl classSymbol = (ClassSymbolImpl) symbol; <START> if (hasMultipleBindingUsages(classSymbol)) { <END> classSymbol.setKind(Symbol.Kind.OTHER); return; } ArgList argList = classDef.args(); classSymbol.hasUnresolvedParents = false; if (argList == null) { return; } for (Argument argument : argList.arguments()) { if (!argument.is(Kind.REGULAR_ARGUMENT) || !(((RegularArgument) argument).expression() instanceof HasSymbol)) { classSymbol.hasUnresolvedParents = true; return; } Symbol parentSymbol = ((HasSymbol) ((RegularArgument) argument).expression()).symbol(); if (parentSymbol == null) { classSymbol.hasUnresolvedParents = true; return; } if (hasMultipleBindingUsages(parentSymbol)) { classSymbol.hasUnresolvedParents = true; return; } if (parentSymbol.fullyQualifiedName() != null && BuiltinSymbols.all().contains(parentSymbol.fullyQualifiedName())) { if (!classSymbol.parents().contains(parentSymbol)) { classSymbol.addParent(parentSymbol); } continue; } if (!Symbol.Kind.CLASS.equals(parentSymbol.kind())) { classSymbol.hasUnresolvedParents = true; return; } classSymbol.addParent(parentSymbol); } }</code><technical_language>I suggest change kind of a classSymbol OTHER Scope#addBindingUsage. add code: java if (symbol.kind() != Symbol.Kind.OTHER) { symbol.setKind(Symbol.Kind.OTHER); }</technical_language>

Target:
private void resolveParents(ClassDef classDef) { Symbol symbol = classDef.name().symbol(); if (symbol == null || !Symbol.Kind.CLASS.equals(symbol.kind())) { return; } ClassSymbolImpl classSymbol = (ClassSymbolImpl) symbol; ArgList argList = classDef.args(); classSymbol.setHasUnresolvedParents(false); if (argList == null) { return; } for (Argument argument : argList.arguments()) { if (!argument.is(Kind.REGULAR_ARGUMENT) || !(((RegularArgument) argument).expression() instanceof HasSymbol)) { classSymbol.setHasUnresolvedParents(true); return; } Symbol parentSymbol = ((HasSymbol) ((RegularArgument) argument).expression()).symbol(); if (parentSymbol == null) { classSymbol.setHasUnresolvedParents(true); return; } if (BuiltinSymbols.all().contains(parentSymbol.fullyQualifiedName())) { classSymbol.addParent(parentSymbol); continue; } if (!Symbol.Kind.CLASS.equals(parentSymbol.kind())) { classSymbol.setHasUnresolvedParents(true); return; } classSymbol.addParent(parentSymbol); } }
Source:
<code>private Future<Void> initializeCredentials(Future<Credentials> credentialsFuture) throws IOException { final Credentials credentials = get(credentialsFuture, "Cloud not initialize credentials"); Future<Void> clientAuthInterceptorFuture = null; if (credentials != null) { if (credentials instanceof OAuth2Credentials) { final RefreshingOAuth2CredentialsInterceptor oauth2Interceptor = new RefreshingOAuth2CredentialsInterceptor(batchPool, (OAuth2Credentials) credentials); clientAuthInterceptorFuture = batchPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { oauth2Interceptor.syncRefresh(); return null; } }); this.clientAuthInterceptor = oauth2Interceptor; } else { this.clientAuthInterceptor = new ClientAuthInterceptor(credentials, batchPool); <START> clientAuthInterceptorFuture = batchPool.submit(new Callable<Void>() { <END> @Override public Void call() throws Exception { credentials.refresh(); return null; } }); } } else { this.clientAuthInterceptor = null; } return clientAuthInterceptorFuture; }</code><technical_language>I if call clientAuthInterceptorFuture, is refresh credentials</technical_language>

Target:
private Future<Void> initializeCredentials(Future<Credentials> credentialsFuture) throws IOException { final Credentials credentials = get(credentialsFuture, "Cloud not initialize credentials"); Future<Void> credentialRefreshFuture = null; if (credentials != null) { if (credentials instanceof OAuth2Credentials) { final RefreshingOAuth2CredentialsInterceptor oauth2Interceptor = new RefreshingOAuth2CredentialsInterceptor(batchPool, (OAuth2Credentials) credentials); credentialRefreshFuture = batchPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { oauth2Interceptor.syncRefresh(); return null; } }); this.clientAuthInterceptor = oauth2Interceptor; } else { this.clientAuthInterceptor = new ClientAuthInterceptor(credentials, batchPool); credentialRefreshFuture = batchPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { credentials.refresh(); return null; } }); } } else { this.clientAuthInterceptor = null; } return credentialRefreshFuture; }
Source:
<code>private @Nullable Index checkIndexPresence(Index curIdx) throws IgniteCheckedException { IndexColumn[] curColumns = curIdx.getIndexColumns(); Index registredIdx = null; for (Index idx : idxs) { if (!(idx instanceof H2TreeIndex)) continue; if (F.eq(curIdx.getName(), idx.getName())) throw new IgniteCheckedException("Index already exists: " + idx.getName()); IndexColumn[] idxColumns = idx.getIndexColumns(); <START> if (idxColumns.length == curColumns.length) { <END> boolean copy = true; for (IndexColumn idxCol : idxColumns) { registredIdx = null; for (IndexColumn curCol : curColumns) { if (F.eq(aliasNameTransformer(idxCol), aliasNameTransformer(curCol)) && idxCol.sortType == curCol.sortType) registredIdx = idx; } if (registredIdx == null) { copy = false; break; } } if (copy) return registredIdx; } } return null; }</code><technical_language>skip check if lengths diffrent, due special _KEY column for composite key columns example: _KEY = ID1, ID2 index IDX_1(VAL, _KEY) index IDX_2(VAL, ID1, ID2) IDX_1 eqauls IDX_2</technical_language>

Target:
private @Nullable Index checkIndexPresence(Index curIdx) throws IgniteCheckedException { IndexColumn[] curColumns = curIdx.getIndexColumns(); Index registredIdx = null; for (Index idx : idxs) { if (!(idx instanceof H2TreeIndex)) continue; if (F.eq(curIdx.getName(), idx.getName())) throw new IgniteCheckedException("Index already exists: " + idx.getName()); IndexColumn[] idxColumns = idx.getIndexColumns(); for (int i = 0; i < Math.min(idxColumns.length, curColumns.length); ++i) { IndexColumn idxCol = idxColumns[i]; IndexColumn curCol = curColumns[i]; if (curCol.column.getColumnId() == 0 && registredIdx != null) continue; if (H2Utils.equals(idxCol, curCol) && idxCol.sortType == curCol.sortType) registredIdx = idx; else { registredIdx = null; break; } } if (registredIdx != null) return registredIdx; } return null; }
Source:
<code>private List<SignedCertificateTimestamp> getSCTsFromSCTList(byte[] data, SignedCertificateTimestamp.Origin origin) { if (data == null) { return Collections.EMPTY_LIST; } byte[][] sctList; try { sctList = Serialization.readList(data, <START> 2, 2); <END> } catch (SerializationException e) { return Collections.EMPTY_LIST; } List<SignedCertificateTimestamp> scts = new ArrayList(); for (byte[] encodedSCT: sctList) { try { SignedCertificateTimestamp sct = SignedCertificateTimestamp.decode(encodedSCT, origin); scts.add(sct); } catch (SerializationException e) { } } return scts; }</code><technical_language>do magic numbers stand for? constants instead</technical_language>

Target:
private List<SignedCertificateTimestamp> getSCTsFromSCTList(byte[] data, SignedCertificateTimestamp.Origin origin) { if (data == null) { return Collections.EMPTY_LIST; } byte[][] sctList; try { sctList = Serialization.readList(data, CTConstants.SCT_LIST_LENGTH_BYTES, CTConstants.SERIALIZED_SCT_LENGTH_BYTES); } catch (SerializationException e) { return Collections.EMPTY_LIST; } List<SignedCertificateTimestamp> scts = new ArrayList(); for (byte[] encodedSCT: sctList) { try { SignedCertificateTimestamp sct = SignedCertificateTimestamp.decode(encodedSCT, origin); scts.add(sct); } catch (SerializationException e) { } } return scts; }
Source:
<code><START> public CoreClusterMember leaderTx( BiConsumer<CoreGraphDatabase,Transaction> op, int timeout, TimeUnit timeUnit ) <END> throws Exception { ThrowingSupplier<CoreClusterMember,Exception> supplier = () -> { CoreClusterMember member = awaitLeader( timeout, timeUnit ); CoreGraphDatabase db = member.database(); if ( db == null ) { throw new DatabaseShutdownException(); } try ( Transaction tx = db.beginTx() ) { op.accept( db, tx ); return member; } catch ( Throwable e ) { if ( isTransientFailure( e ) ) { System.err.println( "Transient failure in leader transaction, trying again." ); e.printStackTrace(); return null; } else { throw e; } } }; return awaitEx( supplier, notNull()::test, timeout, timeUnit ); }</code><technical_language>Unnecessary this public</technical_language>

Target:
private CoreClusterMember leaderTx( BiConsumer<CoreGraphDatabase,Transaction> op, int timeout, TimeUnit timeUnit ) throws Exception { ThrowingSupplier<CoreClusterMember,Exception> supplier = () -> { CoreClusterMember member = awaitLeader( timeout, timeUnit ); CoreGraphDatabase db = member.database(); if ( db == null ) { throw new DatabaseShutdownException(); } try ( Transaction tx = db.beginTx() ) { op.accept( db, tx ); return member; } catch ( Throwable e ) { if ( isTransientFailure( e ) ) { System.err.println( "Transient failure in leader transaction, trying again." ); e.printStackTrace(); return null; } else { throw e; } } }; return awaitEx( supplier, notNull()::test, timeout, timeUnit ); }
Source:
<code>public Map<VariableReferenceExpression, VariableReferenceExpression> visitProject(ProjectNode node, Set<VariableReferenceExpression> lookupVariables) { <START> Map<VariableReferenceExpression, VariableReferenceExpression> directVariableTranslationOutputMap = Maps.transformEntries( <END> Maps.filterValues( node.getAssignments().getMap(), IndexKeyTracer::isVariable), this::extractVariable); Map<VariableReferenceExpression, VariableReferenceExpression> outputToSourceMap = lookupVariables.stream() .filter(directVariableTranslationOutputMap.keySet()::contains) .collect(toImmutableMap(identity(), variable -> directVariableTranslationOutputMap.get(variable))); checkState(!outputToSourceMap.isEmpty(), "No lookup variables were able to pass through the projection"); Map<VariableReferenceExpression, VariableReferenceExpression> sourceToIndexMap = node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values())); Map<VariableReferenceExpression, VariableReferenceExpression> outputToIndexMap = Maps.transformValues(Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())), Functions.forMap(sourceToIndexMap)); return ImmutableMap.copyOf(outputToIndexMap); }</code><technical_language>nit, need break lines java Map<VariableReferenceExpression, VariableReferenceExpression> directVariableTranslationOutputMap = Maps.transformEntries( Maps.filterValues(node.getAssignments().getMap(), IndexKeyTracer::isVariable), Visitor::extractVariable);</technical_language>

Target:
public Map<VariableReferenceExpression, VariableReferenceExpression> visitProject(ProjectNode node, Set<VariableReferenceExpression> lookupVariables) { Map<VariableReferenceExpression, VariableReferenceExpression> directVariableTranslationOutputMap = Maps.transformEntries( Maps.filterValues(node.getAssignments().getMap(), IndexKeyTracer::isVariable), IndexKeyTracer::extractVariable); Map<VariableReferenceExpression, VariableReferenceExpression> outputToSourceMap = lookupVariables.stream() .filter(directVariableTranslationOutputMap.keySet()::contains) .collect(toImmutableMap(identity(), variable -> directVariableTranslationOutputMap.get(variable))); checkState(!outputToSourceMap.isEmpty(), "No lookup variables were able to pass through the projection"); Map<VariableReferenceExpression, VariableReferenceExpression> sourceToIndexMap = node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values())); Map<VariableReferenceExpression, VariableReferenceExpression> outputToIndexMap = Maps.transformValues(Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())), Functions.forMap(sourceToIndexMap)); return ImmutableMap.copyOf(outputToIndexMap); }
Source:
<code>public void run(IAction action) { System.out.println("**** BEGIN DUMP JOB MANAGER INFORMATION ****"); IJobManager <START> jobManager = <END> Job.getJobManager(); Job[] jobs = jobManager.find(null); for (int i = 0; i < jobs.length; i++) { System.out.println("" + jobs[i].getClass().getName() + " state: " + JobManager.printState(jobs[i].getState())); } System.out.println("**** END DUMP JOB MANAGER INFORMATION ****"); }</code><technical_language>simply replace Platform Job</technical_language>

Target:
public void run(IAction action) { System.out.println("**** BEGIN DUMP JOB MANAGER INFORMATION ****"); Job[] jobs = Job.getJobManager().find(null); for (int i = 0; i < jobs.length; i++) { System.out.println("" + jobs[i].getClass().getName() + " state: " + JobManager.printState(jobs[i].getState())); } System.out.println("**** END DUMP JOB MANAGER INFORMATION ****"); }
Source:
<code><START> public int[] getAdnRecordsSize(int efid) { <END> if (DBG) logd("getAdnRecordsSize: efid=" + efid); synchronized(mLock) { checkThread(); recordSize = new int[3]; Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE); ((RuimFileHandler)phone.getIccFileHandler()).getEFLinearRecordSize(efid, response); try { mLock.wait(); } catch (InterruptedException e) { logd("interrupted while trying to load from the RUIM"); } } return recordSize; }</code><technical_language>I this routine promoted base class</technical_language>

Target:
public int[] getAdnRecordsSize(int efid) { if (DBG) logd("getAdnRecordsSize: efid=" + efid); synchronized(mLock) { checkThread(); recordSize = new int[3]; Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE); phone.getIccFileHandler().getEFLinearRecordSize(efid, response); try { mLock.wait(); } catch (InterruptedException e) { logd("interrupted while trying to load from the RUIM"); } } return recordSize; }
Source:
<code>public void testUpdateVcfSequenceDictionary(final String outputFileName) throws FileNotFoundException { final File input = new File(TEST_DATA_PATH, "vcfFormatTest.vcf"); final File samSequenceDictionaryVcf = new File(TEST_DATA_PATH, "vcfFormatTest.bad_dict.vcf"); File outputFile = new File(outputFileName); outputFile.deleteOnExit(); <START> if ( outputFileName.equals(UpdateVcfSequenceDictionary.STD_OUT) ) { <END> System.setOut(new PrintStream(STD_OUT_FILE)); } final UpdateVcfSequenceDictionary updateVcfSequenceDictionary = new UpdateVcfSequenceDictionary(); updateVcfSequenceDictionary.INPUT = input; updateVcfSequenceDictionary.SEQUENCE_DICTIONARY = samSequenceDictionaryVcf; updateVcfSequenceDictionary.OUTPUT = outputFile; Assert.assertEquals(updateVcfSequenceDictionary.instanceMain(new String[0]), 0); if ( outputFileName.equals(UpdateVcfSequenceDictionary.STD_OUT) ) { outputFile = STD_OUT_FILE; } IOUtil.assertFilesEqual(samSequenceDictionaryVcf, outputFile); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(input).size(), 84); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(samSequenceDictionaryVcf).size(), 82); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(outputFile).size(), 82); }</code><technical_language>a local variable for STD_OUT</technical_language>

Target:
public void testUpdateVcfSequenceDictionary(final String outputFileName) throws IOException, NoSuchFieldException, IllegalAccessException { File input = new File(TEST_DATA_PATH, "vcfFormatTest.vcf"); final File samSequenceDictionaryVcf = new File(TEST_DATA_PATH, "vcfFormatTest.bad_dict.vcf"); File outputFile = new File(outputFileName); outputFile.deleteOnExit(); final UpdateVcfSequenceDictionary updateVcfSequenceDictionary = new UpdateVcfSequenceDictionary(); if (outputFileName.equals(STD_OUT_NAME)) { final FileOutputStream stream = new FileOutputStream(STD_OUT_FILE); final Field fdField = FileDescriptor.class.getDeclaredField("fd"); fdField.setAccessible(true); updateVcfSequenceDictionary.OUTPUT = new File("/dev/fd/" + fdField.getInt(stream.getFD())); } else { final FileOutputStream stream = null; updateVcfSequenceDictionary.OUTPUT = outputFile; } updateVcfSequenceDictionary.INPUT = input; updateVcfSequenceDictionary.SEQUENCE_DICTIONARY = samSequenceDictionaryVcf; Assert.assertEquals(updateVcfSequenceDictionary.instanceMain(new String[0]), 0); if (outputFileName.equals(STD_OUT_NAME)) { outputFile = STD_OUT_FILE; } IOUtil.assertFilesEqual(samSequenceDictionaryVcf, outputFile); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(input).size(), 84); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(samSequenceDictionaryVcf).size(), 82); Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(outputFile).size(), 82); }
Source:
<code>public File getInfoDir() { if (infoDir == null) { StorageLocationConfig storageLocation = locations.get(0); if (storageLocation != null) { infoDir = new File(storageLocation.getPath(), "info_dir"); <START> } <END> } return infoDir; }</code><technical_language>This method throw IndexOutOfBoundsException if locations is empty (due .get(0)) NPE call site if locations is non-empty, a null (since returns null, callers expecting null). Instead, I suggest detecting conditions throwing a worded error message "You segment cache locations defined. Please configure druid.segmentCache.locations more locations."</technical_language>

Target:
public File getInfoDir() { if (infoDir == null) { if (locations == null || locations.size() == 0) { throw new ISE("You have no segment cache locations defined. Please configure druid.segmentCache.locations to use one or more locations."); } infoDir = new File(locations.get(0).getPath(), "info_dir"); } return infoDir; }
Source:
<code>public void testGetAcceptableTokens() { final MatchXpathCheck matchXpathCheck = new MatchXpathCheck(); <START> assertThat("Expected empty array", <END> matchXpathCheck.getAcceptableTokens(), is(CommonUtil.EMPTY_INT_ARRAY)); }</code><technical_language>ex -> ignored. This is common naming convention for cases. Another (preferred) option is assert exception message</technical_language>

Target:
public void testGetAcceptableTokens() { final MatchXpathCheck matchXpathCheck = new MatchXpathCheck(); assertWithMessage("Expected empty array") .that(matchXpathCheck.getAcceptableTokens()) .isEmpty(); }
Source:
<code>public void testAllDomainsWithinThresholdsOneLacking() { domain1.getStorageDynamicData().setAvailableDiskSize(15); domain2.getStorageDynamicData().setAvailableDiskSize(7); ValidationResult result = validator.allDomainsWithinThresholds(); <START> assertFalse("Both domains should not be withing thresholds", result.isValid()); <END> assertEquals("Wrong validation error", VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN, result.getMessage()); }</code><technical_language>consider change message domain2 enough disk size pass threshold check</technical_language>

Target:
public void testAllDomainsWithinThresholdsOneLacking() { domain1.getStorageDynamicData().setAvailableDiskSize(15); domain2.getStorageDynamicData().setAvailableDiskSize(7); ValidationResult result = validator.allDomainsWithinThresholds(); assertFalse("domain2 should not be within thresholds", result.isValid()); assertEquals("Wrong validation error", VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN, result.getMessage()); }
Source:
<code>public RuntimeWorkspaceDto getRuntimeWorkspaceById(@PathParam("id") String id) throws ServerException, BadRequestException, NotFoundException { <START> return asRuntimeWorkspaceDto(workspaceManager.getRuntimeWorkspace(id)); <END> }</code><technical_language>DtoConverter here</technical_language>

Target:
public RuntimeWorkspaceDto getRuntimeWorkspaceById(@PathParam("id") String id) throws ServerException, BadRequestException, NotFoundException { return asDto(workspaceManager.getRuntimeWorkspace(id)); }
Source:
<code>public void archive(RegionServerServices services) throws IOException{ if (getNumRolledLogFiles() < 1) { return; } Map.Entry<Path, WalProps> firstWALEntry = this.walFile2Props.firstEntry(); Map<byte[], List<byte[]>> regions = this.sequenceIdAccounting.findLower(firstWALEntry.getValue().encodedName2HighestSequenceId); if (regions != null) { for (Map.Entry<byte[], List<byte[]>> entry : regions.entrySet()) { String encodedRegionName = Bytes.toString(entry.getKey()); HRegion r = (HRegion) services.getRegion(encodedRegionName); if (r == null) { LOG.warn("Failed to flush of when archive manually, because it is not online on us", encodedRegionName); return; } r.flushcache(entry.getValue(), false, FlushLifeCycleTracker.DUMMY); } } this.totalLogSize.addAndGet(-firstWALEntry.getValue().logSize); <START> moveLogFileToArchiveDir(firstWALEntry.getKey()); <END> this.walFile2Props.remove(firstWALEntry.getKey()); }</code><technical_language>if IOException is thrown this call ? totalLogSize correct</technical_language>

Target:
public void archive(RegionServerServices services) throws IOException{ if (getNumRolledLogFiles() < 1) { return; } Map.Entry<Path, WalProps> firstWALEntry = this.walFile2Props.firstEntry(); Map<byte[], List<byte[]>> regions = this.sequenceIdAccounting.findLower(firstWALEntry.getValue().encodedName2HighestSequenceId); if (regions != null) { for (Map.Entry<byte[], List<byte[]>> entry : regions.entrySet()) { String encodedRegionName = Bytes.toString(entry.getKey()); HRegion r = (HRegion) services.getRegion(encodedRegionName); if (r == null) { throw new RegionException("Failed to flush of " + encodedRegionName + " when archive manually, because it is not online on rs"); } r.flushcache(entry.getValue(), false, FlushLifeCycleTracker.DUMMY); } } moveLogFileToArchiveDir(firstWALEntry.getKey()); this.totalLogSize.addAndGet(-firstWALEntry.getValue().logSize); this.walFile2Props.remove(firstWALEntry.getKey()); }
Source:
<code>public void testRetryPostEnabled() throws Exception { enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); ClientResponse response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); <START> response.close(); <END> }</code><technical_language>A try/finally here</technical_language>

Target:
public void testRetryPostEnabled() throws Exception { enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); ClientResponse response = null; try { response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); } finally { if (response != null) { response.close(); } } }
Source:
<code>public void scanHttpRequestSend(HttpMessage msg, int id) { TreeSet<HtmlParameter> urlParams = msg.getUrlParams(); String uri = msg.getRequestHeader().getURI().toString(); boolean found = false; OptionsParam options = Model.getSingleton().getOptionsParam(); HttpSessionsParam sessionOptions = options.getParamSet(HttpSessionsParam.class); List<String> sessionIds = Collections.emptyList(); if (sessionOptions != null) { sessionIds = sessionOptions.getDefaultTokensEnabled(); } if (!urlParams.isEmpty()) { for (HtmlParameter param : urlParams) { if (sessionIds.contains(param.getName().toLowerCase(Locale.ROOT))) { if (param.getValue().length() > SESSION_TOKEN_MIN_LENGTH) { Alert alert = new Alert( getPluginId(), getRisk(), Alert.CONFIDENCE_HIGH, getName()); alert.setDetail( getDescription(), uri, param.getName(), "", "", getSolution(), getReference(), param.getValue(), getCweId(), getWascId(), msg); parent.raiseAlert(id, alert); found = true; } } } } if (!found && msg.getRequestHeader().getURI().getEscapedPath() != null) { Matcher jsessMatcher = null; <START> String path = ""; <END> try { path = msg.getRequestHeader().getURI().getPath().toLowerCase(); jsessMatcher = PATHSESSIONIDPATTERN.matcher(path); } catch (URIException e) { e.printStackTrace(); } if (jsessMatcher != null && jsessMatcher.find()) { Alert alert = new Alert(getPluginId(), getRisk(), Alert.CONFIDENCE_HIGH, getName()); alert.setDetail( getDescription(), uri, "", "", "", getSolution(), getReference(), jsessMatcher.group(), getCweId(), getWascId(), msg); parent.raiseAlert(id, alert); found = true; } } if (found) { try { checkSessionIDExposureTo3rdParty(msg, id); } catch (URIException e) { } } }</code><technical_language>This declared try block, outside</technical_language>

Target:
public void scanHttpRequestSend(HttpMessage msg, int id) { }
Source:
<code>public List<String> normalize(String... strings) { final Map<String, Pair<String, String>> <START> stringParts = <END> Arrays.stream(strings) .filter(Objects::nonNull) .collect(Collectors.toMap(Function.identity(), this::decompose, (value, ignore) -> value)); final int maxNumericSuffixLength = stringParts.values() .stream() .filter(Objects::nonNull) .collect(Collectors.summarizingInt(pair -> pair.getSecond().length())) .getMax(); return Arrays.stream(strings) .map(str -> compose(str, stringParts, maxNumericSuffixLength)) .collect(Collectors.toList()); }</code><technical_language>this is equivalent of naming this variable simply 'a' in 1960. name explanatory all. Name is key is of this map</technical_language>

Target:
public List<String> normalize(String... strings) { final Map<String, Pair<String, String>> stringParts = new HashMap<>(strings.length); Arrays.stream(strings) .filter(Objects::nonNull) .forEach(str -> stringParts.put(str, decompose(str))); final int maxNumericSuffixLength = stringParts.values() .stream() .filter(Objects::nonNull) .collect(Collectors.summarizingInt(pair -> pair.getSecond().length())) .getMax(); return Arrays.stream(strings) .map(str -> compose(str, stringParts, maxNumericSuffixLength)) .collect(Collectors.toList()); }
Source:
<code>protected void calculateFilters() { Map<String, String> values = getValues(); Collection<MarkerFieldFilter> filters = new ArrayList<>(); for (MarkerField <START> field : <END> generator.getVisibleFields()) { MarkerFieldFilter fieldFilter = MarkerSupportInternalUtilities.generateFilter(field); if (fieldFilter != null) { filters.add(fieldFilter); if (fieldFilter instanceof MarkerTypeFieldFilter) { ((MarkerTypeFieldFilter) fieldFilter).setContentGenerator(generator); } if (values != null) { fieldFilter.initialize(values); } } } MarkerFieldFilter[] newFilters = new MarkerFieldFilter[filters.size()]; filters.toArray(newFilters); fieldFilters = newFilters; }</code><technical_language>rename 'visibleField'</technical_language>

Target:
protected void calculateFilters() { Map<String, String> values = getValues(); Collection<MarkerFieldFilter> filters = new ArrayList<>(); for (MarkerField visibleField : generator.getVisibleFields()) { MarkerFieldFilter fieldFilter = MarkerSupportInternalUtilities.generateFilter(visibleField); if (fieldFilter != null) { filters.add(fieldFilter); if (fieldFilter instanceof MarkerTypeFieldFilter) { ((MarkerTypeFieldFilter) fieldFilter).setContentGenerator(generator); } if (values != null) { fieldFilter.initialize(values); } } } MarkerFieldFilter[] newFilters = new MarkerFieldFilter[filters.size()]; filters.toArray(newFilters); fieldFilters = newFilters; }
Source:
<code>protected IntegerRangePredicate(FieldDef<T, Integer> type, String value) throws QueryParseException { super(type, value); if (value.startsWith("<=")) { relation = Relation.LESS_THAN_OR_EQUAL; value = value.substring(2); } else if (value.startsWith("<")) { relation = Relation.LESS_THAN; value = value.substring(1); } else if (value.startsWith(">=")) { relation = Relation.GREATER_THAN_OR_EQUAL; value = value.substring(2); } else if (value.startsWith(">")) { relation = Relation.GREATER_THAN; value = value.substring(1); } else { <START> relation = Relation.EQUAL; <END> } try { queryInt = Integer.parseInt(value); } catch (NumberFormatException e) { throw new QueryParseException(e.getMessage(), e); } }</code><technical_language>Hm, I if people other == typing size:500. I arguments for >=500 <=500 default..</technical_language>

Target:
protected IntegerRangePredicate(FieldDef<T, Integer> type, String value) throws QueryParseException { super(type, value); range = RangeUtil.getRange(value, Integer.MIN_VALUE, Integer.MAX_VALUE); if (range == null) { throw new QueryParseException("Invalid range predicate: " + value); } }
Source:
<code>private void showNic(NetworkInterfaceModel nic) { contents.removeAllRows(); VdsNetworkInterface entity = nic.getOriginalIface(); addRow(templates.titleSetupNetworkTooltip(nic.getName(), SafeStylesUtils.forTrustedBackgroundColor(BACKGROUND_COLOR))); if (nic.getItems().isEmpty() && !nic.isBonded()) { insertHorizontalLine(); addMtuInfo(entity.getMtu()); addBootProtoAndIpInfo(new InterfacePropertiesAccessor.FromNic(entity, null)); } if (nic instanceof BondNetworkInterfaceModel) { CreateOrUpdateBond createOrUpdateBond = ((BondNetworkInterfaceModel) nic).getCreateOrUpdateBond(); String bondOptions = entity.getBondOptions(); if (createOrUpdateBond != null) { bondOptions = createOrUpdateBond.getBondOptions(); } addRow(constants.bondOptionsItemInfo(), bondOptions.replace(BOND_OPTIONS_IP_SEPARATOR, BOND_OPTIONS_IP_SEPARATOR + " ")); } else { addLldpInfo(nic); } if (nic.isVf()) { addRow(constants.physicalFunction(), nic.getPhysicalFunction()); } <START> HostNicVfsConfig vfsConfig = nic.getSetupModel().getVfConfig(nic.getOriginalIface().getId()); addNonNullOrEmptyValueRow(constants.enabledVirtualFunctions(), vfsConfig != null ? String.valueOf(vfsConfig.getNumOfVfs()) : null); addNonNullOrEmptyValueRow(constants.freeVirtualFunctions(), vfsConfig != null ? String.valueOf(vfsConfig.getNumOfFreeVfs()) : null); <END> }</code><technical_language>I surround 'if (nic.isSriovEnabled())' need null checks</technical_language>

Target:
private void showNic(NetworkInterfaceModel nic) { contents.removeAllRows(); VdsNetworkInterface entity = nic.getOriginalIface(); addRow(templates.titleSetupNetworkTooltip(nic.getName(), SafeStylesUtils.forTrustedBackgroundColor(BACKGROUND_COLOR))); if (nic.getItems().isEmpty() && !nic.isBonded()) { insertHorizontalLine(); addMtuInfo(entity.getMtu()); addBootProtoAndIpInfo(new InterfacePropertiesAccessor.FromNic(entity, null)); } if (nic instanceof BondNetworkInterfaceModel) { CreateOrUpdateBond createOrUpdateBond = ((BondNetworkInterfaceModel) nic).getCreateOrUpdateBond(); String bondOptions = entity.getBondOptions(); if (createOrUpdateBond != null) { bondOptions = createOrUpdateBond.getBondOptions(); } addRow(constants.bondOptionsItemInfo(), bondOptions.replace(BOND_OPTIONS_IP_SEPARATOR, BOND_OPTIONS_IP_SEPARATOR + " ")); } else { addLldpInfo(nic); } if (nic.isVf()) { addRow(constants.physicalFunction(), nic.getPhysicalFunction()); } HostNicVfsConfig vfsConfig = nic.getSetupModel().getVfConfig(nic.getOriginalIface().getId()); if (nic.isSriovEnabled()) { addNonNullOrEmptyValueRow(constants.enabledVirtualFunctions(), String.valueOf(vfsConfig.getNumOfVfs())); addNonNullOrEmptyValueRow(constants.freeVirtualFunctions(), String.valueOf(vfsConfig.getNumOfFreeVfs())); } }
Source:
<code>private Address contact(final Gateway gateway, final int expires) throws ServletParseException { SipURI outboundInterface = null; if (address != null && !address.isEmpty()) { if(address.contains(":")) { outboundInterface = (SipURI) factory.createSipURI(null, address); } else { outboundInterface = outboundInterface(address, "udp"); } } else { outboundInterface = outboundInterface(); } if (outboundInterface == null) outboundInterface = (SipURI) factory.createSipURI(null, address); final String user = gateway.getUserName(); <START> String contactUser = new String (user); <END> if (contactUser.contains("@")) { int index = contactUser.indexOf("@"); contactUser = contactUser.substring(0, index); } final String host = outboundInterface.getHost(); int port = outboundInterface.getPort(); if (port == -1) { port = outboundInterface().getPort(); } final StringBuilder buffer = new StringBuilder(); buffer.append("sip:").append(contactUser).append("@").append(host).append(":").append(port); final Address contact = factory.createAddress(buffer.toString()); contact.setExpires(expires); return contact; }</code><technical_language>i this "new String" is strictly neccesary..</technical_language>

Target:
private Address contact(final Gateway gateway, final int expires) throws ServletParseException { SipURI outboundInterface = null; if (address != null && !address.isEmpty()) { if(address.contains(":")) { outboundInterface = (SipURI) factory.createSipURI(null, address); } else { outboundInterface = outboundInterface(address, "udp"); } } else { outboundInterface = outboundInterface(); } if (outboundInterface == null) outboundInterface = (SipURI) factory.createSipURI(null, address); final String user = gateway.getUserName(); String contactUser = user; if (contactUser.contains("@")) { int index = contactUser.indexOf("@"); contactUser = contactUser.substring(0, index); } final String host = outboundInterface.getHost(); int port = outboundInterface.getPort(); if (port == -1) { port = outboundInterface().getPort(); } final StringBuilder buffer = new StringBuilder(); buffer.append("sip:").append(contactUser).append("@").append(host).append(":").append(port); final Address contact = factory.createAddress(buffer.toString()); contact.setExpires(expires); return contact; }
Source:
<code>private void validateFilter() { String filter = getProperty(NotificationProperties.FILTER); if (!StringUtils.isEmpty(filter)) { String[] filterElements = filter.split("\\s+"); for (String filterElement : filterElements) { if (!StringUtils.isEmpty(filterElement)) { if (!FirstMatchSimpleFilter.PARSE_PATTERN.matcher(filterElement).matches()) { throw new IllegalArgumentException( String.format("%s Illegal value for %s , (%s)", GENERIC_MESSAGE, FILTER, filterElement)); <START> } <END> } } } }</code><technical_language>validate content format, PARSE_PATTER is private used. parse interface. exception parse considered invalid, other good. if need more syntax validation, parse method improved, location of is here</technical_language>

Target:
private void validateFilter() { String filter = getProperty(NotificationProperties.FILTER, true); if (filter != null) FirstMatchSimpleFilter.parse(filter); }