auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public LogEntry save(LogEntry delegate) throws ResourceDoesNotSupportOperationException { <END> return null; }</code><technical_language>Try fill more of methods bodies copying ideas pull request classes i pointed in ticket description</technical_language>

Target:
public LogEntry save(LogEntry delegate) throws ResourceDoesNotSupportOperationException { throw new ResourceDoesNotSupportOperationException(); }
Source:
<code>public BufferedImage getImage() { final GraphicsConfiguration gc = device.getDefaultConfiguration(); final Rectangle bounds = gc.getBounds(); BufferedImage screen = robot.createScreenCapture(bounds); int width = resolution.width; int height = resolution.height; <START> BufferedImage img = new BufferedImage(width, height, screen.getType()); <END> Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(screen, 0, 0, width, height, 0, 0, screen.getWidth(), screen.getHeight(), null); g.dispose(); return img; }</code><technical_language>Please consider checking if screen image Robot size resolution Dimension return original screen image in a case, do need create resized image unnecessary. java if (screen.getWidth() == width && screen.getHeight() == height) { return screen; }</technical_language>

Target:
public BufferedImage getImage() { final GraphicsConfiguration gc = device.getDefaultConfiguration(); final Rectangle bounds = gc.getBounds(); BufferedImage screen = robot.createScreenCapture(bounds); int width = resolution.width; int height = resolution.height; if (screen.getWidth() == width && screen.getHeight() == height) { return screen; } BufferedImage img = new BufferedImage(width, height, screen.getType()); Graphics2D g = img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(screen, 0, 0, width, height, 0, 0, screen.getWidth(), screen.getHeight(), null); g.dispose(); return img; }
Source:
<code>public void addEmptyAction() { var parametersMap = new HashMap<String, String>(); for (ActionParameter actionParameter: this.actionParameters) { parametersMap.put(actionParameter.getName(), actionParameter.getName()+Integer.toString(actions.size())); } var newAction = new ScriptGeneratorAction(parametersMap); this.actions.add(newAction); <START> firePropertyChange("actions", null, null); <END> }</code><technical_language>While firing null work, fire new listeners if want to</technical_language>

Target:
public void addEmptyAction() { var parametersMap = new HashMap<ActionParameter, String>(); for (ActionParameter actionParameter: this.actionParameters) { parametersMap.put(actionParameter, actionParameter.getName()+Integer.toString(actions.size())); } var newAction = new ScriptGeneratorAction(parametersMap); firePropertyChange("actions", actions, actions.add(newAction)); }
Source:
<code>public void close() { SQLException exception = null; try { <START> List<Cleanable> clnables = new ArrayList<>(this.cleanables); <END> this.cleanables.clear(); Collections.reverse(clnables); for (Cleanable cleanable : clnables) { try { cleanable.close(); } catch (SQLException e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } } finally { if (exception != null) { throw new CloseException("Exception thrown while cleaning StatementContext", exception); } } }</code><technical_language>I prefer c cs this</technical_language>

Target:
public void close() { SQLException exception = null; try { List<Cleanable> cleanables = new ArrayList<>(this.cleanables); this.cleanables.clear(); Collections.reverse(cleanables); for (Cleanable cleanable : cleanables) { try { cleanable.close(); } catch (SQLException e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } } finally { if (exception != null) { throw new CloseException("Exception thrown while cleaning StatementContext", exception); } } }
Source:
<code>public OAuthAPIProvider( @Nullable @Named("che.oauth.service_mode") String oauthType, Injector injector) { <START> this.oauthType = oauthType == null ? "" : oauthType; <END> this.injector = injector; }</code><technical_language>I guess need fail if oauthType!= embedded keycloak</technical_language>

Target:
public OAuthAPIProvider( @Nullable @Named("che.oauth.service_mode") String oauthType, Injector injector) { this.oauthType = oauthType; this.injector = injector; }
Source:
<code>public void simulateUsbUnplug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "unplug")) { Stream.flushRead(stream); <START> stream.close(); <END> } }</code><technical_language>No, need for close try-with-resource</technical_language>

Target:
public void simulateUsbUnplug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "unplug")) { Stream.flushRead(stream); } }
Source:
<code>public void visit(NodeTraversal t, Node n, Node parent) { if (n.isExprResult()) { ClassMemberDeclaration declaration = ClassMemberDeclaration.newDeclarationOnThis(n); if (declaration == null || declarationHasBeenAdded(declaration)) { return; } Node fnNode = NodeUtil.getEnclosingFunction(n); Node fnParent = fnNode.getParent(); <START> String fnName = (fnParent.isGetProp()) ? fnParent.getQualifiedName() : fnParent.getString(); <END> if ("constructor".equals(fnName) && declaration.jsDoc != null && declaration.jsDoc.getType() != null && declaration.rhsEqualToField()) { JSTypeExpression declarationType = declaration.jsDoc.getType(); Node params = fnNode.getSecondChild(); JSDocInfo constructorJsDoc = NodeUtil.getBestJSDocInfo(fnNode); for (Node param : params.children()) { JSTypeExpression paramType = constructorJsDoc.getParameterType(param.getString()); if (declaration.memberName.equals(param.getString()) && declarationType.equals(paramType)) { moveAccessModifier(declaration, param); markAsConst(declaration, param); n.detachFromParent(); compiler.reportCodeChange(); return; } } } moveFieldsIntoClasses(declaration); registerDeclaration(declaration); } }</code><technical_language>nit: drop parens, cleaner</technical_language>

