auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void onFragmentLoaded(final boolean restoreScrollPosition) { if (recyclerAdapter == null) { MainActivity activity = (MainActivity) getActivity(); recyclerAdapter = new QueueRecyclerAdapter(activity, itemAccess, new DefaultActionButtonCallback(activity), itemTouchHelper); recyclerAdapter.setHasStableIds(true); recyclerView.setAdapter(recyclerAdapter); } if(queue == null || queue.size() == 0) { recyclerView.setVisibility(View.GONE); <START> layoutEmpty.setVisibility(View.VISIBLE); <END> } else { layoutEmpty.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } if (restoreScrollPosition) { restoreScrollPosition(); } getActivity().supportInvalidateOptionsMenu(); refreshInfoBar(); }</code><technical_language>Please indentation</technical_language>

Target:
private void onFragmentLoaded(final boolean restoreScrollPosition) { if (recyclerAdapter == null) { MainActivity activity = (MainActivity) getActivity(); recyclerAdapter = new QueueRecyclerAdapter(activity, itemAccess, new DefaultActionButtonCallback(activity), itemTouchHelper); recyclerAdapter.setHasStableIds(true); recyclerView.setAdapter(recyclerAdapter); } if(queue == null || queue.size() == 0) { recyclerView.setVisibility(View.GONE); emptyView.setVisibility(View.VISIBLE); } else { emptyView.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } if (restoreScrollPosition) { restoreScrollPosition(); } getActivity().supportInvalidateOptionsMenu(); refreshInfoBar(); }
Source:
<code>public PermissionBlueprintDTO populate(ModelTranslator translator, PermissionBlueprint source, PermissionBlueprintDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("destination is null"); } <START> PermissionType type = source.getType(); <END> Access access = source.getAccess(); dest.id(source.getId()) .type(type != null ? type.name() : null) .access(access != null ? access.name() : null); if (translator != null) { dest.setOwner(translator.translate(source.getOwner(), NestedOwnerDTO.class)); } else { dest.setOwner(null); } return dest; }</code><technical_language>In addition checking for null, TimestampedEntityTranslator is extended, need manually translate created/updated fields</technical_language>

Target:
public PermissionBlueprintDTO populate(ModelTranslator translator, PermissionBlueprint source, PermissionBlueprintDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("destination is null"); } PermissionType type = source.getType(); Access access = source.getAccess(); dest.created(source.getCreated() != null ? source.getCreated().toInstant().atOffset(ZoneOffset.UTC) : null) .updated(source.getUpdated() != null ? source.getUpdated().toInstant().atOffset(ZoneOffset.UTC) : null) .id(source.getId()) .type(type != null ? type.name() : null) .access(access != null ? access.name() : null); if (translator != null) { dest.setOwner(translator.translate(source.getOwner(), NestedOwnerDTO.class)); } else { dest.setOwner(null); } return dest; }
Source:
<code>static void validateDatasourceName(String dataSource) { Preconditions.checkArgument( !Strings.isNullOrEmpty(dataSource), "dataSource cannot be null or empty. Please provide a dataSource." ); Preconditions.checkArgument(!dataSource.contains("/"), "dataSource cannot contain the '/' character."); Preconditions.checkArgument( <START> !dataSource.matches("(?s)(.*)\\s(.*)"), <END> "dataSource cannot contain whitespace character." ); }</code><technical_language>forbidden apis check is flagging error here: > [ERROR] Forbidden method invocation: java.lang.String#matches(java.lang.String) [Use startsWith(), endsWith(), contains(), compile cache a Pattern explicitly] regex more complicated necessary is causing test failures: <LINK_0> [ERROR] testIsTaskCurrent[numThreads = 1](org.apache.druid.indexing.kafka.supervisor.KafkaSupervisorTest) Time elapsed: 0.142 s <<< ERROR! java.lang.IllegalArgumentException: dataSource whitespace character. com.google.common.base.Preconditions.checkArgument(Preconditions.java:125) org.apache.druid.segment.indexing.DataSchema.validateDatasourceName(DataSchema.java:108) org.apache.druid.segment.indexing.DataSchema.<init>(DataSchema.java:76) org.apache.druid.indexing.kafka.supervisor.KafkaSupervisorTest.getDataSchema(KafkaSupervisorTest.java:3636) org.apache.druid.indexing.kafka.supervisor.KafkaSupervisorTest.testIsTaskCurrent(KafkaSupervisorTest.java:3099)</technical_language>

Target:
static void validateDatasourceName(String dataSource) { Preconditions.checkArgument( !Strings.isNullOrEmpty(dataSource), "dataSource cannot be null or empty. Please provide a dataSource." ); Matcher m = INVALIDCHARS.matcher(dataSource); Preconditions.checkArgument( !m.matches(), "dataSource cannot contain whitespace character except space." ); Preconditions.checkArgument(!dataSource.contains("/"), "dataSource cannot contain the '/' character."); }
Source:
<code>public List<Long> getDurationList(String path, TimeUnit unit) { List<Long> l = new ArrayList<Long>(); List<? extends ConfigValue> list = getList(path); for (ConfigValue v : list) { if (v.valueType() == ConfigValueType.NUMBER) { Long n = unit.convert( ((Number) v.unwrapped()).longValue(), TimeUnit.MILLISECONDS); l.add(n); } else if (v.valueType() == ConfigValueType.STRING) { String s = (String) v.unwrapped(); Long n = unit.convert( parseDuration(s, v.origin(), path), TimeUnit.NANOSECONDS); l.add(n); } else { throw new ConfigException.WrongType(v.origin(), path, <START> "duration string or number of " + unit.name(), <END> v.valueType().name()); } } return l; }</code><technical_language>original error problem, if a number a string, is milliseconds I believe. this sort of misleading</technical_language>

