auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { <START> View element = convertView; <END> if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.user_item, null); } View userColor = (View) element.findViewById(R.id.userColor); TextView username = (TextView)element.findViewById(R.id.username); userColor.setBackgroundColor(Color.parseColor(users.get(usernames[position]))); username.setText(usernames[position]); return element; }</code><technical_language>Is a more descriptive name element? if lets if worries</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { View userView = convertView; if(userView == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); userView = inflater.inflate(R.layout.user_item, null); } View userColor = (View) userView.findViewById(R.id.user_color); TextView username = (TextView)userView.findViewById(R.id.username); userColor.setBackgroundColor(Color.parseColor(users.get(usernames[position]))); username.setText(usernames[position]); return userView; }
Source:
<code>protected void describeLine(StringBuilder sb) { super.describeLine(sb); if (barrier == null) { sb.append(String.format("connect %s\n", location)); } else { <START> sb.append(String.format("connect await %s\nconnect %s\n", barrier, location)); <END> } }</code><technical_language>Static imports for String.format for readability</technical_language>

Target:
protected void describeLine(StringBuilder sb) { super.describeLine(sb); if (barrier == null) { sb.append(format("connect %s\n", location)); } else { sb.append(format("connect await %s\nconnect %s\n", barrier, location)); } }
Source:
<code>public void testReadAvroWithoutReaderSchemas() throws IOException { Path sequenceFilePath = new Path(new File(mTempDir.getRoot(), "output.seq").getPath()); writeSequenceFile(sequenceFilePath, AvroKey.class, AvroValue.class, Schema.create(Schema.Type.STRING), Schema.create(Schema.Type.INT), new AvroKey<CharSequence>("one"), new AvroValue<>(1), new AvroKey<CharSequence>("two"), new AvroValue<>(2)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); AvroSequenceFile.Reader.Options options = new AvroSequenceFile.Reader.Options().withFileSystem(fs) .withInputPath(sequenceFilePath).withConfiguration(conf); SequenceFile.Reader reader = new AvroSequenceFile.Reader(options); AvroKey<CharSequence> key = new AvroKey<>(); AvroValue<Integer> value = new AvroValue<>(); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("one", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(1, value.datum().intValue()); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("two", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(2, value.datum().intValue()); assertNull("Should be no more records.", reader.next(key)); <START> reader.close(); <END> }</code><technical_language>a try-with-resource pattern here</technical_language>

Target:
public void testReadAvroWithoutReaderSchemas() throws IOException { Path sequenceFilePath = new Path(new File(mTempDir.getRoot(), "output.seq").getPath()); writeSequenceFile(sequenceFilePath, AvroKey.class, AvroValue.class, Schema.create(Schema.Type.STRING), Schema.create(Schema.Type.INT), new AvroKey<CharSequence>("one"), new AvroValue<>(1), new AvroKey<CharSequence>("two"), new AvroValue<>(2)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); AvroSequenceFile.Reader.Options options = new AvroSequenceFile.Reader.Options().withFileSystem(fs) .withInputPath(sequenceFilePath).withConfiguration(conf); try (SequenceFile.Reader reader = new AvroSequenceFile.Reader(options)) { AvroKey<CharSequence> key = new AvroKey<>(); AvroValue<Integer> value = new AvroValue<>(); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("one", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(1, value.datum().intValue()); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("two", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(2, value.datum().intValue()); assertNull("Should be no more records.", reader.next(key)); } }
Source:
<code>private boolean alreadyExistsInTgt(StoreKey key, IndexValue srcValue) throws StoreException { IndexValue tgtValue = tgtIndex.findKey(key); return tgtValue != null && srcValue.isFlagSet(IndexValue.Flags.Delete_Index) == tgtValue.isFlagSet( IndexValue.Flags.Delete_Index); <START> } <END></code><technical_language>minor: exists in targetIndex</technical_language>

Target:
private boolean alreadyExistsInTgt(StoreKey key, IndexValue srcValue) throws StoreException { IndexValue tgtValue = tgtIndex.findKey(key); return tgtValue != null && (tgtValue.isFlagSet(IndexValue.Flags.Delete_Index) || !srcValue.isFlagSet( IndexValue.Flags.Delete_Index)); }
Source:
<code>public void onBackPressed() { if (coordinatesChanged) { showSaveChangesDialog(this); } else { <START> super.onBackPressed(); <END> } }</code><technical_language>please rename finishWithResult similar. saving anything, finishing activity</technical_language>

Target:
public void onBackPressed() { showSaveChangesDialog(this); }
Source:
<code>public long getMessageSendTime(final int idx) { <START> if (!VmSettings.MESSAGE_TIMESTAMPS) { <END> return 0; } return messageSendTime.get(idx); }</code><technical_language>this, I a worried checks abstraction level in code. is checked level of callee, instead of caller for instance in Actor class? version is better, I callers methods have. But, good if is done uniformly, if possible/sensible</technical_language>

Target:
public long getMessageSendTime(final int idx) { return messageSendTime.get(idx); }
Source:
<code>public Builder cmd(List<String> cmd) { <START> this.cmd = ImmutableList.builder(); <END> this.cmd.addAll(cmd); return this; }</code><technical_language>overriding here? If want add, initialize variable declaring copyOf here</technical_language>

Target:
public Builder cmd(List<String> cmd) { this.cmd = ImmutableList.copyOf(checkNotNull(cmd, "cmd")); return this; }
Source:
<code><START> public void waitTabSelected(String tabTitle) { <END> final String terminalTabXpath = getTerminalTabXpath(tabTitle); final String cssTopBorderColorProperty = "border-top-color"; final String selectedElementTopBorderColor = "rgba(245, 245, 245, 1)"; seleniumWebDriverHelper.waitCssValueEqualsTo( By.xpath(terminalTabXpath), cssTopBorderColorProperty, selectedElementTopBorderColor); }</code><technical_language>I patterns of method names includesTerminal. redundant is Theia Terminal anyway</technical_language>

Target:
public void waitTabSelected(String tabTitle) { final String tabXpath = getTabXpath(tabTitle); final String cssTopBorderColorProperty = "border-top-color"; final String selectedElementTopBorderColor = "rgba(245, 245, 245, 1)"; seleniumWebDriverHelper.waitCssValueEqualsTo( By.xpath(tabXpath), cssTopBorderColorProperty, selectedElementTopBorderColor); }
Source:
<code>public final Response createServiceIntegrationSecrets( @Context final HttpServletRequest request, @Context final HttpServletResponse response, final SecretForm secretForm ) { try { <START> secretForm.checkValid(); <END> final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); helper.saveUpdateSecret(secretForm, user); return Response.ok(new ResponseEntityView(OK)).build(); } catch (Exception e) { Logger.error(this.getClass(),"Exception creating secret with message: " + e.getMessage(), e); return ResponseUtil.mapExceptionResponse(e); } }</code><technical_language>this validation I</technical_language>

Target:
public final Response createServiceIntegrationSecrets( @Context final HttpServletRequest request, @Context final HttpServletResponse response, final SecretForm secretForm ) { try { secretForm.checkValid(); final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(request, response) .rejectWhenNoUser(true) .init(); final User user = initData.getUser(); helper.saveUpdateSecret(secretForm, user); return Response.ok(new ResponseEntityView(OK)).build(); } catch (Exception e) { Logger.error(this.getClass(), String.format("Exception creating secret integration with form `%s` ",secretForm), e ); return ResponseUtil.mapExceptionResponse(e); } }
Source:
<code>private DashboardFilter blacklist(String... pipelines) { <START> return new BlacklistFilter(DEFAULT_NAME, CaseInsensitiveString.list(pipelines), new HashSet<>()); <END> }</code><technical_language>I Collections.emptySet() here, else need a dummy set in helpers tests</technical_language>

Target:
private DashboardFilter blacklist(String... pipelines) { return new BlacklistFilter(DEFAULT_NAME, CaseInsensitiveString.list(pipelines), Collections.emptySet()); }
Source:
<code>public String completeToolTipText(String toolTipText, EObject eObject, EStructuralFeature feature) { return <START> completeToolTipText(toolTipText, <END> eObject); }</code><technical_language>tooltipText;</technical_language>

Target:
public String completeToolTipText(String toolTipText, EObject eObject, EStructuralFeature feature) { return toolTipText; }
Source:
<code>public static Map<String, String> filterTags(Map<String, String> tags, List<String> whiteList, List<String> whiteListPrefixes) { if (!(whiteList == null && whiteListPrefixes == null)) { final Map<String, String> tagsCopy = Maps.newHashMap(tags); final Map<String, String> newTags = Maps.newLinkedHashMap(); String key; if (whiteList != null) { for (Map.Entry<String, String> entry : tags.entrySet()) { key = entry.getKey(); if (whiteList.contains(key)) { newTags.put(key, entry.getValue()); tagsCopy.remove(key); } } } if (whiteListPrefixes != null) { for (Map.Entry<String, String> entry : tagsCopy.entrySet()) { key = entry.getKey(); for (String prefix : whiteListPrefixes) { if (key.startsWith(prefix)) { newTags.put(key, entry.getValue()); break; } } } } <START> return newTags; <END> } return tags; }</code><technical_language>remove nested if statements short-circuiting method if white lists null</technical_language>

Target:
public static Map<String, String> filterTags(Map<String, String> tags, List<String> whiteList, List<String> whiteListPrefixes) { if (whiteList == null && whiteListPrefixes == null) { return tags; } final Map<String, String> tagsCopy = Maps.newHashMap(tags); final Map<String, String> newTags = Maps.newLinkedHashMap(); String key; if (whiteList != null) { for (Map.Entry<String, String> entry : tags.entrySet()) { key = entry.getKey(); if (whiteList.contains(key)) { newTags.put(key, entry.getValue()); tagsCopy.remove(key); } } } if (whiteListPrefixes != null) { for (Map.Entry<String, String> entry : tagsCopy.entrySet()) { key = entry.getKey(); for (String prefix : whiteListPrefixes) { if (key.startsWith(prefix)) { newTags.put(key, entry.getValue()); break; } } } } return newTags; }
Source:
<code>public GenericRecord convertToAvro(String json) { try { ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(json); return getOutputRecord(jsonNode, schema); } catch (IOException ex) { <START> logger.error(ex.getMessage()); <END> } return null; }</code><technical_language>I if this is handle this exception. Ok contract of this API is clear in interface definition, I a null is expected this API is used. Especially for level API this I if throw a TalendRuntimeException nests IOException exception is handled caller. This saves a null check. wrong want return null. @gonchar-ivan do</technical_language>

Target:
public GenericRecord convertToAvro(String json) { try { ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(json); return getOutputRecord(jsonNode, schema); } catch (IOException | TalendRuntimeException e) { throw TalendRuntimeException.createUnexpectedException(e.getCause()); } }
Source:
<code>public synchronized void put(Integer key, String testUnitName) throws OseeCoreException { ensurePopulated(); if (idToNameCache.containsKey(key) && !idToNameCache.get(key).equalsIgnoreCase(testUnitName)) { throw new OseeArgumentException("TestUnit key: [%s] has already been used", key); <START> } else { <END> idToNameCache.put(key, testUnitName); cacheIsDirty = true; } }</code><technical_language>Need add event listener update this cache artifact is updated. John</technical_language>

Target:
public synchronized void put(Integer key, String testUnitName) throws OseeCoreException { ensurePopulated(); if (idToNameCache.containsKey(key) && !idToNameCache.get(key).equalsIgnoreCase(testUnitName)) { throw new OseeArgumentException("TestUnit key: [%s] has already been used", key); } else { idToNameCache.put(key, testUnitName); cacheIsDirty = true; lastId = Math.max(lastId, key); } }
Source:
<code>public void testRemoveValueUnequalStoreEntryCacheAccessExceptionNoCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.<String, String>emptyMap()); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); <START> assertFalse(ehcache.remove("key", "value")); END> verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); assertThat(realCache.getEntries().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>others, I assert result of operation, resilience strategy invoked</technical_language>

Target:
public void testRemoveValueUnequalStoreEntryCacheAccessExceptionNoCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.<String, String>emptyMap()); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); ehcache.remove("key", "value"); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>public void visitToken(final DetailAST ast) { final String[] lines = this.getLines(); final int start = ast.getLineNo(); final int cstart = JavadocEmptyLineCheck.findCommentStart(lines, start) + 1; if (JavadocEmptyLineCheck.isNodeHavingJavaDoc(ast, cstart)) { if (JavadocEmptyLineCheck.isJavadocLineEmpty(lines[cstart])) { this.log(cstart + 1, "Empty javadoc line at the beginning"); } <START> final int cend = <END> JavadocEmptyLineCheck.findCommentEnd(lines, start) - 1; if (JavadocEmptyLineCheck.isJavadocLineEmpty(lines[cend])) { this.log(cend + 1, "Empty javadoc line at the end"); } } }</code><technical_language>@dskalenko cend is compound name, please rename single word</technical_language>