Target:
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isExprResult()) { ClassMemberDeclaration declaration = ClassMemberDeclaration.newDeclarationOnThis(n); if (declaration == null || declarationHasBeenAdded(declaration)) { return; } Node fnNode = NodeUtil.getEnclosingFunction(n); Node fnParent = fnNode.getParent(); String fnName = fnParent.isGetProp()? fnParent.getQualifiedName() : fnParent.getString(); if ("constructor".equals(fnName) && declaration.jsDoc != null && declaration.jsDoc.getType() != null && declaration.rhsEqualToField()) { JSTypeExpression declarationType = declaration.jsDoc.getType(); Node params = fnNode.getSecondChild(); JSDocInfo constructorJsDoc = NodeUtil.getBestJSDocInfo(fnNode); for (Node param : params.children()) { JSTypeExpression paramType = constructorJsDoc.getParameterType(param.getString()); if (declaration.memberName.equals(param.getString()) && declarationType.equals(paramType)) { moveAccessModifier(declaration, param); markAsConst(declaration, param); n.detachFromParent(); compiler.reportCodeChange(); return; } } } moveFieldsIntoClasses(declaration); registerDeclaration(declaration); } }
Source:
<code>public void putAll(K key, Map<? extends HK, ? extends HV> m) { if (m.isEmpty()) { return; } byte[] rawKey = rawKey(key); <START> int size = Math.min(RedisTemplate.REDIS_MAX_ARGS / 2 - 1, m.size()); <END> Map<byte[], byte[]> hashes = new LinkedHashMap<>(size); Iterator<? extends Entry<? extends HK, ? extends HV>> entries = m.entrySet().iterator(); while (entries.hasNext()) { Entry<? extends HK, ? extends HV> entry = entries.next(); hashes.put(rawHashKey(entry.getKey()), rawHashValue(entry.getValue())); if (!entries.hasNext() || hashes.size() == size) { execute(connection -> { connection.hMSet(rawKey, hashes); return null; }, true); hashes.clear(); } } }</code><technical_language>change a single anticipated HMSET multiple losing atomicity. handled in application code</technical_language>

Target:
public void putAll(K key, Map<? extends HK, ? extends HV> m) { if (m.isEmpty()) { return; } byte[] rawKey = rawKey(key); Map<byte[], byte[]> hashes = new LinkedHashMap<>(m.size()); for (Map.Entry<? extends HK, ? extends HV> entry : m.entrySet()) { hashes.put(rawHashKey(entry.getKey()), rawHashValue(entry.getValue())); } execute(connection -> { connection.hMSet(rawKey, hashes); return null; }, true); }
Source:
<code>public static SortedMap<Short, List<Container>> groupByKey(RoaringBitmap... bitmaps) { Map<Short, List<Container>> grouped = new HashMap<>(); for (RoaringBitmap bitmap : bitmaps) { RoaringArray ra = bitmap.highLowContainer; for (int i = 0; i < ra.size; ++i) { Container container = ra.values[i]; short key = ra.keys[i]; <START> List<Container> slice = grouped.computeIfAbsent(key, k -> new ArrayList<>()); <END> slice.add(container); } } SortedMap<Short, List<Container>> sorted = new TreeMap<>(Util::compareUnsigned); sorted.putAll(grouped); return sorted; }</code><technical_language>Please benchmark this. code written this for a reason</technical_language>

Target:
public static SortedMap<Short, List<Container>> groupByKey(RoaringBitmap... bitmaps) { Map<Short, List<Container>> grouped = new HashMap<>(); for (RoaringBitmap bitmap : bitmaps) { RoaringArray ra = bitmap.highLowContainer; for (int i = 0; i < ra.size; ++i) { Container container = ra.values[i]; Short key = ra.keys[i]; List<Container> slice = grouped.get(key); if (null == slice) { slice = new ArrayList<>(); grouped.put(key, slice); } slice.add(container); } } SortedMap<Short, List<Container>> sorted = new TreeMap<>(Util::compareUnsigned); sorted.putAll(grouped); return sorted; }
Source:
<code>public static boolean isRestBaseEnabled() { if (Prefs.forceRestBase()) { <START> return Prefs.useRestBase(); <END> } boolean useRestBase = shouldUseRestBase(); Prefs.setUseRestBase(useRestBase); return useRestBase; }</code><technical_language>this return true? I thought force meant unconditionally RESTbase</technical_language>

Target:
public boolean isRestBaseEnabled() { return Prefs.useRestBase(); }
Source:
<code>public void setPortalEntity() { for(EntityRef portal : entityManager.getEntitiesWith(PortalComponent.class, LocationComponent.class)){ <START> portalEntity = portal; <END> } }</code><technical_language>portalEntity variable, portal values. code stands, point in iterating results. break out of loop assigning a portalEntity loop all</technical_language>

Target:
private void setPortalEntity() { for (EntityRef portal : entityManager.getEntitiesWith(PortalComponent.class, LocationComponent.class)) { portalEntity = portal; break; } }
Source:
<code>protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthProvider()); auth.eraseCredentials(false); <START> auth.inMemoryAuthentication().withUser("admin").password("admin").roles("QUADRIGA_USER_ADMIN"); <END> super.configure(auth); }</code><technical_language>Noooooo!!!! this needs configurable. admin password needs pom, installation of Quadriga admin account admin/admin. SECURITY (to channel Abhijith...) ;)</technical_language>

Target:
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthProvider()); auth.eraseCredentials(false); auth.inMemoryAuthentication().withUser(propertyManager.getProperty("admin_username")).password(propertyManager.getProperty("admin_password")).roles("QUADRIGA_USER_ADMIN"); super.configure(auth); }
Source:
<code>public IWorkbenchPart[] getDirtyWorkbenchParts() { List<IWorkbenchPart> result = new ArrayList<>(3); IWorkbenchPartReference[] allParts = getSortedParts(true, true, true); boolean autoSave = WorkbenchPlugin.getDefault().getPreferenceStore() .getBoolean(IPreferenceConstants.SAVE_AUTOMATICALLY); for (int i = 0; i < allParts.length; i++) { IWorkbenchPartReference reference = allParts[i]; IWorkbenchPart part = reference.getPart(false); <START> if (autoSave && part instanceof IAutoSaveableEditorPart) { <END> if (((IAutoSaveableEditorPart) part).isDirty() && ((IAutoSaveableEditorPart) part).getAutoSavePolicy()) { result.add(part); } } else { ISaveablePart saveable = SaveableHelper.getSaveable(part); if (saveable != null) { if (saveable.isDirty()) { result.add(part); } } } } return result.toArray(new IWorkbenchPart[result.size()]); }</code><technical_language>usage of java inheritance add ability editors of giving auto save policy is flexible. A solution user list of editors follow autosave do not. default policy provided editor provider, user able override it. I suggest remove this code open a new bug talk this topic this patch is accepted</technical_language>