Target:
public List<Long> getDurationList(String path, TimeUnit unit) { List<Long> l = new ArrayList<Long>(); List<? extends ConfigValue> list = getList(path); for (ConfigValue v : list) { if (v.valueType() == ConfigValueType.NUMBER) { Long n = unit.convert( ((Number) v.unwrapped()).longValue(), TimeUnit.MILLISECONDS); l.add(n); } else if (v.valueType() == ConfigValueType.STRING) { String s = (String) v.unwrapped(); Long n = unit.convert( parseDuration(s, v.origin(), path), TimeUnit.NANOSECONDS); l.add(n); } else { throw new ConfigException.WrongType(v.origin(), path, "duration string or number of milliseconds", v.valueType().name()); } } return l; }
Source:
<code>public void processQueuedQueries() { <START> synchronized (getRoot()) { <END> internalRefreshStats(); while (internalStartNext()) { } } }</code><technical_language>do need call getRoot() return root? function call serve purpose? If remove avoid overhead</technical_language>

Target:
public void processQueuedQueries() { synchronized (super.root) { internalRefreshStats(); while (internalStartNext()) { } } }
Source:
<code>public String idFromValue (Object o) { if (o instanceof CustomModification) { Object r5type = ((CustomModification)o).getFreeformProperties().get("r5type"); if (r5type instanceof String) { <START> return (String)r5type; <END> } } return modificationTypes.inverse().get(o.getClass()); }</code><technical_language>Space cast? Also, log a warning in else clause here</technical_language>

Target:
public String idFromValue (Object o) { if (o instanceof CustomModificationHolder) { Object r5type = ((CustomModificationHolder) o).getFreeformProperties().get("r5type"); if (r5type instanceof String) { return (String)r5type; } else { LOG.error("The r5type property of a custom modification was not a String. " + "The R5 worker will not be able to deserialize and use the resulting R5 modification."); return null; } } return modificationTypes.inverse().get(o.getClass()); }
Source:
<code>public String waitForUpdatedStringInLog(String regexp, long timeout, File outputFile, int previousOccurrences) { <START> int waited = 0; <END> final int waitIncrement = 500; log(MessageFormat.format(messages.getString("info.search.string"), regexp, outputFile.getAbsolutePath(), timeout / 1000)); try { while (waited <= timeout) { List<String> matches = findStringsInFileCommon(regexp, false, -1, outputFile, Project.MSG_VERBOSE); if (matches == null || matches.size() <= previousOccurrences) { try { Thread.sleep(waitIncrement); } catch (InterruptedException e) { } waited += waitIncrement; } else { String line = matches.get(matches.size() - 1); log(MessageFormat.format(messages.getString("info.match.string"), matches.size(), line), Project.MSG_INFO); return line; } } log(MessageFormat.format(messages.getString("error.serch.string.timeout"), regexp, outputFile.getAbsolutePath())); } catch (Exception e) { throw new BuildException(e); } return null; }</code><technical_language>I waited waitIncrement of type long timeout is</technical_language>

Target:
public String waitForUpdatedStringInLog(String regexp, long timeout, File outputFile, int previousOccurrences) { long waited = 0; final long waitIncrement = 500; log(MessageFormat.format(messages.getString("info.search.string"), regexp, outputFile.getAbsolutePath(), timeout / 1000)); while (waited <= timeout) { List<String> matches = findStringsInFileCommon(regexp, false, -1, outputFile, Project.MSG_VERBOSE); if (matches == null || matches.size() <= previousOccurrences) { try { Thread.sleep(waitIncrement); } catch (InterruptedException e) { } waited += waitIncrement; } else { String line = matches.get(matches.size() - 1); log(MessageFormat.format(messages.getString("info.match.string"), matches.size(), line), Project.MSG_INFO); return line; } } log(MessageFormat.format(messages.getString("error.serch.string.timeout"), regexp, outputFile.getAbsolutePath())); return null; }
Source:
<code>public String getQuestionResultStatisticsHtml( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if ("student".equals(view) || responses.isEmpty()) { return ""; } StringBuilder fragments = new StringBuilder(100); Map<String, List<Integer>> optionRanks = generateOptionRanksMapping(responses); DecimalFormat df = new DecimalFormat("#.##"); for (Entry<String, List<Integer>> entry : optionRanks.entrySet()) { List<Integer> ranks = entry.getValue(); double average = computeAverage(ranks); String ranksReceived = getListOfRanksReceivedAsString(ranks); String option = entry.getKey(); fragments.append(Templates.populateTemplate(FormTemplates.RANK_RESULT_STATS_OPTIONFRAGMENT, Slots.RANK_OPTION_VALUE, Sanitizer.sanitizeForHtml(option), "${ranksReceived}", ranksReceived, <START> "${averageRank}", df.format(average))); <END> } return Templates.populateTemplate(FormTemplates.RANK_RESULT_OPTION_STATS, Slots.OPTION_RECIPIENT_DISPLAY_NAME, "Option", "${fragments}", fragments.toString()); }</code><technical_language>guessing previous level of indentation bust line length limit. In case, align other parameters below</technical_language>

Target:
public String getQuestionResultStatisticsHtml( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if ("student".equals(view) || responses.isEmpty()) { return ""; } StringBuilder fragments = new StringBuilder(100); Map<String, List<Integer>> optionRanks = generateOptionRanksMapping(responses); DecimalFormat df = new DecimalFormat("#.##"); for (Entry<String, List<Integer>> entry : optionRanks.entrySet()) { List<Integer> ranks = entry.getValue(); double average = computeAverage(ranks); String ranksReceived = getListOfRanksReceivedAsString(ranks); String option = entry.getKey(); fragments.append(Templates.populateTemplate(FormTemplates.RANK_RESULT_STATS_OPTIONFRAGMENT, Slots.RANK_OPTION_VALUE, Sanitizer.sanitizeForHtml(option), Slots.RANK_RECIEVED, ranksReceived, Slots.RANK_AVERAGE, df.format(average))); } return Templates.populateTemplate(FormTemplates.RANK_RESULT_OPTION_STATS, Slots.OPTION_RECIPIENT_DISPLAY_NAME, "Option", Slots.FRAGMENTS, fragments.toString()); }
Source:
<code>static void assertAccountInAccountService(Account account, AccountService accountService) { Objects.requireNonNull(account, "account cannot be null"); Objects.requireNonNull(accountService, "accountService cannot be null"); Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); <START> assertEquals("Account got by id from accountService does not match account got by name.", accountFoundById, <END> accountFoundByName); assertEquals("Account got by id from accountService does not match the assert to assert", accountFoundById, account); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }</code><technical_language>comparing field in Account</technical_language>