Target:
public void visitToken(final DetailAST ast) { final String[] lines = this.getLines(); final int current = ast.getLineNo(); final int start = JavadocEmptyLineCheck.findCommentStart(lines, current) + 1; if (JavadocEmptyLineCheck.isNodeHavingJavadoc(ast, start)) { if (JavadocEmptyLineCheck.isJavadocLineEmpty(lines[start])) { this.log(start + 1, "Empty Javadoc line at the beginning"); } final int end = JavadocEmptyLineCheck.findCommentEnd(lines, current) - 1; if (JavadocEmptyLineCheck.isJavadocLineEmpty(lines[end])) { this.log(end + 1, "Empty Javadoc line at the end"); } } }
Source:
<code>public static void setup() { try { Class.forName(DB_DRIVER).newInstance(); Connection con = DriverManager.getConnection(DB_URL,USER_NAME,PSW); Statement stmt = con.createStatement(); String createMetaTable = "CREATE TABLE IF NOT EXISTS " + JdbcTransactionalStore.DEFAULT_META_TABLE + " ( " + JdbcTransactionalStore.DEFAULT_APP_ID_COL + " VARCHAR(100) NOT NULL, " + JdbcTransactionalStore.DEFAULT_OPERATOR_ID_COL + " INT NOT NULL, " + JdbcTransactionalStore.DEFAULT_WINDOW_COL + " BIGINT NOT NULL, " + "UNIQUE (" + JdbcTransactionalStore.DEFAULT_APP_ID_COL + ", " + JdbcTransactionalStore.DEFAULT_OPERATOR_ID_COL + ", " + JdbcTransactionalStore.DEFAULT_WINDOW_COL + ") " + ")"; stmt.executeUpdate(createMetaTable); String createInputTable = "CREATE TABLE IF NOT EXISTS " + INPUT_TABLE + "(MONTH INT(2) not NULL, DAY INT(2), YEAR INT(4), MEANTEMP DOUBLE(10) )"; stmt.executeUpdate(createInputTable); String createOutputTable = "CREATE TABLE IF NOT EXISTS " + OUTPUT_TABLE + "(MONTH INT(2) not NULL, MEANTEMP DOUBLE(10) )"; stmt.executeUpdate(createOutputTable); String cleanTable = "truncate table " + INPUT_TABLE; stmt.executeUpdate(cleanTable); stmt = con.createStatement(); String sql = "INSERT INTO " + INPUT_TABLE + " VALUES (6, 21, 2014, 85.3)"; stmt.executeUpdate(sql); sql = "INSERT INTO " + INPUT_TABLE + " VALUES (7, 20, 2014, 75.4)"; stmt.executeUpdate(sql); sql = "INSERT INTO " + INPUT_TABLE + " VALUES (6, 18, 2014, 45.3)"; stmt.executeUpdate(sql); } catch (Throwable e) { <START> DTThrowable.rethrow(e); <END> } }</code><technical_language>DTThrowable is deprecated. Please check other occurrences</technical_language>