Target:
public IWorkbenchPart[] getDirtyWorkbenchParts() { List<IWorkbenchPart> result = new ArrayList<>(3); IWorkbenchPartReference[] allParts = getSortedParts(true, true, true); for (int i = 0; i < allParts.length; i++) { IWorkbenchPartReference reference = allParts[i]; IWorkbenchPart part = reference.getPart(false); ISaveablePart saveable = SaveableHelper.getSaveable(part); if (saveable != null) { if (saveable.isDirty()) { result.add(part); } } } return result.toArray(new IWorkbenchPart[result.size()]); }
Source:
<code>public MoveDescription( final Collection<Unit> units, final Route route, final Map<Unit, Unit> unitsToTransports, final Map<Unit, Collection<Unit>> dependentUnits) { super(Collections.unmodifiableCollection(units)); this.route = Preconditions.checkNotNull(route); <START> if (route.getEnd() == null || route.getStart() == null || route.hasNoSteps()) { <END> throw new IllegalStateException("Invalid route: " + route); } this.unitsToTransports = Collections.unmodifiableMap(unitsToTransports); this.dependentUnits = Collections.unmodifiableMap( dependentUnits.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Set.copyOf(e.getValue())))); }</code><technical_language>A single territory route is valid for a move description? clarify if is fully intended. route.getStart() == null is guaranteed route? Side-note, kinda nice single constructor, start is asserted null: public Route(final Territory start, final List<Territory> territories) { this.start = checkNotNull(start); for (final Territory t : territories) { add(t); } } public Route(final List<Territory> territories) { this(territories.get(0), territories.subList(1, territories.size())); } public Route(final Territory start, final Territory... territories) { this(start, List.of(territories)); } getEnd() null (start is guaranteed non-null, if steps is non-empty guarantee do add null elements it): public Territory getEnd() { if (steps.isEmpty()) { return start; } return steps.get(steps.size() - 1); } /** Add territory end of route. */ private void add(final Territory territory) { checkNotNull(territory); if (territory.equals(start) || steps.contains(territory)) { throw new IllegalArgumentException( String.format( "Loops allowed in steps, route: %s, new territory: %s", this, territory)); } steps.add(territory); }</technical_language>

Target:
public MoveDescription( final Collection<Unit> units, final Route route, final Map<Unit, Unit> unitsToTransports, final Map<Unit, Collection<Unit>> dependentUnits) { super(Collections.unmodifiableCollection(units)); this.route = Preconditions.checkNotNull(route); Preconditions.checkArgument(route.hasSteps()); this.unitsToTransports = Collections.unmodifiableMap(unitsToTransports); this.dependentUnits = Collections.unmodifiableMap( dependentUnits.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Set.copyOf(e.getValue())))); }
Source:
<code>public EntityInteractHandler getItemHandler() { return (p, entity, item, offhand) -> { <START> if (!(entity instanceof WanderingTrader) && entity instanceof Merchant) { <END> if (p.getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } Villager v = (Villager) entity; v.setVillagerExperience(0); v.setProfession(Profession.NONE); Location l = v.getLocation().clone(); Double offset = ThreadLocalRandom.current().nextDouble(0, 0.5); boolean flip = false; double o1 = 0; double o2 = offset / 2; double o3 = 0; for(int i = 0; i < 10; i++) { flip = !flip; if(flip) { o1 = offset; o3 = offset * -1; } else { o1 = offset * -1; o3 = offset; } v.getWorld().spawnParticle(Particle.CRIMSON_SPORE, l, 3, o1, o2, o3,0.0d); if(i == 1 || i ==5) v.getWorld().spawnParticle(Particle.ENCHANTMENT_TABLE, l, 3, 0.04d, 1d, 0.04d); } } }; }</code><technical_language>do (entity instance of Villager) instead of this weird double-check. Mojang decide add more types of Merchants, break too. a Villager instanceof check is here. Especially if casting this Villager anyway, result in unexpected class casting exceptions</technical_language>

Target:
public EntityInteractHandler getItemHandler() { return (e, item, offhand) -> { if (e.getRightClicked() instanceof Villager) { Villager v = (Villager) e.getRightClicked(); if (v.getProfession() == Profession.NONE || v.getProfession() == Profession.NITWIT) { return; } if (e.getPlayer().getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } v.setVillagerExperience(0); v.setProfession(Profession.NONE); double offset = ThreadLocalRandom.current().nextDouble(0.5); v.getWorld().spawnParticle(Particle.CRIMSON_SPORE, v.getLocation(), 10, 0, offset / 2, 0,0.0d); v.getWorld().spawnParticle(Particle.ENCHANTMENT_TABLE, v.getLocation(), 5, 0.04d, 1d, 0.04d); } }; }
Source:
<code>public static boolean isEnabled( IConfiguration configuration, IBackupRestoreConfig backupRestoreConfig) { boolean enabled = false; try { enabled = (configuration.isIncrementalBackupEnabled() && (SnapshotBackup.isBackupEnabled(configuration) || (backupRestoreConfig.enableV2Backups() && SnapshotMetaTask.isBackupEnabled( configuration, backupRestoreConfig)))); if (!enabled) { <START> Set<Path> backupPaths = <END> AbstractBackup.getBackupDirectories( configuration, INCREMENTAL_BACKUP_FOLDER); for (Path backupDirPath : backupPaths) { FileUtils.cleanDirectory(backupDirPath.toFile()); } } } catch (Exception e) { logger.warn( "Error while trying to find if incremental backup is enabled: " + e.getMessage()); e.printStackTrace(); } return enabled; }</code><technical_language>isEnabled delete backup directories? want refactor</technical_language>