Target:
static void assertAccountInAccountService(Account account, AccountService accountService) { Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); assertEquals("Account got by id from accountService does not match account got by name.", accountFoundById, accountFoundByName); assertEquals("Account got by id from accountService does not match the assert to assert", accountFoundById, account); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }
Source:
<code>protected void releaseLock( @Nonnull final String sessionId ) { try { if ( _log.isDebugEnabled() ) { _log.debug( "Releasing lock for session " + sessionId ); } final long start = System.currentTimeMillis(); _memcached.delete( _sessionIdFormat.createLockName( sessionId ) ); _stats.registerSince( RELEASE_LOCK, start ); <START> } catch ( final IOException e ) { <END> _log.warn( "Caught exception when trying to release lock for session " + sessionId, e ); } }</code><technical_language>catch Exception here</technical_language>

Target:
protected void releaseLock( @Nonnull final String sessionId ) { try { if ( _log.isDebugEnabled() ) { _log.debug( "Releasing lock for session " + sessionId ); } final long start = System.currentTimeMillis(); _memcached.delete( _sessionIdFormat.createLockName( sessionId ) ).get(); _stats.registerSince( RELEASE_LOCK, start ); } catch ( final Exception e ) { _log.warn( "Caught exception when trying to release lock for session " + sessionId, e ); } }
Source:
<code>public static Object codeLogger(int code) { <START> return new CodeLogFormatter(code); <END> }</code><technical_language>number of rc is limited a pool save memory allocations? this code executed write path read path</technical_language>

Target:
public static Object codeLogger(int code) { return logMessagePool.get(code); }
Source:
<code>protected String getTextTransform(String text, CSSValue value, String defaultText) { if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) { CSSPrimitiveValue primitiveValue = (CSSPrimitiveValue) value; String textTransform = primitiveValue.getStringValue(); if ("capitalize".equals(textTransform)) { return StringUtils.capitalize(text); } if <START> ("uppercase".equals(textTransform)) { <END> if (text != null) { return text.toUpperCase(); } } if ("lowercase".equals(textTransform)) { if (text != null) { return text.toLowerCase(); } } if ("inherit".equals(textTransform)) { return text; } } if (defaultText != null) { return defaultText; } return text; }</code><technical_language>"uppercase".equals(textTransform) && text != null</technical_language>

Target:
protected String getTextTransform(String text, CSSValue value, String defaultText) { if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) { CSSPrimitiveValue primitiveValue = (CSSPrimitiveValue) value; String textTransform = primitiveValue.getStringValue(); if ("capitalize".equals(textTransform)) { return StringUtils.capitalize(text); } if ("uppercase".equals(textTransform) && text != null) { return text.toUpperCase(); } if ("lowercase".equals(textTransform) && text != null) { return text.toLowerCase(); } if ("inherit".equals(textTransform)) { return text; } } if (defaultText != null) { return defaultText; } return text; }
Source:
<code>public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginArray(); <START> for (int k = 0; k < stacktrace.length && k < STACKTRACE_TRIM_LENGTH; k++) { <END> StackTraceElement el = stacktrace[k]; try { writer.beginObject(); writer.name("method").value(el.getClassName() + "." + el.getMethodName()); writer.name("file").value(el.getFileName() == null ? "Unknown" : el.getFileName()); writer.name("lineNumber").value(el.getLineNumber()); if (config.inProject(el.getClassName())) { writer.name("inProject").value(true); } writer.endObject(); } catch (Exception lineEx) { Logger.warn("Failed to serialise stacktrace", lineEx); } } writer.endArray(); }</code><technical_language>understanding of this change is omits 200 values in stacktrace serializing. work if report fails send? serialized report get saved storage original report entity get saved? get is unruly stacktrace reallocated some memory and/or persistent storage is passed in reference operated in initially allocated memory</technical_language>

Target:
public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginArray(); for (int k = 0; k < stacktrace.length && k < STACKTRACE_TRIM_LENGTH; k++) { StackTraceElement el = stacktrace[k]; try { writer.beginObject(); writer.name("method").value(el.getClassName() + "." + el.getMethodName()); writer.name("file").value(el.getFileName() == null ? "Unknown" : el.getFileName()); writer.name("lineNumber").value(el.getLineNumber()); if (config.inProject(el.getClassName())) { writer.name("inProject").value(true); } writer.endObject(); } catch (Exception lineEx) { Logger.warn("Failed to serialize stacktrace", lineEx); } } writer.endArray(); }
Source:
<code>public Object[][] dataArgumentValidation() { return new Object[][]{ {new String[]{"--" + SITE_FREQUENCY_LONG_NAME, "0"}}, {new String[]{"--" + SITE_FREQUENCY_LONG_NAME, "10"}}, <START> {new String[]{"--" + SITE_FREQUENCY_LONG_NAME, "-1"}} <END> }; }</code><technical_language>Space []</technical_language>

Target:
public Object[][] dataArgumentValidation() { return new Object[][]{ {new String[]{"--" + SITE_FREQUENCY_THRESHOLD_LONG_NAME, "0"}}, {new String[]{"--" + SITE_FREQUENCY_THRESHOLD_LONG_NAME, "10"}}, {new String[]{"--" + SITE_FREQUENCY_THRESHOLD_LONG_NAME, "-1"}} }; }
Source:
<code>public static Map<String,String> getOverrides(List<String> args) { Map<String,String> config = new HashMap<>(); List<String> allproperties = ListUtils.union(args, deprecated_overrides); for (String prop : allproperties) { String[] propArgs = prop.split("=", 2); String key = propArgs[0].trim(); String value = ""; if (propArgs.length == 2) { value = propArgs[1].trim(); } else { <START> value = String.valueOf(Property.isValidBooleanPropertyKey(key)); <END> } if (key.isEmpty() || value.isEmpty()) { throw new IllegalArgumentException("Invalid command line -o option: " + prop); } else { config.put(key, value); } } return config; }</code><technical_language>+1: This is a nice addition. However, I suggest empty string if a boolean value, set "false", instead catches IllegalArgumentException below. suggestion = Property.isValidBooleanPropertyKey(key) ? "true" : "";</technical_language>