Target:
public static void setup() { try { Class.forName(DB_DRIVER).newInstance(); Connection con = DriverManager.getConnection(DB_URL,USER_NAME,PSW); Statement stmt = con.createStatement(); String createMetaTable = "CREATE TABLE IF NOT EXISTS " + JdbcTransactionalStore.DEFAULT_META_TABLE + " ( " + JdbcTransactionalStore.DEFAULT_APP_ID_COL + " VARCHAR(100) NOT NULL, " + JdbcTransactionalStore.DEFAULT_OPERATOR_ID_COL + " INT NOT NULL, " + JdbcTransactionalStore.DEFAULT_WINDOW_COL + " BIGINT NOT NULL, " + "UNIQUE (" + JdbcTransactionalStore.DEFAULT_APP_ID_COL + ", " + JdbcTransactionalStore.DEFAULT_OPERATOR_ID_COL + ", " + JdbcTransactionalStore.DEFAULT_WINDOW_COL + ") " + ")"; stmt.executeUpdate(createMetaTable); String createInputTable = "CREATE TABLE IF NOT EXISTS " + INPUT_TABLE + "(MONTH INT(2) not NULL, DAY INT(2), YEAR INT(4), MEANTEMP DOUBLE(10) )"; stmt.executeUpdate(createInputTable); String createOutputTable = "CREATE TABLE IF NOT EXISTS " + OUTPUT_TABLE + "(MONTH INT(2) not NULL, MEANTEMP DOUBLE(10) )"; stmt.executeUpdate(createOutputTable); String cleanTable = "truncate table " + INPUT_TABLE; stmt.executeUpdate(cleanTable); stmt = con.createStatement(); String sql = "INSERT INTO " + INPUT_TABLE + " VALUES (6, 21, 2014, 85.3)"; stmt.executeUpdate(sql); sql = "INSERT INTO " + INPUT_TABLE + " VALUES (7, 20, 2014, 75.4)"; stmt.executeUpdate(sql); sql = "INSERT INTO " + INPUT_TABLE + " VALUES (6, 18, 2014, 45.3)"; stmt.executeUpdate(sql); } catch (Throwable e) { throw Throwables.propagate(e); } }
Source:
<code>public void endWindow() { if (!partialWindowTuples.isEmpty() && windowId > windowDataManager.getLargestRecoveryWindow()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } try { this.windowDataManager.save(getPartitionsAndOffsets(), operatorId, windowId); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } catch (ExecutionException e) { e.printStackTrace(); } }</code><technical_language>swallow exception</technical_language>