Target:
public static boolean isEnabled( IConfiguration configuration, IBackupRestoreConfig backupRestoreConfig) { boolean enabled = false; try { enabled = (configuration.isIncrementalBackupEnabled() && (SnapshotBackup.isBackupEnabled(configuration) || (backupRestoreConfig.enableV2Backups() && SnapshotMetaTask.isBackupEnabled( configuration, backupRestoreConfig)))); logger.info("Incremental backups are enabled: {}", enabled); if (!enabled) { cleanOldBackups(configuration); } } catch (Exception e) { logger.error( "Error while trying to find if incremental backup is enabled: " + e.getMessage()); } return enabled; }
Source:
<code>public static void main(String[] args) { A a = new A(); System.out.println(a.SayHi("a string 0", "a string 1", "a string 2", "a string 3", "a string 4", "a string 5", "a string 6", "a string 7", "a string 8", "a string 9")); <START> iface b = (iface)a; <END> System.out.println(b.SayHi("a string 0", "a string 1", "a string 2", "a string 3", "a string 4", "a string 5", "a string 6", "a string 7", "a string 8", "a string 9")); }</code><technical_language>nit: space</technical_language>

Target:
public static void main(String[] args) { A a = new A(); System.out.println(a.SayHi("a string 0", "a string 1", "a string 2", "a string 3", "a string 4", "a string 5", "a string 6", "a string 7", "a string 8", "a string 9")); Iface b = a; System.out.println(b.SayHi("a string 0", "a string 1", "a string 2", "a string 3", "a string 4", "a string 5", "a string 6", "a string 7", "a string 8", "a string 9")); }
Source:
<code>private String extractWhat(DispatchCommand dcmd) { String commandName = dcmd.getCommandName(); <START> String[] args = dcmd.getArguments(); for (int i = 1; i < args.length; i++) { commandName = commandName + "." + args[i]; } <END> return commandName; }</code><technical_language>[optional] write this for (String arg : dcmd.getArguments()) { commandName = commandName + "." + arg; }</technical_language>

Target:
private String extractWhat(DispatchCommand dcmd) { String commandName = dcmd.getCommandName(); for (String arg : dcmd.getArguments()) { commandName = commandName + "." + arg; } return commandName; }
Source:
<code>public void testDesignatedFile() throws Exception{ MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); File designatedFile = new File(TEST_UTIL.getDataTestDir().toUri().getPath(), "designated_file"); HRegionServer designatedServer = cluster.getRegionServer(0); try(FileWriter fos = new FileWriter(designatedFile)) { String designatedHostname = designatedServer.getServerName().getHostname(); int designatedServerPort = designatedServer.getServerName().getPort(); String excludeServerName = designatedHostname + ":" + designatedServerPort; fos.write(excludeServerName); } int regionsInDesignatedServer = designatedServer.getNumberOfOnlineRegions(); HRegionServer regionServer = cluster.getRegionServer(1); String rsName = regionServer.getServerName().getHostname(); int port = regionServer.getServerName().getPort(); String rs = rsName + ":" + port; int regionsInRegionServer = regionServer.getNumberOfOnlineRegions(); RegionMoverBuilder rmBuilder = new RegionMoverBuilder(rs, TEST_UTIL.getConfiguration()) .designatedFile(designatedFile.getCanonicalPath()); try (RegionMover rm = rmBuilder.build()) { <START> LOG.info("Unloading regions", rs); <END> rm.unload(); assertEquals(0, regionServer.getNumberOfOnlineRegions()); assertEquals(regionsInDesignatedServer + regionsInRegionServer, designatedServer.getNumberOfOnlineRegions()); LOG.info("Before:{} After:{}", regionsInDesignatedServer, designatedServer.getNumberOfOnlineRegions()); } }</code><technical_language>debug log for test cases :)</technical_language>

Target:
public void testDesignatedFile() throws Exception{ MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); File designatedFile = new File(TEST_UTIL.getDataTestDir().toUri().getPath(), "designated_file"); HRegionServer designatedServer = cluster.getRegionServer(0); try(FileWriter fos = new FileWriter(designatedFile)) { String designatedHostname = designatedServer.getServerName().getHostname(); int designatedServerPort = designatedServer.getServerName().getPort(); String excludeServerName = designatedHostname + ":" + designatedServerPort; fos.write(excludeServerName); } int regionsInDesignatedServer = designatedServer.getNumberOfOnlineRegions(); HRegionServer regionServer = cluster.getRegionServer(1); String rsName = regionServer.getServerName().getHostname(); int port = regionServer.getServerName().getPort(); String rs = rsName + ":" + port; int regionsInRegionServer = regionServer.getNumberOfOnlineRegions(); RegionMoverBuilder rmBuilder = new RegionMoverBuilder(rs, TEST_UTIL.getConfiguration()) .designatedFile(designatedFile.getCanonicalPath()); try (RegionMover rm = rmBuilder.build()) { LOG.debug("Unloading regions", rs); rm.unload(); assertEquals(0, regionServer.getNumberOfOnlineRegions()); assertEquals(regionsInDesignatedServer + regionsInRegionServer, designatedServer.getNumberOfOnlineRegions()); LOG.debug("Before:{} After:{}", regionsInDesignatedServer, designatedServer.getNumberOfOnlineRegions()); } }
Source:
<code>protected final String getDotFunctionCallString(final String functionName, final ExpressionOperatorParameter parameters) { StringBuilder callString = new StringBuilder(children.get(0).getJavaString(parameters)).append(functionName).append("("); <START> for (int i = 1; i < children.size(); ++i) { <END> callString.append(children.get(i).getJavaString(parameters)); if (i != children.size() - 1) { callString.append(","); } } callString.append(")"); return callString.toString(); }</code><technical_language><LINK_0></technical_language>