Target:
public static Map<String,String> getOverrides(List<String> args) { Map<String,String> config = new HashMap<>(); for (String prop : args) { String[] propArgs = prop.split("=", 2); String key = propArgs[0].trim(); String value; if (propArgs.length == 2) { value = propArgs[1].trim(); } else { value = Property.isValidBooleanPropertyKey(key) ? "true" : ""; } if (key.isEmpty() || value.isEmpty()) { throw new IllegalArgumentException("Invalid command line -o option: " + prop); } config.put(key, value); } return config; }
Source:
<code>protected void setValue(T value) { currentError = null; if (value != null) { this.value = value; for (Observer<T> observer : observers) <START> observer.onValue(value); <END> } }</code><technical_language>Delimit for-loop body braces code style</technical_language>

Target:
protected void setValue(T value) { currentError = null; if (value != null) { this.value = value; for (Observer<T> observer : observers) { observer.onValue(value); } } }
Source:
<code>public RecipeBrew read(@Nonnull Identifier id, @Nonnull JsonObject json) { String brewStr = JsonHelper.getString(json, "brew"); Identifier brewId = Identifier.tryParse(brewStr); <START> if (brewId == null || BotaniaAPI.instance().getBrewRegistry().get(brewId) == ModBrews.fallbackBrew) { <END> throw new JsonParseException("Unknown brew " + brewStr); } Brew brew = BotaniaAPI.instance().getBrewRegistry().get(brewId); JsonArray ingrs = JsonHelper.getArray(json, "ingredients"); List<Ingredient> inputs = new ArrayList<>(); for (JsonElement e : ingrs) { inputs.add(Ingredient.fromJson(e)); } return new RecipeBrew(id, brew, inputs.toArray(new Ingredient[0])); }</code><technical_language>explain this below? existing check work</technical_language>

Target:
public RecipeBrew read(@Nonnull Identifier id, @Nonnull JsonObject json) { String brewStr = JsonHelper.getString(json, "brew"); Identifier brewId = Identifier.tryParse(brewStr); if (brewId == null || !BotaniaAPI.instance().getBrewRegistry().getOrEmpty(brewId).isPresent()) { throw new JsonParseException("Unknown brew " + brewStr); } Brew brew = BotaniaAPI.instance().getBrewRegistry().get(brewId); JsonArray ingrs = JsonHelper.getArray(json, "ingredients"); List<Ingredient> inputs = new ArrayList<>(); for (JsonElement e : ingrs) { inputs.add(Ingredient.fromJson(e)); } return new RecipeBrew(id, brew, inputs.toArray(new Ingredient[0])); }
Source:
<code>public void draw(GameDrawer drawer, SolGame game) { SolCam cam = game.getCam(); float iconSz = getIconRadius(cam) * 2; float starNodeW = cam.getViewHeight(zoom) * STAR_NODE_SZ; float viewDist = cam.getViewDistance(zoom); FactionManager factionManager = game.getFactionMan(); Hero hero = game.getHero(); Planet np = game.getPlanetManager().getNearestPlanet(); Vector2 camPos = cam.getPosition(); float camAngle = cam.getAngle(); float heroDmgCap = hero.isTranscendent() ? Float.MAX_VALUE : HardnessCalc.getShipDmgCap(hero.getShip()); drawer.updateMatrix(game); game.getGridDrawer().draw(drawer, game, GRID_SZ, lineTexture); drawPlanets(drawer, game, viewDist, np, camPos, heroDmgCap, camAngle); drawMazes(drawer, game, viewDist, np, camPos, heroDmgCap, camAngle); drawStarNodes(drawer, game, viewDist, camPos, starNodeW); <START> drawWaypoints(drawer, game, iconSz, viewDist); <END> drawIcons(drawer, game, iconSz, viewDist, factionManager, hero, camPos, heroDmgCap); }</code><technical_language>add newline drawWaypoints call</technical_language>

Target:
public void draw(GameDrawer drawer, SolGame game) { SolCam cam = game.getCam(); float iconSz = getIconRadius(cam) * 2; float starNodeW = cam.getViewHeight(zoom) * STAR_NODE_SZ; float viewDist = cam.getViewDistance(zoom); FactionManager factionManager = game.getFactionMan(); Hero hero = game.getHero(); Planet np = game.getPlanetManager().getNearestPlanet(); Vector2 camPos = cam.getPosition(); float camAngle = cam.getAngle(); float heroDmgCap = hero.isTranscendent() ? Float.MAX_VALUE : HardnessCalc.getShipDmgCap(hero.getShip()); drawer.updateMatrix(game); game.getGridDrawer().draw(drawer, game, GRID_SZ, lineTexture); drawPlanets(drawer, game, viewDist, np, camPos, heroDmgCap, camAngle); drawMazes(drawer, game, viewDist, np, camPos, heroDmgCap, camAngle); drawStarNodes(drawer, game, viewDist, camPos, starNodeW); drawWaypoints(drawer, game, iconSz, viewDist); drawIcons(drawer, game, iconSz, viewDist, factionManager, hero, camPos, heroDmgCap); if (game.getScreens().mapScreen.isPickingWaypointSpot()) { drawer.drawString("Click a spot for the new waypoint", hero.getPosition().x, hero.getPosition().y + (zoom* 1.5f), 0.125f * zoom, true, Color.RED); } if (game.getScreens().mapScreen.isPickingWaypointToRemove()) { drawer.drawString("Click a waypoint to remove", hero.getPosition().x, hero.getPosition().y + (zoom* 1.5f), 0.125f * zoom, true, Color.RED); } }
Source:
<code>Tracing.Builder tracingBuilder(Sampler sampler) { return Tracing.newBuilder() .spanReporter(spans::add) <START> .currentTraceContext(ThreadLocalCurrentTraceContext.create()) <END> .sampler(sampler); }</code><technical_language>add strict scope decorator</technical_language>