Target:
public void endWindow() { if (!partialWindowTuples.isEmpty() && windowId > windowDataManager.getLargestRecoveryWindow()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } getProducer().flush(); try { this.windowDataManager.save(getPartitionsAndOffsets(true), operatorId, windowId); } catch (IOException | InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
Source:
<code>public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable { CompletionStage<Void> stage; if (command instanceof TxReadOnlyKeyCommand) { stage = entryFactory.wrapEntryForWriting(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command), true); } else { stage = entryFactory.wrapEntryForReading(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command)); } <START> if (CompletionStages.isCompletedSuccessfully(stage)) { <END> return invokeNext(ctx, command); } else { return asyncInvokeNext(ctx, command, stage); } }</code><technical_language>asyncInvokeNext checks if delay stage is completed</technical_language>

Target:
public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable { CompletionStage<Void> stage; if (command instanceof TxReadOnlyKeyCommand) { stage = entryFactory.wrapEntryForWriting(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command), true); } else { stage = entryFactory.wrapEntryForReading(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command)); } return asyncInvokeNext(ctx, command, stage); }
Source:
<code>@Override protected <T> PrioritizedListenableFutureTask<T> newTaskFor(Runnable runnable, T value) { <START> return PrioritizedListenableFutureTask.create(ListenableFutureTask.create(runnable, value), <END> runnable instanceof PrioritizedRunnable ? ((PrioritizedRunnable) runnable).getPriority() : DEFAULT_PRIORITY ); }</code><technical_language>Do intend send prioritized tasks executor? If throw exception (or log) if priority is set</technical_language>

Target:
@Override protected <T> PrioritizedListenableFutureTask<T> newTaskFor(Runnable runnable, T value) { Preconditions.checkArgument(allowRegularTasks || runnable instanceof PrioritizedRunnable, "task does not implement PrioritizedRunnable"); return PrioritizedListenableFutureTask.create(ListenableFutureTask.create(runnable, value), runnable instanceof PrioritizedRunnable ? ((PrioritizedRunnable) runnable).getPriority() : defaultPriority ); }
Source:
<code>private String getArtifactViewApplicabiltyText() { <START> String viewName = null; <END> if (explorer != null) { BranchId branch = explorer.getBranch(); if (branch != null) { if (!ViewApplicabilityUtil.isBranchOfProductLine(branch)) { button.setEnabled(false); } else { button.setEnabled(true); ArtifactId viewId = explorer.getViewId(); if (viewId.isValid()) { viewName = ArtifactQuery.getArtifactTokenFromId(explorer.getBranch(), viewId).getName(); } } } } return String.format("<form><p>%s</p></form>", viewName == null ? "Not Set" : viewName); }</code><technical_language>Default "Not Set", ternary expression is needed</technical_language>

Target:
private String getArtifactViewApplicabiltyText() { String viewName = "Not Set"; if (explorer != null) { BranchId branch = explorer.getBranch(); if (branch != null) { if (!ViewApplicabilityUtil.isBranchOfProductLine(branch)) { button.setEnabled(false); } else { button.setEnabled(true); ArtifactId viewId = explorer.getViewId(); if (viewId.isValid()) { viewName = ArtifactQuery.getArtifactTokenFromId(explorer.getBranch(), viewId).getName(); } } } } return String.format("<form><p>%s</p></form>", viewName); }
Source:
<code>public void run() { service.submit(new Runnable() { @Override public void run() { while (true) { while (avroDataStream.hasNext()) { if (!keepIndexing) { return; } GenericRecord record = avroDataStream.next(); GenericRecord message = new GenericData.Record(AvroUtils.getAvroSchemaFromPinotSchema(pinotSchema)); for (FieldSpec spec : pinotSchema.getDimensionFieldSpecs()) { message.put(spec.getName(), record.get(spec.getName())); } for (FieldSpec spec : pinotSchema.getDimensionFieldSpecs()) { message.put(spec.getName(), record.get(spec.getName())); } TimeFieldSpec spec = pinotSchema.getTimeFieldSpec(); <START> String timeColumn = spec.getName(); <END> message.put(timeColumn, currentTimeValue); try { publish(message); counter++; if (counter % 60 == 0) { currentTimeValue = currentTimeValue + 1; } Thread.sleep(1000); } catch (Exception e) { logger.error(e.getMessage()); } } try { avroDataStream.close(); } catch (IOException e) { logger.error(e.getMessage()); } try { createStream(); } catch (IOException e) { logger.error(e.getMessage()); } } } }); }</code><technical_language>Conceptually this incoming name</technical_language>