Target:
protected final String getDotFunctionCallString(final String functionName, final ExpressionOperatorParameter parameters) { StringBuilder callString = new StringBuilder(children.get(0).getJavaString(parameters)).append(functionName).append("("); Iterator<ExpressionOperator> it = children.iterator(); it.next(); if (it.hasNext()) { callString.append(it.next().getJavaString(parameters)); while (it.hasNext()) { callString.append(","); callString.append(it.next().getJavaString(parameters)); } } callString.append(")"); return callString.toString(); }
Source:
<code>public Range toMetadataRange() { Text metadataPrevRow; <START> if (textPrevEndRow == null) <END> metadataPrevRow = TabletsSection.getRow(getTableId(), new Text("")); else metadataPrevRow = TabletsSection.getRow(getTableId(), this.textPrevEndRow); return new Range(metadataPrevRow, getPrevEndRow() == null, getMetadataEntry(), true); }</code><technical_language>I suggest calling getPrevEndRow() more consistent rest of function</technical_language>

Target:
public Range toMetadataRange() { Text metadataPrevRow = TabletsSection.getRow(getTableId(), getPrevEndRow() == null ? EMPTY_TEXT : getPrevEndRow()); return new Range(metadataPrevRow, getPrevEndRow() == null, getMetadataEntry(), true); }
Source:
<code>public void test() { <START> TestApplication app = new TestApplication(); <END> Map mysqlConf = MutableMap.of("creationScriptContents", SCRIPT); MySqlNode mySqlNode = new MySqlNode(mysqlConf, app); Drupal drupal = new Drupal(app); drupal.setConfig(Drupal.DATABASE_HOST, "127.0.0.1"); drupal.setConfig(Drupal.DATABASE_SCHEMA, "drupal"); drupal.setConfig(Drupal.DATABASE_USER, "drupal"); drupal.setConfig(Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); drupal.setConfig(Drupal.DATABASE_PASSWORD, "password"); drupal.setConfig(Drupal.ADMIN_EMAIL, "alarmnummer@gmail.com"); drupal.setConfig(Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); Entities.startManagement(app); app.start(Arrays.asList(location)); HttpTestUtils.assertContentEventuallyContainsText("http://" + location.getAddress().getHostName() + "/index.php", "Welcome"); }</code><technical_language>suggest move app = ... setUp tearDown stop it</technical_language>

Target:
public void test() { Map mysqlConf = MutableMap.of("creationScriptContents", SCRIPT); MySqlNode mySqlNode = new MySqlNode(mysqlConf, app); Drupal drupal = new Drupal(app); drupal.setConfig(Drupal.DATABASE_HOST, "127.0.0.1"); drupal.setConfig(Drupal.DATABASE_SCHEMA, "drupal"); drupal.setConfig(Drupal.DATABASE_USER, "drupal"); drupal.setConfig(Drupal.DATABASE_PORT, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.MYSQL_PORT)); drupal.setConfig(Drupal.DATABASE_PASSWORD, "password"); drupal.setConfig(Drupal.ADMIN_EMAIL, "alarmnummer@gmail.com"); drupal.setConfig(Drupal.DATABASE_UP, DependentConfiguration.attributeWhenReady(mySqlNode, MySqlNode.SERVICE_UP)); Entities.startManagement(app); app.start(Arrays.asList(location)); HttpTestUtils.assertContentEventuallyContainsText("http://" + drupal.getAttribute(Drupal.HOSTNAME) + "/index.php", "Welcome"); }
Source:
<code>public <R> R getOwnedEntities(MambuEntityType parentEntity, String parentId, MambuEntityType ownedEntity, String relatedEntityId, ParamsMap params, boolean requiresFullDetails) throws MambuApiException { if (parentEntity == null || ownedEntity == null) { throw new IllegalArgumentException("Parent Entity and Owned Entity cannot be null"); } Class<?> parentClass = parentEntity.getEntityClass(); Class<?> ownedClass = ownedEntity.getEntityClass(); <START> ApiDefinition apiDefinition ; <END> apiDefinition = createApiDefinitionForGetOwnedEntities(requiresFullDetails, parentClass, ownedClass); return execute(apiDefinition, parentId, relatedEntityId, params); }</code><technical_language>curious, this approach a single line of code</technical_language>