Target:
Tracing.Builder tracingBuilder(Sampler sampler) { return Tracing.newBuilder() .spanReporter(spans::add) .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() .addScopeDecorator(StrictScopeDecorator.create()) .build()) .sampler(sampler); }
Source:
<code>public void listPartitionSpliterator() { IterableView<List<String>> view = IterableView.of(ImmutableList.of("a", "b", "c")).partition(1); Spliterator<List<String>> spliterator = view.spliterator(); assertThat(spliterator.estimateSize()).isEqualTo(3); int characteristics = spliterator.characteristics(); assertThat(characteristics).isNotEqualTo(0); assertThat(characteristics & Spliterator.CONCURRENT).isEqualTo(0); assertThat(characteristics & Spliterator.DISTINCT).isEqualTo(0); <START> assertThat(characteristics & Spliterator.IMMUTABLE).isEqualTo(0); <END> assertThat(characteristics & Spliterator.NONNULL).isEqualTo(0); assertThat(characteristics & Spliterator.SIZED).isEqualTo(Spliterator.SIZED); assertThat(characteristics & Spliterator.SORTED).isEqualTo(0); assertThat(characteristics & Spliterator.SUBSIZED).isEqualTo(Spliterator.SUBSIZED); }</code><technical_language>tests fragile changes elsewhere. For example, super reasonable for Guava's Iterables.partition claim non-null (always) immutable (given immutable input), for change in some version of Guava. I propose test this a single test, simply validates spliterator characteristics identical if call delegate().spliterator() spliterator()</technical_language>

Target:
public void listPartitionSpliterator() { ImmutableList<String> delegate = ImmutableList.of("a", "b", "c"); IterableView<List<String>> view = IterableView.of(delegate).partition(1); Spliterator<List<String>> spliterator = view.spliterator(); assertThat(spliterator.estimateSize()).isEqualTo(3); assertThat(spliterator.characteristics()).isNotZero(); assertThat(spliterator.hasCharacteristics(Spliterator.SIZED)).isTrue(); assertThat(spliterator.hasCharacteristics(Spliterator.SUBSIZED)).isTrue(); assertThat(StreamSupport.stream(spliterator, false)).containsExactly( ImmutableList.of("a"), ImmutableList.of("b"), ImmutableList.of("c")); }
Source:
<code><START> public void testRegisterPositionProvider() { final GuidedTourCustomSelectorPositionProvider positionProvider = mock(GuidedTourCustomSelectorPositionProvider.class); final PositionProviderFunction positionProviderFunction = mock(PositionProviderFunction.class); final String type = "type"; doReturn(positionProvider).when(bridge).getPositionProviderInstance(); bridge.registerPositionProvider(type, positionProviderFunction); verify(bridge).registerPositionProvider(type, positionProviderFunction); } <END></code><technical_language>This test is correct</technical_language>

Target:
public void testRegisterPositionProvider() { final GuidedTourCustomSelectorPositionProvider positionProvider = mock(GuidedTourCustomSelectorPositionProvider.class); final PositionProviderFunction positionProviderFunction = mock(PositionProviderFunction.class); final String type = "type"; doReturn(positionProvider).when(bridge).getPositionProviderInstance(); bridge.registerPositionProvider(type, positionProviderFunction); verify(positionProvider).registerPositionProvider(type, positionProviderFunction); }
Source:
<code>private static int zzUnpackAttribute() { int[] result = new int[184]; <START> int offset = 0; <END> zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; }</code><technical_language>kill offset pass 0</technical_language>

Target:
private static int zzUnpackAttribute() { int result = new int[184]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; }
Source:
<code>public void start() { <START> INSTANCE = this; <END> }</code><technical_language>fix</technical_language>

Target:
public void start() { instance = this; }
Source:
<code>private void checkCacheReload() { if (nextLoadTime > System.currentTimeMillis()) { return; } if (nextLoadTime > 0) { LOG.info("Lookup join cache has expired after minute(s), reloading", getCacheTTL().toMinutes()); } else { LOG.info("Populating lookup join cache"); } int numRetry = 0; while (true) { cache.clear(); try { T[] inputSplits = inputFormat.createInputSplits(1); GenericRowData reuse = new GenericRowData(producedNames.length); long count = 0; for (T split : inputSplits) { inputFormat.open(split); while (!inputFormat.reachedEnd()) { RowData row = inputFormat.nextRecord(reuse); count++; Row key = extractKey(row); List<RowData> rows = cache.computeIfAbsent(key, k -> new ArrayList<>()); rows.add(serializer.copy(row)); } inputFormat.close(); } nextLoadTime = System.currentTimeMillis() + getCacheTTL().toMillis(); LOG.info("Loaded row(s) into lookup join cache", count); return; } catch (IOException e) { if (numRetry >= MAX_RETRIES) { throw new FlinkRuntimeException( String.format("Failed to load table into cache after %d retries", numRetry), e); } <START> long toSleep = ++numRetry * RETRY_INTERVAL.toMillis(); <END> LOG.warn(String.format("Failed to load table into cache, will retry in %d seconds", toSleep / 1000), e); try { Thread.sleep(toSleep); } catch (InterruptedException ex) { LOG.warn("Interrupted while waiting to retry failed cache load, aborting"); throw new FlinkRuntimeException(ex); } } } }</code><technical_language>single line numRetry ++</technical_language>