Target:
public void run() { service.submit(new Runnable() { @Override public void run() { while (true) { while (avroDataStream.hasNext()) { if (!keepIndexing) { return; } GenericRecord record = avroDataStream.next(); GenericRecord message = new GenericData.Record(AvroUtils.getAvroSchemaFromPinotSchema(pinotSchema)); for (FieldSpec spec : pinotSchema.getDimensionFieldSpecs()) { message.put(spec.getName(), record.get(spec.getName())); } for (FieldSpec spec : pinotSchema.getDimensionFieldSpecs()) { message.put(spec.getName(), record.get(spec.getName())); } TimeFieldSpec spec = pinotSchema.getTimeFieldSpec(); String timeColumn = spec.getIncomingGranularitySpec().getName(); message.put(timeColumn, currentTimeValue); try { publish(message); counter++; if (counter % 60 == 0) { currentTimeValue = currentTimeValue + 1; } Thread.sleep(1000); } catch (Exception e) { logger.error(e.getMessage()); } } try { avroDataStream.close(); } catch (IOException e) { logger.error(e.getMessage()); } try { createStream(); } catch (IOException e) { logger.error(e.getMessage()); } } } }); }
Source:
<code>public static void initialize() throws Exception { repoFile = Files.createTempDir(); <START> System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); <END> System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); System.setProperty(ArtifactRepositoryService.ORG_GUVNOR_M2REPO_DIR_PROPERTY, repoFile.getAbsolutePath()); weldContainer = new Weld().initialize(); ioService = weldContainer.select(IOService.class, new NamedLiteral("ioStrategy")).get(); buildService = weldContainer.select(BuildService.class).get(); moduleService = weldContainer.select(KieModuleService.class).get(); classLoaderHelper = weldContainer.select(ModuleClassLoaderHelper.class).get(); formFinderService = weldContainer.select(ModuleFormFinderServiceImpl.class).get(); fs.forceAsDefault(); }</code><technical_language>properties replace definitions <LINK_0></technical_language>