Target:
public <R> R getOwnedEntities(MambuEntityType parentEntity, String parentId, MambuEntityType ownedEntity, String relatedEntityId, ParamsMap params, boolean requiresFullDetails) throws MambuApiException { if (parentEntity == null || ownedEntity == null) { throw new IllegalArgumentException("Parent Entity and Owned Entity cannot be null"); } Class<?> parentClass = parentEntity.getEntityClass(); Class<?> ownedClass = ownedEntity.getEntityClass(); ApiDefinition apiDefinition = createApiDefinitionForGetOwnedEntities(requiresFullDetails, parentClass, ownedClass); return execute(apiDefinition, parentId, relatedEntityId, params); }
Source:
<code>public Answer execute(final OvsCreateTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) { final String bridge = command.getNetworkName(); try { if (!libvirtComputingResource.findOrCreateTunnelNetwork(bridge)) { s_logger.debug("Error during bridge setup"); return new OvsCreateTunnelAnswer(command, false, "Cannot create network", bridge); } libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName()); <START> final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout().getMillis(), s_logger); <END> scriptCommand.add("create_tunnel"); scriptCommand.add("--bridge", bridge); scriptCommand.add("--remote_ip", command.getRemoteIp()); scriptCommand.add("--key", command.getKey().toString()); scriptCommand.add("--src_host", command.getFrom().toString()); scriptCommand.add("--dst_host", command.getTo().toString()); final String result = scriptCommand.execute(); if (result != null) { return new OvsCreateTunnelAnswer(command, true, result, null, bridge); } else { return new OvsCreateTunnelAnswer(command, false, result, bridge); } } catch (final Exception e) { s_logger.warn("Caught execption when creating ovs tunnel", e); return new OvsCreateTunnelAnswer(command, false, e.getMessage(), bridge); } }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public Answer execute(final OvsCreateTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) { final String bridge = command.getNetworkName(); try { if (!libvirtComputingResource.findOrCreateTunnelNetwork(bridge)) { s_logger.debug("Error during bridge setup"); return new OvsCreateTunnelAnswer(command, false, "Cannot create network", bridge); } libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName()); final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger); scriptCommand.add("create_tunnel"); scriptCommand.add("--bridge", bridge); scriptCommand.add("--remote_ip", command.getRemoteIp()); scriptCommand.add("--key", command.getKey().toString()); scriptCommand.add("--src_host", command.getFrom().toString()); scriptCommand.add("--dst_host", command.getTo().toString()); final String result = scriptCommand.execute(); if (result != null) { return new OvsCreateTunnelAnswer(command, true, result, null, bridge); } else { return new OvsCreateTunnelAnswer(command, false, result, bridge); } } catch (final Exception e) { s_logger.warn("Caught execption when creating ovs tunnel", e); return new OvsCreateTunnelAnswer(command, false, e.getMessage(), bridge); } }
Source:
<code>private HashMap<String, ArrayList<String>> getMappedIssuesToFiles(Collection<PostJobIssue> allIssues) { <START> HashMap<String, ArrayList<String>> issueToFilesMap = new HashMap<>(); <END> if (!this.includeFilesInOverview) { return issueToFilesMap; } for (PostJobIssue issue : allIssues) { String title = this.printIssueMarkdown(issue); if (!issueToFilesMap.containsKey(title)) { issueToFilesMap.put(title, new ArrayList<>()); } if (issueToFilesMap.get(title).size() >= MAX_FILES_PER_ISSUE) { continue; } Integer issueLine = issue.line(); if (issueLine == null) { issueLine = 0; } issueToFilesMap.get(title).add(this.parseFileName(issue.componentKey(), issueLine)); } return issueToFilesMap; }</code><technical_language>I a guava Multimap cleaner</technical_language>

Target:
private ListMultimap<String, String> getMappedIssuesToFiles(Collection<PostJobIssue> allIssues) { ListMultimap<String, String> issueToFilesMap = ArrayListMultimap.create(); if (this.includeFilesInOverview <= 0) { return issueToFilesMap; } for (PostJobIssue issue : allIssues) { String title = this.printIssueMarkdown(issue); Integer issueLine = issue.line(); if (issueLine == null) { issueLine = 0; } issueToFilesMap.get(title).add(this.issuePathResolver.getIssuePath(issue) + ":" + issueLine); } this.sortMappedIssuesToFiles(issueToFilesMap); return issueToFilesMap; }
Source:
<code>protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { BaseImagesCommand cloneCinderDiskCommand = (BaseImagesCommand) command; ImagesContainterParametersBase parameters = (ImagesContainterParametersBase) cloneCinderDiskCommand.getParameters(); ImageStatus imageStatus = cloneCinderDiskCommand.getCinderBroker().getDiskStatus(parameters.getDestinationImageId()); <START> DiskImage disk = (CinderDisk) DbFacade.getInstance().getDiskDao().get(parameters.getContainerId()); <END> if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }</code><technical_language>injection for dao</technical_language>

Target:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { BaseImagesCommand cloneCinderDiskCommand = (BaseImagesCommand) command; ImagesContainterParametersBase parameters = (ImagesContainterParametersBase) cloneCinderDiskCommand.getParameters(); ImageStatus imageStatus = cloneCinderDiskCommand.getCinderBroker().getDiskStatus(parameters.getDestinationImageId()); DiskImage disk = (CinderDisk) diskDao.get(parameters.getContainerId()); if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }
Source:
<code>public void testMultiIntervalSerde() throws Exception { String jsonStr = "{\n" + " \"dataSource\": \"test\",\n" + " \"intervals\": [\"2014/2015\", \"2016/2017\"]\n" + "}\n"; DatasourceIngestionSpec actual = MAPPER.readValue( MAPPER.writeValueAsString( MAPPER.readValue(jsonStr, DatasourceIngestionSpec.class) ), DatasourceIngestionSpec.class ); List<Interval> intervals = ImmutableList.of(Interval.parse("2014/2015"), Interval.parse("2016/2017")); <START> <END> DatasourceIngestionSpec expected = new DatasourceIngestionSpec( "test", null, intervals, null, null, null, null, null ); Assert.assertEquals(expected, actual); jsonStr = "{\n" + " \"dataSource\": \"test\",\n" + " \"intervals\": [\"2014/2015\", \"2016/2017\"],\n" + " \"filter\": { \"type\": \"selector\", \"dimension\": \"dim\", \"value\": \"value\"},\n" + " \"granularity\": \"day\",\n" + " \"dimensions\": [\"d1\", \"d2\"],\n" + " \"metrics\": [\"m1\", \"m2\", \"m3\"],\n" + " \"ignoreWhenNoSegments\": true\n" + "}\n"; expected = new DatasourceIngestionSpec( "test", null, intervals, new SelectorDimFilter("dim", "value"), QueryGranularity.DAY, Lists.newArrayList("d1", "d2"), Lists.newArrayList("m1", "m2", "m3"), true ); actual = MAPPER.readValue( MAPPER.writeValueAsString( MAPPER.readValue(jsonStr, DatasourceIngestionSpec.class) ), DatasourceIngestionSpec.class ); Assert.assertEquals(expected, actual); }</code><technical_language>this assertion redundant next one</technical_language>