Target:
private void checkCacheReload() { if (nextLoadTime > System.currentTimeMillis()) { return; } if (nextLoadTime > 0) { LOG.info("Lookup join cache has expired after minute(s), reloading", getCacheTTL().toMinutes()); } else { LOG.info("Populating lookup join cache"); } int numRetry = 0; while (true) { cache.clear(); try { T[] inputSplits = inputFormat.createInputSplits(1); GenericRowData reuse = new GenericRowData(producedNames.length); long count = 0; for (T split : inputSplits) { inputFormat.open(split); while (!inputFormat.reachedEnd()) { RowData row = inputFormat.nextRecord(reuse); count++; Row key = extractKey(row); List<RowData> rows = cache.computeIfAbsent(key, k -> new ArrayList<>()); rows.add(serializer.copy(row)); } inputFormat.close(); } nextLoadTime = System.currentTimeMillis() + getCacheTTL().toMillis(); LOG.info("Loaded row(s) into lookup join cache", count); return; } catch (IOException e) { if (numRetry >= MAX_RETRIES) { throw new FlinkRuntimeException( String.format("Failed to load table into cache after %d retries", numRetry), e); } numRetry++; long toSleep = numRetry * RETRY_INTERVAL.toMillis(); LOG.warn(String.format("Failed to load table into cache, will retry in %d seconds", toSleep / 1000), e); try { Thread.sleep(toSleep); } catch (InterruptedException ex) { LOG.warn("Interrupted while waiting to retry failed cache load, aborting"); throw new FlinkRuntimeException(ex); } } } }
Source:
<code>protected PerPartitionCategorizationConfig createTestInstance() { boolean enabled = randomBoolean(); <START> return new PerPartitionCategorizationConfig(enabled, enabled && randomBoolean()); <END> }</code><technical_language>suggestion return new PerPartitionCategorizationConfig(enabled, randomBoolean() ? null : enabled && randomBoolean());</technical_language>

Target:
protected PerPartitionCategorizationConfig createTestInstance() { boolean enabled = randomBoolean(); return new PerPartitionCategorizationConfig(enabled, randomBoolean() ? null : enabled && randomBoolean()); }
Source:
<code>private VipAddressResolver getVipAddressResolver() { if (resolver == null) { synchronized (this) { if (resolver == null) { try { resolver = (VipAddressResolver) Class.forName( (String) getProperty(CommonClientConfigKey.VipAddressResolverClassName)).newInstance(); <START> } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) { <END> LOG.error("Cannot instantiate VipAddressResolver", e); } } } } return resolver; }</code><technical_language>This a recoverable scenario, re-throwing this one? is some default/fallback VipAddressResolver if instantiation fails here</technical_language>