Target:
public static void initialize() throws Exception { repoFile = Files.createTempDir(); System.setProperty(JGitFileSystemProviderConfiguration.GIT_DAEMON_ENABLED, "false"); System.setProperty(JGitFileSystemProviderConfiguration.GIT_SSH_ENABLED, "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); System.setProperty(ArtifactRepositoryService.ORG_GUVNOR_M2REPO_DIR_PROPERTY, repoFile.getAbsolutePath()); weldContainer = new Weld().initialize(); ioService = weldContainer.select(IOService.class, new NamedLiteral("ioStrategy")).get(); buildService = weldContainer.select(BuildService.class).get(); moduleService = weldContainer.select(KieModuleService.class).get(); classLoaderHelper = weldContainer.select(ModuleClassLoaderHelper.class).get(); formFinderService = weldContainer.select(ModuleFormFinderServiceImpl.class).get(); fs.forceAsDefault(); }
Source:
<code>protected GraphHopper createGraphHopper(CmdArgs args) { GraphHopper tmp = new GraphHopperOSM().forServer().init(args); <START> tmp.setSpatialRuleLookup(SpatialRuleLookupBuilder.build()); <END> tmp.importOrLoad(); logger.info("loaded graph at:" + tmp.getGraphHopperLocation() + ", data_reader_file:" + tmp.getDataReaderFile() + ", flag_encoders:" + tmp.getEncodingManager() + ", " + tmp.getGraphHopperStorage().toDetailsString()); return tmp; }</code><technical_language>related TODOs :) ... is suboptimal configured load json resolution ..</technical_language>

Target:
protected GraphHopper createGraphHopper(CmdArgs args) { GraphHopper tmp = new GraphHopperOSM().forServer().init(args); String location = args.get("spatial_rules.location", ""); if (!location.isEmpty()) { if (!tmp.getEncodingManager().supports(("generic"))) { logger.warn("spatial_rules.location was specified but 'generic' encoder is missing to utilize the index"); } else try { SpatialRuleLookup index = buildIndex(new FileReader(location), tmp.getGraphHopperStorage().getBounds()); if (index != null) { logger.info("Set spatial rule lookup with " + index.size() + " rules"); ((DataFlagEncoder) tmp.getEncodingManager().getEncoder("generic")).setSpatialRuleLookup(index); } } catch (IOException ex) { throw new RuntimeException(ex); } } tmp.importOrLoad(); logger.info("loaded graph at:" + tmp.getGraphHopperLocation() + ", data_reader_file:" + tmp.getDataReaderFile() + ", flag_encoders:" + tmp.getEncodingManager() + ", " + tmp.getGraphHopperStorage().toDetailsString()); return tmp; }
Source:
<code>public AuthHeader fromString(final String value) { try { return AuthHeader.valueOf(value); } catch (IllegalArgumentException e) { <START> throw new NotAuthorizedException(e, "Bearer"); <END> } }</code><technical_language>do need this stuff? in mind, sending a malformed auth header is another IAE. a (backend) client respond a NAE+"Bearer" challenge</technical_language>

Target:
public AuthHeader fromString(final String value) { if (value == null) { throw new NotAuthorizedException("Bearer"); } try { return AuthHeader.valueOf(value); } catch (IllegalArgumentException e) { throw new NotAuthorizedException(e, "Bearer"); } }
Source:
<code>public String generateVersionCrid(Item item, Version version) { String versionCrid = delegate.generateVersionCrid(item, version); Optional<String> value = idMappingStore.getValueFor(version.getCanonicalUri()); if (!value.isPresent() || !versionCrid.equals(value.get())) { <START> idMappingStore.storeMapping(version.getCanonicalUri(), versionCrid); <END> } return versionCrid; }</code><technical_language>This is private store itself. a mongo need protect writes, a user of need care</technical_language>

Target:
public String generateVersionCrid(Item item, Version version) { String versionCrid = delegate.generateVersionCrid(item, version); idMappingStore.storeMapping(version.getCanonicalUri(), versionCrid); return versionCrid; }
Source:
<code>protected void finishFileInfo() throws IOException { if (lastCell != null) { byte lastKey = PrivateCellUtil.getCellKeySerializedAsKeyValueKey(this.lastCell); fileInfo.append(HFileInfo.LASTKEY, lastKey, false); } <START> int avgKeyLen = (int)this.keySizeSketch.getQuantile(0.5); <END> fileInfo.append(HFileInfo.AVG_KEY_LEN, Bytes.toBytes(avgKeyLen), false); int avgValueLen = (int)this.valueSizeSketch.getQuantile(0.5); fileInfo.append(HFileInfo.AVG_VALUE_LEN, Bytes.toBytes(avgValueLen), false); fileInfo.append(HFileInfo.CREATE_TIME_TS, Bytes.toBytes(hFileContext.getFileCreateTime()), false); if (hFileContext.isIncludesTags()) { fileInfo.append(HFileInfo.MAX_TAGS_LEN, Bytes.toBytes(this.maxTagsLength), false); boolean tagsCompressed = (hFileContext.getDataBlockEncoding() != DataBlockEncoding.NONE) && hFileContext.isCompressTags(); fileInfo.append(HFileInfo.TAGS_COMPRESSED, Bytes.toBytes(tagsCompressed), false); } }</code><technical_language>Please call this median average</technical_language>

Target:
protected void finishFileInfo() throws IOException { if (lastCell != null) { byte lastKey = PrivateCellUtil.getCellKeySerializedAsKeyValueKey(this.lastCell); fileInfo.append(HFileInfo.LASTKEY, lastKey, false); } int medianKeyLen = (int)this.keySizeSketch.getQuantile(0.5); fileInfo.append(HFileInfo.AVG_KEY_LEN, Bytes.toBytes(medianKeyLen), false); int medianValueLen = (int)this.valueSizeSketch.getQuantile(0.5); fileInfo.append(HFileInfo.AVG_VALUE_LEN, Bytes.toBytes(medianValueLen), false); fileInfo.append(HFileInfo.CREATE_TIME_TS, Bytes.toBytes(hFileContext.getFileCreateTime()), false); if (hFileContext.isIncludesTags()) { fileInfo.append(HFileInfo.MAX_TAGS_LEN, Bytes.toBytes(this.maxTagsLength), false); boolean tagsCompressed = (hFileContext.getDataBlockEncoding() != DataBlockEncoding.NONE) && hFileContext.isCompressTags(); fileInfo.append(HFileInfo.TAGS_COMPRESSED, Bytes.toBytes(tagsCompressed), false); } }
Source:
<code>protected void loadAvailableModels() { logger.info("Registering existing models"); try (Stream<java.nio.file.Path> walk = Files.walk(Paths.get(runtimeOptions.getImportsBaseDir()), 1)) { <START> walk.filter(p -> p.toFile().isFile()) .filter(p -> p.toString().toLowerCase().endsWith(DASHBOARD_EXTENSION)) <END> .map(p -> p.toString()) .peek(p -> logger.info("Registering {}", p)) .peek(runtimeModelRegistry::registerFile) .forEach(p -> logger.info("Sucessfully Registered {}", p)); } catch (Exception e) { logger.info("Error Registering existing models"); logger.debug("Error Registering existing models.", e); throw new RuntimeException("Error registering existing models.", e); } }</code><technical_language>Consider merging filter operations a single one</technical_language>

Target:
protected void loadAvailableModels() { logger.info("Registering existing models"); try (Stream<java.nio.file.Path> walk = Files.walk(Paths.get(runtimeOptions.getImportsBaseDir()), 1)) { walk.filter(p -> p.toFile().isFile() && p.toString().toLowerCase().endsWith(DASHBOARD_EXTENSION)) .map(Object::toString) .forEach(p -> { logger.info("Registering {}", p); runtimeModelRegistry.registerFile(p); logger.info("Sucessfully Registered {}", p); }); } catch (Exception e) { throw new RuntimeException("Error registering existing models.", e); } }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { Expression child = getStringExpression(); if (!child.evaluate(tuple, ptr)) { return false; } int position; <START> if(strToSearch.length()==0){ <END> position = 0; ptr.set(PInteger.INSTANCE.toBytes(position)); return true; } byte strPattern = strToSearch.getBytes(); SortOrder sortOrder = child.getSortOrder(); ImmutableBytesWritable str = new ImmutableBytesWritable(strPattern); position = searchString(ptr,str,sortOrder,strPattern); ptr.set(PInteger.INSTANCE.toBytes(position)); return true; }</code><technical_language>Minor code formatting issue: a space "if" opening parenthesis</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { Expression child = getChildren().get(0); if (!child.evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { ptr.set(ByteUtil.EMPTY_BYTE_ARRAY); return true; } int position; if (strToSearch == null){ position = 0; ptr.set(PInteger.INSTANCE.toBytes(position)); return true; } String sourceStr = (String) PVarchar.INSTANCE.toObject(ptr, getChildren().get(0).getSortOrder()); position = sourceStr.indexOf(strToSearch); ptr.set(PInteger.INSTANCE.toBytes(position)); return true; }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); for (java.util.Map.Entry<byte[], byte[]> entry : _map.entrySet()) { if (sb.length() > 1) { sb.append(','); } sb.append(new String(entry.getKey())); sb.append('='); <START> sb.append(new String(entry.getValue())); <END> } sb.append('}'); return sb.toString(); }</code><technical_language>this problematic, byte-array a string, decodeable a string, this throw</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); for (java.util.Map.Entry<byte[], byte[]> entry : _map.entrySet()) { if (sb.length() > 1) { sb.append(','); } sb.append(Bytes.toString(entry.getKey())); sb.append('='); sb.append(Bytes.toString(entry.getValue())); } sb.append('}'); return sb.toString(); }
Source:
<code>public void handleMessage(Message msg) { switch (msg.what) { case EVENT_QUALIFIED_NETWORKS_CHANGED: <START> synchronized (this) { <END> AsyncResult ar = (AsyncResult) msg.obj; List<QualifiedNetworks> networks = (List<QualifiedNetworks>) ar.result; updateAvailableNetworks(networks); } break; default: loge("Unexpected event " + msg.what); break; } }</code><technical_language>synchronized in updateAvailableNetworks</technical_language>