Target:
public void testMultiIntervalSerde() throws Exception { String jsonStr = "{\n" + " \"dataSource\": \"test\",\n" + " \"intervals\": [\"2014/2015\", \"2016/2017\"]\n" + "}\n"; DatasourceIngestionSpec actual = MAPPER.readValue( MAPPER.writeValueAsString( MAPPER.readValue(jsonStr, DatasourceIngestionSpec.class) ), DatasourceIngestionSpec.class ); List<Interval> intervals = ImmutableList.of(Interval.parse("2014/2015"), Interval.parse("2016/2017")); DatasourceIngestionSpec expected = new DatasourceIngestionSpec( "test", null, intervals, null, null, null, null, false ); Assert.assertEquals(expected, actual); jsonStr = "{\n" + " \"dataSource\": \"test\",\n" + " \"intervals\": [\"2014/2015\", \"2016/2017\"],\n" + " \"filter\": { \"type\": \"selector\", \"dimension\": \"dim\", \"value\": \"value\"},\n" + " \"granularity\": \"day\",\n" + " \"dimensions\": [\"d1\", \"d2\"],\n" + " \"metrics\": [\"m1\", \"m2\", \"m3\"],\n" + " \"ignoreWhenNoSegments\": true\n" + "}\n"; expected = new DatasourceIngestionSpec( "test", null, intervals, new SelectorDimFilter("dim", "value"), QueryGranularity.DAY, Lists.newArrayList("d1", "d2"), Lists.newArrayList("m1", "m2", "m3"), true ); actual = MAPPER.readValue( MAPPER.writeValueAsString( MAPPER.readValue(jsonStr, DatasourceIngestionSpec.class) ), DatasourceIngestionSpec.class ); Assert.assertEquals(expected, actual); }
Source:
<code>public StringIteratorInputStream(Iterator<String> data) { <START> this.data = data; <END> }</code><technical_language>requireNonNull</technical_language>

Target:
public StringIteratorInputStream(Iterator<String> data) { this.data = requireNonNull(data, "data is null"); }
Source:
<code>public TypeSerializer<T> getSerializer() { if (serializer != null) { return serializer; } else { <START> throw new RuntimeException("SerializerFactory ahas not been initialized from configuration."); <END> } }</code><technical_language>typo</technical_language>

Target:
public TypeSerializer<T> getSerializer() { if (serializer != null) { return serializer; } else { throw new RuntimeException("SerializerFactory has not been initialized from configuration."); } }
Source:
<code>public void seek(final long position) throws IOException { if (this.position == position) { return; } <START> if ((position > this.position && (position - this.position < this.bufferedStream.getBytesInBufferAvailable())) <END> || (position < this.position && (this.position - position < this.bufferedStream.getPositionInBuffer()))) { this.bufferedStream.changePos((int) (position - this.position)); } else { wrappedStream.seek(position); bufferedStream = new ExtBufferedInputStream(wrappedStream, bufferSize); } this.position = position; }</code><technical_language>clearer pull out 2 variables here, bufferStart bufferEnd, check position >= bufferStart && position <= bufferEnd. (I 1 errors in currents checks. work fine, potentially do extra seek if wanted jump exact start end of buffer. ) I a similar 1 error in implementation of skip checks if skip seek. want push this check isPositionAvailableInBuffer method in ExtBufferedInputStream instead of getPositionInBuffer method. I this code clearer easier in</technical_language>

Target:
public void seek(final long position) throws IOException { if (this.position == position) { return; } long delta = position - this.position; if (this.bufferedStream.canChangePos(delta)) { this.bufferedStream.changePos((int) delta); this.position = position; } else { seekInternal(position); } }
Source:
<code>private int showSliderSettings(int row) { for (String key : settings.getSliderSettings()) { <START> Label label = new Label(settings.getDescription(key)); <END> Slider slider = new Slider(); double value = settings.getSlider(key); Label valueLabel = new Label(Math.round(value * 100) + "%"); slider.setValue(100 * value); slider.setMaxWidth(200); slider.setMin(0); slider.setMax(100); slider.valueProperty().addListener(e -> { settings.setSlider(key, slider.getValue() / 100); valueLabel.setText(Math.round(slider.getValue()) + "%"); }); HBox box = new HBox(); box.setSpacing(10); box.getChildren().addAll(slider, valueLabel); gridPane.add(label, 0, row); gridPane.add(box, 1, row); row++; } return row; }</code><technical_language>missed tooltip (that missing) <review</technical_language>