Target:
private VipAddressResolver getVipAddressResolver() { if (resolver == null) { synchronized (this) { if (resolver == null) { try { resolver = (VipAddressResolver) Class .forName((String) getProperty(CommonClientConfigKey.VipAddressResolverClassName)) .newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Cannot instantiate VipAddressResolver", e); } } } } return resolver; }
Source:
<code>int processFilterHits(int inputIndex, int outputIndex, int[] resultRows, int[] resultInputNumbers, int numElementResults) { int filterHits = 0; int count = 0; <START> int initialOutputIndex = outputIndex; <END> if (presentStream != null && !present[inputQualifyingSet.getPositions()[inputIndex] - posInRowGroup]) { return outputIndex; } int[] inputNumbers = innerQualifyingSet.getInputNumbers(); int startOfArray = elementStart[inputIndex]; while (outputIndex < numElementResults && inputNumbers[resultInputNumbers[outputIndex]] == inputIndex) { count++; int posInArray = resultRows[outputIndex] - startOfArray; if (elementFilters[filterOffset + posInArray] != null) { filterHits++; } outputIndex++; } filterOffset += elementLength[inputIndex]; if (filterHits < numElementFilters[inputIndex]) { return outputIndex; } outputQualifyingSet.append(inputQualifyingSet.getPositions()[inputIndex], inputIndex); addArrayToResult(inputIndex, initialOutputIndex, outputIndex); int total = localNumFilters != null ? localNumFilters[inputIndex] : globalNumFilters; if (numElementFilters[inputIndex] < total) { ErrorSet errorSet = outputQualifyingSet.getOrCreateErrorSet(); errorSet.addError(outputQualifyingSet.getPositionCount() - 1, inputQualifyingSet.getPositionCount(), new MissingSubscriptException()); } return outputIndex; }</code><technical_language>this variable is</technical_language>

Target:
private int processFilterHits(int inputIndex, int outputIndex, int[] resultRows, int[] resultInputNumbers, int numElementResults) { int filterHits = 0; int initialOutputIndex = outputIndex; if (presentStream != null && !present[inputQualifyingSet.getPositions()[inputIndex] - posInRowGroup]) { return outputIndex; } int[] inputNumbers = innerQualifyingSet.getInputNumbers(); int startOfArray = elementStart[inputIndex]; while (outputIndex < numElementResults && inputNumbers[resultInputNumbers[outputIndex]] == inputIndex) { int posInArray = resultRows[outputIndex] - startOfArray; if (elementFilters[filterOffset + posInArray] != null) { filterHits++; } outputIndex++; } filterOffset += elementLength[inputIndex]; if (filterHits < numElementFilters[inputIndex]) { return outputIndex; } outputQualifyingSet.append(inputQualifyingSet.getPositions()[inputIndex], inputIndex); addArrayToResult(inputIndex, initialOutputIndex, outputIndex); int total = localNumFilters != null ? localNumFilters[inputIndex] : globalNumFilters; if (numElementFilters[inputIndex] < total) { ErrorSet errorSet = outputQualifyingSet.getOrCreateErrorSet(); errorSet.addError(outputQualifyingSet.getPositionCount() - 1, inputQualifyingSet.getPositionCount(), new MissingSubscriptException()); } return outputIndex; }
Source:
<code>public Collection<String> populatePlatformTypes() throws IOException { Collection<PlatformType> platforms = requestManager.listActivePlatformTypes(); if (platforms.size() > 0) { <START> return PlatformType.platformTypeNames(requestManager.listActivePlatformTypes()); <END> } else { return requestManager.listDistinctPlatformNames(); } }</code><technical_language>return PlatformType.platformTypeNames(platforms); instead of lookup</technical_language>

Target:
public Collection<String> populatePlatformTypes() throws IOException { Collection<PlatformType> platforms = requestManager.listActivePlatformTypes(); if (platforms.size() > 0) { return PlatformType.platformTypeNames(platforms); } else { return requestManager.listDistinctPlatformNames(); } }
Source:
<code>public void testFailOnIncrementInt() throws IOException { Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = dataHelper.randomData("testrow-"); byte[] qual = dataHelper.randomData("qual-"); int value = new Random().nextInt(); Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, Bytes.toBytes(value)); table.put(put); Increment increment = new Increment(rowKey).addColumn(COLUMN_FAMILY, qual, 1L); expectedException.expect(DoNotRetryIOException.class); <START> ; <END> expectedException.expectMessage( anyOf( containsString("Attempted to increment field that isn't 64 bits wide"), containsString("Field is not a long") ) ); table.increment(increment); }</code><technical_language>extra ;</technical_language>

Target:
public void testFailOnIncrementInt() throws IOException { Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = dataHelper.randomData("testrow-"); byte[] qual = dataHelper.randomData("qual-"); int value = new Random().nextInt(); Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, Bytes.toBytes(value)); table.put(put); Increment increment = new Increment(rowKey).addColumn(COLUMN_FAMILY, qual, 1L); expectedException.expect(DoNotRetryIOException.class); expectedException.expectMessage( anyOf( containsString("Attempted to increment field that isn't 64 bits wide"), containsString("Field is not a long") ) ); table.increment(increment); }
Source:
<code><START> public void testPackageInstallerInstallSourceIsParsedCorrectly() { <END> final InstallSource installSource = InstallSource.fromInstallerPackageName("com.google.android.packageinstaller"); assertTrue(installSource instanceof PackageInstallerInstallSource); assertEquals("Package Installer", installSource.toString()); }</code><technical_language><b>Reporter: </b>PMD<br /><b>Violation: </b><a target="_blank" href="<LINK_0>">JUnitTestContainsTooManyAsserts</a><br /><b>Notes: </b>JUnit tests more 1 assert(s)</technical_language>

Target:
public void testPackageInstallerInstallSourceIsParsedCorrectly() { final InstallSource installSource = InstallSource.fromInstallerPackageName("com.google.android.packageinstaller"); assertTrue( "Package name is correctly identified as belonging to the Android Package Installer", installSource instanceof PackageInstallerInstallSource); assertEquals( "Package Installer install source has correct description", "Package Installer", installSource.toString()); }
Source:
<code>@Override public void isEqualTo(Object expected) { if (getSubject() == null) { <START> if(expected != null) { <END> if (expected instanceof String) { failWithRawMessage("Not true that null reference is equal to <%s>", wrap((String) expected)); } else { failWithRawMessage("Not true that null reference is equal to (%s)<%s>", expected.getClass().getName(), expected); } } } else { if(expected == null) { isNull(); } else if (!(expected instanceof String)) { failWithRawMessage("Not true that <\"%s\"> is equal to (%s)<%s>", getSubject(), expected.getClass().getName(), expected); } else if (!getSubject().equals(expected)) { if (expected instanceof String) { failureStrategy.failComparing("", (String) expected, getSubject()); } else { failWithRawMessage("Not true that %s equal to (%s)<%s>", getDisplaySubject(), expected.getClass().getName(), expected); } } } }</code><technical_language>nit: space if</technical_language>

Target:
@Override public void isEqualTo(Object expected) { if (getSubject() == null) { if (expected != null) { if (expected instanceof String) { failWithRawMessage("Not true that null reference is equal to <%s>", quote((String) expected)); } else { failWithRawMessage("Not true that null reference is equal to (%s)<%s>", expected.getClass().getName(), expected); } } } else { if (expected == null) { isNull(); } else if (!(expected instanceof String)) { failWithRawMessage("Not true that <\"%s\"> is equal to (%s)<%s>", getSubject(), expected.getClass().getName(), expected); } else if (!getSubject().equals(expected)) { if (expected instanceof String) { failureStrategy.failComparing("", (String) expected, getSubject()); } else { failWithRawMessage("Not true that %s equal to (%s)<%s>", getDisplaySubject(), expected.getClass().getName(), expected); } } } }
Source:
<code>public void testVariableBindings() throws Exception { SelectionScript script = new SelectionScript("variables.get(\"TOTO\")", "groovy", false); ManagerObjects managerObjects = new ManagerObjects(1).invoke(); SelectionManager selectionManager = managerObjects.getSelectionManager(); ArrayList<RMNode> freeNodes = managerObjects.getFreeNodes(); <START> <END> selectionManager.processScriptResult(script, Collections.singletonMap("TOTO", (Serializable) "value"), new ScriptResult<>(true), freeNodes.get(0)); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", (Serializable) "value"), freeNodes.get(0))); Assert.assertFalse(selectionManager.isPassed(script, Collections.singletonMap("TOTO", (Serializable) "differentValue"), freeNodes.get(0))); Assert.assertFalse(selectionManager.isPassed(script, Collections.<String, Serializable> emptyMap(), freeNodes.get(0))); selectionManager.processScriptResult(script, Collections.singletonMap("TOTO", (Serializable) "differentValue"), new ScriptResult<>(true), freeNodes.get(0)); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", (Serializable) "differentValue"), freeNodes.get(0))); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", (Serializable) "value"), freeNodes.get(0))); }</code><technical_language>I add more check, for example bindings a map keys, want verify if script is key, isPassed change key changes</technical_language>

Target:
public void testVariableBindings() throws Exception { SelectionScript script = new SelectionScript("variables.get(\"TOTO\")", "groovy", false); ManagerObjects managerObjects = new ManagerObjects(1).invoke(); SelectionManager selectionManager = managerObjects.getSelectionManager(); ArrayList<RMNode> freeNodes = managerObjects.getFreeNodes(); selectionManager.processScriptResult(script, Collections.singletonMap("TOTO", "value"), new ScriptResult<>(true), freeNodes.get(0)); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", "value"), freeNodes.get(0))); Assert.assertFalse(selectionManager.isPassed(script, Collections.singletonMap("TOTO", "differentValue"), freeNodes.get(0))); Assert.assertFalse(selectionManager.isPassed(script, Collections.<String, Serializable> emptyMap(), freeNodes.get(0))); selectionManager.processScriptResult(script, Collections.singletonMap("TOTO", "differentValue"), new ScriptResult<>(true), freeNodes.get(0)); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", "differentValue"), freeNodes.get(0))); Assert.assertTrue(selectionManager.isPassed(script, Collections.singletonMap("TOTO", "value"), freeNodes.get(0))); }
Source:
<code>public StoreFileWriter build() throws IOException { if ((dir == null ? 0 : 1) + (filePath == null ? 0 : 1) != 1) { throw new IllegalArgumentException("Either specify parent directory " + "or file path"); } if (dir == null) { dir = filePath.getParent(); } if (!fs.exists(dir)) { HRegionFileSystem.mkdirs(fs, conf, dir); } String policyName = this.conf.get(ColumnFamilyDescriptorBuilder.STORAGE_POLICY); if (null == policyName) { policyName = this.conf.get(HStore.BLOCK_STORAGE_POLICY_KEY); } CommonFSUtils.setStoragePolicy(this.fs, dir, policyName); if (filePath == null) { if (fileStoragePolicy != null && !fileStoragePolicy.isEmpty()) { dir = new Path(dir, HConstants.STORAGE_POLICY_PREFIX + fileStoragePolicy); if (!fs.exists(dir)) { HRegionFileSystem.mkdirs(fs, conf, dir); } CommonFSUtils.setStoragePolicy(this.fs, dir, fileStoragePolicy); if (LOG.isDebugEnabled()) { <START> LOG.debug( <END> "Create tmp dir " + dir.toString() + " with storage policy: " + fileStoragePolicy); } } filePath = getUniqueFile(fs, dir); if (!BloomFilterFactory.isGeneralBloomEnabled(conf)) { bloomType = BloomType.NONE; } } return new StoreFileWriter(fs, filePath, conf, cacheConf, bloomType, maxKeyCount, favoredNodes, fileContext, shouldDropCacheBehind, compactedFilesSupplier); }</code><technical_language>log region created? If so, info log</technical_language>