Target:
public void handleMessage(Message msg) { switch (msg.what) { case EVENT_QUALIFIED_NETWORKS_CHANGED: AsyncResult ar = (AsyncResult) msg.obj; List<QualifiedNetworks> networks = (List<QualifiedNetworks>) ar.result; updateAvailableNetworks(networks); break; default: loge("Unexpected event " + msg.what); break; } }
Source:
<code>private List<Object> getResources(final List<String> paths) { return paths.stream().map(path -> resourceResolver.getResource(path)) <START> .collect(Collectors.toList()); <END> }</code><technical_language>this filter out null resources? (ie. bad paths)</technical_language>

Target:
List<Object> getResources(final List<String> paths) { return Optional.ofNullable(paths) .map(Collection::stream) .orElseGet(Stream::empty) .map(path -> resourceResolver.getResource(path)) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code>public void init() { log.info("MQTT inbound endpoint: " + name + " initializing ..."); <START> if (mqttBlockingSenderEnable) <END> initSyncClient(); else initAsyncClient(); }</code><technical_language>put brackets this</technical_language>

Target:
public void init() { log.info("MQTT inbound endpoint: " + name + " initializing ..."); if (mqttBlockingSenderEnable){ initSyncClient(); } else{ initAsyncClient(); } }
Source:
<code>public void waitForCleanup() throws InterruptedException { <START> SECONDS.sleep(8); <END> }</code><technical_language>This removed if change verifyThatCleanupOccurred get NotFoundException if sleeps for (until finally timing out 30 seconds for example)</technical_language>

Target:
public void waitForCleanup() throws InterruptedException { Set<Long> waiting = new HashSet<>(ids); for (int i=0; i<10 && !waiting.isEmpty(); ++i) { SECONDS.sleep(1); for (Iterator<Long> it = waiting.iterator(); it.hasNext(); ) { try { getWorkflowInstance(it.next()); } catch (NotFoundException ex) { it.remove(); } } } }
Source:
<code>public List<GameDetails> getListOfGames(@PathVariable(value = "gameListType") String gameListType, @RequestParam(value = "token", required = false) String token) throws AuthenticationException, GameException, WrongPathException { List<GameBean> games; UserBean user; <START> int userId = 0; <END> switch (GameListType.fromValue(gameListType)) { case CURRENT: user = authenticationService.authenticateUserByToken(token); userId = user.getId(); games = gameService.getListOfGamesWithJoinedUser(user); break; case PUBLIC: try { user = authenticationService.authenticateUserByToken(token); userId = user.getId(); } catch (Exception e) games = gameService.getListOfAllPublicGames(); break; case UNKNOWN: default: throw new WrongPathException(); } List<GameDetails> gamesToReturn = new ArrayList<GameDetails>(); for (GameBean game : games) { gamesToReturn.add(new GameDetails(game, userId)); } return gamesToReturn; }</code><technical_language>thinl need this variable, get accessing getter</technical_language>

Target:
public List<GameDetails> getListOfGames(@PathVariable(value = "gameListType") String gameListType, @RequestParam(value = "token", required = false) String token) throws AuthenticationException, GameException, WrongPathException { List<GameBean> games; switch (GameListType.fromValue(gameListType)) { case CURRENT: UserBean user = authenticationService.authenticateUserByToken(token); games = gameService.getListOfGamesWithJoinedUser(user); break; case PUBLIC: games = gameService.getListOfAllPublicGames(); break; case UNKNOWN: default: throw new WrongPathException(); } List<GameDetails> gamesToReturn = new ArrayList<GameDetails>(); for (GameBean game : games) { gamesToReturn.add(new GameDetails(game, 0)); } return gamesToReturn; }
Source:
<code>protected SafeHtml getRenderedImage(IconType value, String color) { SafeStyles <START> colorStyle = <END> new SafeStylesBuilder().trustedColor(color).toSafeStyles(); return TEMPLATE.icon(value.getCssName(), colorStyle); }</code><technical_language>Nit-pick: name this styles</technical_language>

Target:
protected SafeHtml getRenderedImage(IconType value, String color) { SafeStyles styles = new SafeStylesBuilder().trustedColor(color).toSafeStyles(); return TEMPLATE.icon(value.getCssName(), styles); }
Source:
<code>private DeepLinkEntry findEntry(String uriString) { SchemeHostAndPath schemeHostAndPath = new SchemeHostAndPath(DeepLinkUri.parse(uriString)); DeepLinkEntry entryRegExpMatch = null; DeepLinkEntry entryIdxMatch = null; <START> long regExSearchStart = SystemClock.elapsedRealtime(); <END> long regExSearchEnd = SystemClock.elapsedRealtime(); long idxSearchStart = SystemClock.elapsedRealtime(); for (BaseLoader loader : loaders) { entryIdxMatch = loader.idxMatch(DeepLinkUri.parse(uriString)); if (entryIdxMatch != null) { break; } } long idxSearchEnd = SystemClock.elapsedRealtime(); return entryIdxMatch; }</code><technical_language>Remove time logs</technical_language>

Target:
private DeepLinkEntry findEntry(String uriString) { DeepLinkEntry entryRegExpMatch = null; DeepLinkEntry entryIdxMatch = null; for (BaseRegistry loader : loaders) { entryIdxMatch = loader.idxMatch(DeepLinkUri.parse(uriString)); if (entryIdxMatch != null) { break; } } return entryIdxMatch; }
Source:
<code>private Set<Module> findModulesToBuild(RepositoryBuild build, Set<Module> allModules) { CommitInfo commitInfo = build.getCommitInfo().get(); final Set<Module> toBuild = new HashSet<>(); if (build.getBuildTrigger().getType() == Type.MANUAL) { if (!build.getBuildOptions().isPresent() || build.getBuildOptions().get().getModuleIds().isEmpty()) { toBuild.addAll(allModules); } else { final Set<Integer> requestedModuleIds = build.getBuildOptions().get().getModuleIds(); for (Module module : allModules) { if (requestedModuleIds.contains(module.getId().get())) { toBuild.add(module); } } <START> addDownstreamModules(build, allModules, toBuild); <END> } } else if (build.getBuildTrigger().getType() == Type.BRANCH_CREATION) { toBuild.addAll(allModules); } else if (commitInfo.isTruncated()) { toBuild.addAll(allModules); } else { for (String path : gitHubHelper.affectedPaths(commitInfo)) { for (Module module : allModules) { if (module.contains(FileSystems.getDefault().getPath(path))) { toBuild.add(module); } } } addDownstreamModules(build, allModules, toBuild); } return toBuild; }</code><technical_language>check if this build option is enabled adding downstreams right</technical_language>

Target:
private Set<Module> findModulesToBuild(RepositoryBuild build, Set<Module> allModules) { CommitInfo commitInfo = build.getCommitInfo().get(); final Set<Module> toBuild = new HashSet<>(); if (build.getBuildTrigger().getType() == Type.MANUAL) { if (build.getBuildOptions().getModuleIds().isEmpty()) { toBuild.addAll(allModules); } else { final Set<Integer> requestedModuleIds = build.getBuildOptions().getModuleIds(); for (Module module : allModules) { if (requestedModuleIds.contains(module.getId().get())) { toBuild.add(module); } } addDownstreamModules(build, allModules, toBuild); } } else if (build.getBuildTrigger().getType() == Type.BRANCH_CREATION) { toBuild.addAll(allModules); } else if (commitInfo.isTruncated()) { toBuild.addAll(allModules); } else { for (String path : gitHubHelper.affectedPaths(commitInfo)) { for (Module module : allModules) { if (module.contains(FileSystems.getDefault().getPath(path))) { toBuild.add(module); } } } addDownstreamModules(build, allModules, toBuild); } return toBuild; }
Source:
<code>private boolean canClaimSegment(int segmentId) { if (segmentReleaseDeadlines.containsKey(segmentId) && segmentReleaseDeadlines.get(segmentId) > System.currentTimeMillis()){ return false; } <START> segmentReleaseDeadlines.remove(segmentId); <END> return true; }</code><technical_language>is a small race condition here. If containsKey() returns false entry is added, this remove immediately. I split if separate statements remove(Object, Object) removed if exact entry expecting remove</technical_language>

Target:
private boolean canClaimSegment(int segmentId) { return !segmentReleaseDeadlines.containsKey(segmentId) || segmentReleaseDeadlines.get(segmentId) < System.currentTimeMillis(); }
Source:
<code>public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { switch (opcode) { case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: _methodInsnName = name; _methodInsnOwner = owner; _methodInsnDesc = desc; _methodInsnOpcode = opcode; break; default: <START> LOGGER.debug("Unexpected opcode, falling back"); <END> break; } super.visitMethodInsn(opcode, owner, name, desc, itf); }</code><technical_language>TODO + logger level DEBUG</technical_language>

Target:
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { switch (opcode) { case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: _methodInsnName = name; _methodInsnOwner = owner; _methodInsnDesc = desc; _methodInsnOpcode = opcode; break; default: System.out.println("Unexpected opcode, falling back"); break; } super.visitMethodInsn(opcode, owner, name, desc, itf); }
Source:
<code>public boolean equals(Object obj) { <START> return id == ((Nomination) obj).id; <END> }</code><technical_language>Proper equals implementation leave open class cast exceptions</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id == ((Nomination) obj).id; }
Source:
<code>public Repository getRepository(final IPath location) { Repository repository = null; int largestSegmentCount = 0; List<File> toRemove = new ArrayList<>(); synchronized (repositoryCache) { for (Iterator<Map.Entry<File, Reference<Repository>>> i = repositoryCache .entrySet().iterator(); i.hasNext();) { Map.Entry<File, Reference<Repository>> entry = i.next(); Repository repo = entry.getValue().get(); if (repo == null) { i.remove(); toRemove.add(entry.getKey()); continue; } if (repo.isBare()) { continue; } IPath repoPath = new Path(repo.getWorkTree().getAbsolutePath()); if <START> (location != null && <END> repoPath.isPrefixOf(location)) { if (repository == null || repoPath.segmentCount() > largestSegmentCount) { if (!repo.getDirectory().exists()) { i.remove(); toRemove.add(entry.getKey()); continue; } repository = repo; largestSegmentCount = repoPath.segmentCount(); } } } } removeIndexDiffCaches(toRemove); return repository; }</code><technical_language>move this beginning of method early exit? (should in version)</technical_language>

Target:
public Repository getRepository(final IPath location) { if (location == null) { return null; } Repository repository = null; int largestSegmentCount = 0; List<File> toRemove = new ArrayList<>(); synchronized (repositoryCache) { for (Iterator<Map.Entry<File, Reference<Repository>>> i = repositoryCache .entrySet().iterator(); i.hasNext();) { Map.Entry<File, Reference<Repository>> entry = i.next(); Repository repo = entry.getValue().get(); if (repo == null) { i.remove(); toRemove.add(entry.getKey()); continue; } if (repo.isBare()) { continue; } IPath repoPath = new Path(repo.getWorkTree().getAbsolutePath()); if (repoPath.isPrefixOf(location)) { if (repository == null || repoPath.segmentCount() > largestSegmentCount) { if (!repo.getDirectory().exists()) { i.remove(); toRemove.add(entry.getKey()); continue; } repository = repo; largestSegmentCount = repoPath.segmentCount(); } } } } removeIndexDiffCaches(toRemove); return repository; }