Target:
private int showSliderSettings(int row) { for (String key : settings.getSliderSettings()) { Label label = new Label(settings.getDescription(key)); label.setTooltip(new Tooltip(key)); Slider slider = new Slider(); double value = settings.getSlider(key); Label valueLabel = new Label(Math.round(value * 100) + "%"); slider.setValue(100 * value); slider.setMaxWidth(200); slider.setMin(0); slider.setMax(100); slider.valueProperty().addListener(e -> { settings.setSlider(key, slider.getValue() / 100); valueLabel.setText(Math.round(slider.getValue()) + "%"); }); HBox box = new HBox(); box.setSpacing(10); box.getChildren().addAll(slider, valueLabel); gridPane.add(label, 0, row); gridPane.add(box, 1, row); row++; } return row; }
Source:
<code>public IContentProposal[] getProposals(final String arg0, final int arg1) { IContentProposal[] proposals = null; <START> if (currentEObject != null) { <END> final List<ContentProposal> contentProposalsList = Lists.newArrayList(); ContentInstanceContext context = new ContentInstanceContext(currentEObject, arg0, arg1, editingDomain); if (interpreter instanceof IProposalProvider) { contentProposalsList.addAll(((IProposalProvider) interpreter).getProposals(interpreter, context)); } final List<IProposalProvider> providers = ProposalProviderRegistry.getProvidersFor(interpreter); for (IProposalProvider provider : providers) { contentProposalsList.addAll(provider.getProposals(interpreter, context)); } String proposalStart = null; if (!interpreter.provides(arg0)) { proposalStart = arg0; } else { String prefix = CompoundInterpreter.INSTANCE.getVariablePrefix(arg0); ContentContextHelper helper = new ContentContextHelper(arg0, arg1, prefix); proposalStart = helper.getProposalStart(); } proposals = new ContentProposalConverter(proposalStart).convertToJFaceContentProposals(contentProposalsList); } return proposals; }</code><technical_language>I organise this method in a readable way: if (emtpyArg0) fast getallNewEmptyExpression else if (compound getInterpreterForExpression(arg0) != DefaultInterpreterProvider.INSTANCE) interpreter is do standard completion else interpreter is (default interpreter .instance) try propose new empty expression arg0 a specific "new empty expression" proposal provider. I if do register this new empty expression proposal provider porposal provider extension points declare in proposal provider registryn return proposals if arg0 start of knwon prefixes</technical_language>

Target:
public IContentProposal[] getProposals(final String arg0, final int arg1) { if (currentEObject != null) { final List<ContentProposal> contentProposalsList; if (StringUtil.isEmpty(arg0)) { contentProposalsList = CompoundInterpreter.INSTANCE.getAllNewEmtpyExpressions(); } else { contentProposalsList = Lists.newArrayList(); if (interpreter instanceof IProposalProvider) { contentProposalsList.addAll(((IProposalProvider) interpreter).getProposals(interpreter, new ContentInstanceContext(currentEObject, arg0, arg1, editingDomain))); } final List<IProposalProvider> providers = ProposalProviderRegistry.getProvidersFor(interpreter); for (IProposalProvider provider : providers) { contentProposalsList.addAll(provider.getProposals(interpreter, new ContentInstanceContext(currentEObject, arg0, arg1, editingDomain))); } } String prefix = CompoundInterpreter.INSTANCE.getVariablePrefix(arg0); ContentContextHelper helper = new ContentContextHelper(arg0, arg1, prefix); return new ContentProposalConverter(helper.getProposalStart()).convertToJFaceContentProposals(contentProposalsList); } else { return null; } }
Source:
<code>public WebDriver window(int index) { try { return Wait().until(windowToBeAvailableAndSwitchToIt(index)); } catch (TimeoutException e) { <START> throw new NoSuchWindowException("Window with index not found: " + index); <END> } }</code><technical_language>forget wrap original exception: throw new NoSuchWindowException("Window index found: " + index, e);</technical_language>

Target:
public WebDriver window(int index) { try { return Wait().until(windowToBeAvailableAndSwitchToIt(index)); } catch (TimeoutException e) { throw new NoSuchWindowException("No window found with index: " + index, e); } }
Source:
<code>@Nullable static String errorCode(Throwable error) { if (error instanceof RpcException) { int code = ((RpcException) error).getCode(); switch (code) { case RpcException.UNKNOWN_EXCEPTION: return "UNKNOWN_EXCEPTION"; case RpcException.NETWORK_EXCEPTION: return "NETWORK_EXCEPTION"; case RpcException.TIMEOUT_EXCEPTION: return "TIMEOUT_EXCEPTION"; case RpcException.BIZ_EXCEPTION: return "BIZ_EXCEPTION"; case RpcException.FORBIDDEN_EXCEPTION: return "FORBIDDEN_EXCEPTION"; case RpcException.SERIALIZATION_EXCEPTION: return "SERIALIZATION_EXCEPTION"; default: <START> return String.valueOf(code); <END> } } return null; }</code><technical_language>Nah ok</technical_language>

Target:
@Nullable static String errorCode(Throwable error) { if (error instanceof RpcException) { return String.valueOf(((RpcException) error).getCode()); } return null; }
Source:
<code>public void shareWrongStoreWithMapTest() throws Exception { CompilerHelper helper = new CompilerHelper(); <START> Map<String, Object> kieMap = new HashMap<>(); <END> String compilationID = UUID.randomUUID().toString(); kieMap.put("compilation.ID", compilationID); File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator); URL url = dir.toURL(); ClassLoader cl = new URLClassLoader(new URL[]{url}); helper.shareStoreWithMap(cl, compilationID, kieMap, log); StringBuilder sbTypes = new StringBuilder(compilationID).append(".").append("ProjectClassloaderStore"); kieMap.get(sbTypes.toString()); Map store = (Map) kieMap.get(sbTypes.toString()); assertThat(store).isNull(); }</code><technical_language>know: create a map single key-value pair single statement Map<String,Object> kieMap = Collections.singletonMap("compilation.ID", compilationID); remove some boilerplate.</technical_language>

Target:
public void shareWrongStoreWithMapTest() throws Exception { CompilerHelper helper = new CompilerHelper(); String compilationID = UUID.randomUUID().toString(); Map<String,Object> kieMap = Collections.singletonMap("compilation.ID", compilationID); File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator); URL url = dir.toURL(); ClassLoader cl = new URLClassLoader(new URL[]{url}); helper.shareStoreWithMap(cl, compilationID, kieMap, log); StringBuilder sbTypes = new StringBuilder(compilationID).append(".").append("ProjectClassloaderStore"); kieMap.get(sbTypes.toString()); Map store = (Map) kieMap.get(sbTypes.toString()); assertThat(store).isNull(); }