Target:
public StoreFileWriter build() throws IOException { if ((dir == null ? 0 : 1) + (filePath == null ? 0 : 1) != 1) { throw new IllegalArgumentException("Either specify parent directory " + "or file path"); } if (dir == null) { dir = filePath.getParent(); } if (!fs.exists(dir)) { HRegionFileSystem.mkdirs(fs, conf, dir); } String policyName = this.conf.get(ColumnFamilyDescriptorBuilder.STORAGE_POLICY); if (null == policyName) { policyName = this.conf.get(HStore.BLOCK_STORAGE_POLICY_KEY); } CommonFSUtils.setStoragePolicy(this.fs, dir, policyName); if (filePath == null) { if (!Strings.isNullOrEmpty(fileStoragePolicy)) { dir = new Path(dir, HConstants.STORAGE_POLICY_PREFIX + fileStoragePolicy); if (!fs.exists(dir)) { HRegionFileSystem.mkdirs(fs, conf, dir); LOG.info( "Create tmp dir " + dir.toString() + " with storage policy: " + fileStoragePolicy); } CommonFSUtils.setStoragePolicy(this.fs, dir, fileStoragePolicy); } filePath = getUniqueFile(fs, dir); if (!BloomFilterFactory.isGeneralBloomEnabled(conf)) { bloomType = BloomType.NONE; } } return new StoreFileWriter(fs, filePath, conf, cacheConf, bloomType, maxKeyCount, favoredNodes, fileContext, shouldDropCacheBehind, compactedFilesSupplier); }
Source:
<code><START> private short getLibraryId(final SAMRecord rec) { <END> if (this.libraryIds.size() == 0) { populateLibraryIds(rec.getHeader()); } final String library = getLibraryName(rec); return updateLibraryId(library); }</code><technical_language>I race conditions in some (potentially rare) conditions. If records sam headers ( pre-initializing deprecated constructor) id is dependent order getLibraryID is called in is a race condition. care case expect headers deprecated constructor. happened syncronizing populateTransientAttributes? a ConcurrentHashMap.calculateIfMissing is a good idea</technical_language>

Target:
private short getLibraryId(final SAMRecord rec) { if (this.libraryIds.size() == 0) { populateLibraryIds(Arrays.asList(rec.getHeader())); } final String library = getLibraryName(rec); return updateLibraryId(library); }
Source:
<code>protected void executeQueryCommand() { Guid objectId = getParameters().getObjectId(); List<permissions> perms; if (getParameters().getDirectOnly()) { <START> perms = getPermissionDAO() <END> .getAllForEntity(objectId, getUserID(), getParameters().isFiltered()); } else { perms = getPermissionDAO() .getTreeForEntity(objectId, getParameters().getVdcObjectType(), getUserID(), getParameters().isFiltered()); } getQueryReturnValue().setReturnValue(perms); }</code><technical_language>instead of calling function put if: PermissonDAO permissionDao = getDbFacade().getPermissionDAO(); this if else blocks</technical_language>

Target:
protected void executeQueryCommand() { Guid objectId = getParameters().getObjectId(); PermissionDAO dao = getDbFacade().getPermissionDAO(); List<permissions> perms; if (getParameters().getDirectOnly()) { perms = dao.getAllForEntity(objectId, getUserID(), getParameters().isFiltered()); } else { perms = dao.getTreeForEntity(objectId, getParameters().getVdcObjectType(), getUserID(), getParameters().isFiltered()); } getQueryReturnValue().setReturnValue(perms); }