auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected static List<WebElement> findByKeyAttrs(WebDriver webDriver, FindByCoordinates findByCoordinates) { KeyAttrs keyAttrs = KeyAttrs.DEFAULT; if (findByCoordinates.tag != null) { try { keyAttrs = KeyAttrs.valueOf(findByCoordinates.tag.trim().toUpperCase()); } catch (IllegalArgumentException e) { } } String xpathCriteria = Element.escapeXpathValue(findByCoordinates.criteria); String xpathTag = findByCoordinates.tag; if (findByCoordinates.tag == null) { xpathTag = "*"; } List<String> xpathConstraints = new ArrayList<>(); if (findByCoordinates.constraints != null) { for (Entry<String, String> entry : findByCoordinates.constraints.entrySet()) { for (String value : entry.getValue().split(",")) { xpathConstraints.add(String.format("@%s='%s'", entry.getKey(), value)); } } } List<String> xpathSearchers = new ArrayList<>(); for (String attr : keyAttrs.getKeyAttrs()) { xpathSearchers.add(String.format("%s=%s", attr, xpathCriteria)); } xpathSearchers.addAll(getAttrsWithUrl(webDriver, keyAttrs, findByCoordinates.criteria)); String xpath = String.format(" xpathTag, <START> (xpathConstraints.size() > 0 ? "("+StringUtils.join(xpathConstraints, " or ")+")" : ""), <END> (xpathConstraints.size() > 0 ? " and " : ""), StringUtils.join(xpathSearchers, " or ")); return webDriver.findElements(By.xpath(xpath)); }</code><technical_language>missed spaces</technical_language>

Target:
protected static List<WebElement> findByKeyAttrs(WebDriver webDriver, FindByCoordinates findByCoordinates) { KeyAttrs keyAttrs = KeyAttrs.DEFAULT; if (findByCoordinates.tag != null) { try { keyAttrs = KeyAttrs.valueOf(findByCoordinates.tag.trim().toUpperCase()); } catch (IllegalArgumentException e) { } } String xpathCriteria = Element.escapeXpathValue(findByCoordinates.criteria); String xpathTag = findByCoordinates.tag; if (findByCoordinates.tag == null) { xpathTag = "*"; } List<String> xpathConstraints = new ArrayList<>(); if (findByCoordinates.constraints != null) { for (Entry<String, String> entry : findByCoordinates.constraints.entrySet()) { for (String value : entry.getValue().split(",")) { xpathConstraints.add(String.format("@%s='%s'", entry.getKey(), value)); } } } List<String> xpathSearchers = new ArrayList<>(); for (String attr : keyAttrs.getKeyAttrs()) { xpathSearchers.add(String.format("%s=%s", attr, xpathCriteria)); } xpathSearchers.addAll(getAttrsWithUrl(webDriver, keyAttrs, findByCoordinates.criteria)); String xpath = String.format(" xpathTag, (xpathConstraints.size() > 0 ? String.format("(%s) and ",StringUtils.join(xpathConstraints, " or ")) : ""), StringUtils.join(xpathSearchers, " or ")); return webDriver.findElements(By.xpath(xpath)); }
Source:
<code>public static <M extends Message, B extends Message.Builder> Collection<M> applyMask(@SuppressWarnings("TypeMayBeWeakened") FieldMask mask, Collection<M> entities, TypeUrl typeUrl) { <START> final List<M> filtered = new ArrayList<>(); <END> final ProtocolStringList filter = mask.getPathsList(); final Class<B> builderClass = getBuilderForType(typeUrl); if (filter.isEmpty() || builderClass == null) { return Collections.unmodifiableCollection(entities); } try { final Constructor<B> builderConstructor = builderClass.getDeclaredConstructor(); builderConstructor.setAccessible(true); for (Message wholeMessage : entities) { final B builder = builderConstructor.newInstance(); for (Descriptors.FieldDescriptor field : wholeMessage.getDescriptorForType().getFields()) { if (filter.contains(field.getFullName())) { builder.setField(field, wholeMessage.getField(field)); } } filtered.add((M) builder.build()); } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { return Collections.unmodifiableCollection(entities); } return Collections.unmodifiableList(filtered); }</code><technical_language>LinkedList well. ArrayList in case - size - expect heavy get(index) usage</technical_language>

Target:
public static <M extends Message, B extends Message.Builder> Collection<M> applyMask(@SuppressWarnings("TypeMayBeWeakened") FieldMask mask, Collection<M> entities, TypeUrl typeUrl) { final List<M> filtered = new LinkedList<>(); final ProtocolStringList filter = mask.getPathsList(); final Class<B> builderClass = getBuilderForType(typeUrl); if (filter.isEmpty() || builderClass == null) { return Collections.unmodifiableCollection(entities); } try { final Constructor<B> builderConstructor = builderClass.getDeclaredConstructor(); builderConstructor.setAccessible(true); for (Message wholeMessage : entities) { final B builder = builderConstructor.newInstance(); for (Descriptors.FieldDescriptor field : wholeMessage.getDescriptorForType().getFields()) { if (filter.contains(field.getFullName())) { builder.setField(field, wholeMessage.getField(field)); } } filtered.add((M) builder.build()); } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { return Collections.unmodifiableCollection(entities); } return Collections.unmodifiableList(filtered); }
Source:
<code>public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { BlockFace direction; <START> double rot = player.getLocation().getYaw() % 360; <END> if (rot < 0) { rot += 360.0; } if (0 <= rot && rot < 45) { direction = BlockFace.SOUTH; } else if (45 <= rot && rot < 135) { direction = BlockFace.WEST; } else if (135 <= rot && rot < 225) { direction = BlockFace.NORTH; } else if (225 <= rot && rot < 315) { direction = BlockFace.EAST; } else if (315 <= rot && rot < 360.0) { direction = BlockFace.SOUTH; } else { direction = BlockFace.EAST; } if (state.getBlock().getRelative(direction).getType() == Material.AIR && state.getBlock().getRelative(direction).getRelative(BlockFace.DOWN).getType().isSolid()) { super.placeBlock(player, state, face, holding, clickedLoc); final MaterialData data = state.getData(); if (data instanceof Bed) { ((Bed) data).setFacingDirection(direction); state.setData(data); } else { GlowServer.logger.warning("Placing " + getMaterial().name() + ": MaterialData was of wrong type (" + data.getClass().getName() + ")"); } } }</code><technical_language>Stuff this done in getYaw() avoid duplicated/buggy code</technical_language>

Target:
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { BlockFace direction; double rot = player.getLocation().getYaw(); if (rot < 0) { rot += 360.0; } if (0 <= rot && rot < 45) { direction = BlockFace.SOUTH; } else if (45 <= rot && rot < 135) { direction = BlockFace.WEST; } else if (135 <= rot && rot < 225) { direction = BlockFace.NORTH; } else if (225 <= rot && rot < 315) { direction = BlockFace.EAST; } else if (315 <= rot && rot < 360.0) { direction = BlockFace.SOUTH; } else { direction = BlockFace.EAST; } if (state.getBlock().getRelative(direction).getType() == Material.AIR && state.getBlock().getRelative(direction).getRelative(BlockFace.DOWN).getType().isSolid()) { super.placeBlock(player, state, face, holding, clickedLoc); final MaterialData data = state.getData(); if (data instanceof Bed) { ((Bed) data).setFacingDirection(direction); state.setData(data); } else { GlowServer.logger.warning("Placing " + getMaterial().name() + ": MaterialData was of wrong type (" + data.getClass().getName() + ")"); } } }
Source:
<code>protected static void setUpBeforeClass(String params, String projectRoot, boolean isDevMode) throws IOException, InterruptedException, FileNotFoundException { basicDevProj = new File(projectRoot); String os = System.getProperty("os.name"); if (os != null && os.toLowerCase().startsWith("windows")) { isWindows = true; } if (!isWindows) { tempProj = Files.createTempDirectory("temp").toFile(); assertTrue(tempProj.exists()); assertTrue(basicDevProj.exists()); FileUtils.copyDirectoryStructure(basicDevProj, tempProj); assertTrue(tempProj.listFiles().length > 0); logFile = new File(basicDevProj, "logFile.txt"); assertTrue(logFile.createNewFile()); pom = new File(tempProj, "pom.xml"); assertTrue(pom.exists()); replaceVersion(); <START> startProcess(params, isDevMode); <END> } }</code><technical_language>RunTest run Windows right? This setupBeforeClass is called RunTest isDevMode set false. this call startProcess is a if (!isWindows) statement get called, for RunTest</technical_language>

Target:
protected static void setUpBeforeClass(String params, String projectRoot, boolean isDevMode) throws IOException, InterruptedException, FileNotFoundException { basicDevProj = new File(projectRoot); tempProj = Files.createTempDirectory("temp").toFile(); assertTrue(tempProj.exists()); assertTrue(basicDevProj.exists()); FileUtils.copyDirectoryStructure(basicDevProj, tempProj); assertTrue(tempProj.listFiles().length > 0); logFile = new File(basicDevProj, "logFile.txt"); assertTrue(logFile.createNewFile()); pom = new File(tempProj, "pom.xml"); assertTrue(pom.exists()); replaceVersion(); startProcess(params, isDevMode); }
Source:
<code>private boolean syncAcl(ACLDocumentOperation operation) { for (int n : new int {1 , 1 , 2 , 3 , 5 , 8}) { if(trySyncAcl(operation)) { return true; } try { if(LOGGER.isTraceEnabled()) { <START> LOGGER.trace("Sleeping for {}(s)", n * 1000); <END> } Thread.sleep(n * 1000); } catch (InterruptedException e) { LOGGER.error("There was an error while trying the sleep the syncACL operation", e); } } return false; }</code><technical_language>n is seconds? n n * 1000</technical_language>

Target:
private boolean syncAcl(ACLDocumentOperation operation) { for (int n : new int {1 , 1 , 2 , 3 , 5 , 8}) { if(trySyncAcl(operation)) { return true; } try { if(LOGGER.isTraceEnabled()) { LOGGER.trace("Sleeping for {}(s)", n); } Thread.sleep(n * 1000); } catch (InterruptedException e) { LOGGER.error("There was an error while trying the sleep the syncACL operation", e); } } return false; }
Source:
<code>public ActionResult execute() { String instructorEmail = getNonNullRequestParamValue(Const.ParamsNames.INSTRUCTOR_EMAIL).trim(); <START> AccountCreateRequest createRequest = getAndValidateRequestBody(AccountCreateRequest.class); <END> String instructorName = createRequest.getInstructorName(); String courseId = null; try { courseId = importDemoData(instructorEmail, instructorName); } catch (InvalidParametersException | EntityDoesNotExistException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } String instructorInstitution = createRequest.getInstructorInstitution(); List<InstructorAttributes> instructorList = logic.getInstructorsForCourse(courseId); String joinLink = Config.getFrontEndAppUrl(Const.WebPageURIs.JOIN_PAGE) .withRegistrationKey(StringHelper.encrypt(instructorList.get(0).key)) .withInstructorInstitution(instructorInstitution) .withParam(Const.ParamsNames.ENTITY_TYPE, Const.EntityType.INSTRUCTOR) .toAbsoluteString(); EmailWrapper email = emailGenerator.generateNewInstructorAccountJoinEmail( instructorList.get(0).email, instructorName, joinLink); emailSender.sendEmail(email); JoinLinkData output = new JoinLinkData(joinLink); return new JsonResult(output); }</code><technical_language>Email in request</technical_language>

Target:
public ActionResult execute() { AccountCreateRequest createRequest = getAndValidateRequestBody(AccountCreateRequest.class); String instructorName = createRequest.getInstructorName().trim(); String instructorEmail = createRequest.getInstructorEmail().trim(); String courseId = null; try { courseId = importDemoData(instructorEmail, instructorName); } catch (InvalidParametersException | EntityDoesNotExistException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } String instructorInstitution = createRequest.getInstructorInstitution().trim(); List<InstructorAttributes> instructorList = logic.getInstructorsForCourse(courseId); String joinLink = Config.getFrontEndAppUrl(Const.WebPageURIs.JOIN_PAGE) .withRegistrationKey(StringHelper.encrypt(instructorList.get(0).key)) .withInstructorInstitution(instructorInstitution) .withParam(Const.ParamsNames.ENTITY_TYPE, Const.EntityType.INSTRUCTOR) .toAbsoluteString(); EmailWrapper email = emailGenerator.generateNewInstructorAccountJoinEmail( instructorList.get(0).email, instructorName, joinLink); emailSender.sendEmail(email); JoinLinkData output = new JoinLinkData(joinLink); return new JsonResult(output); }
Source:
<code>public SpongePaginationService() { <START> Sponge.getGame().getCommandDispatcher().register(Sponge.getPlugin(), CommandSpec.builder() <END> .description(t("Helper command for paginations occurring")) .arguments(new ActivePaginationCommandElement(t("pagination-id"))) .child(CommandSpec.builder() .description(t("Go to the next page")) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().nextPage(); return CommandResult.success(); } }).build(), "next", "n") .child(CommandSpec.builder() .description(t("Go to the previous page")) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().previousPage(); return CommandResult.success(); } }).build(), "previous", "prev", "p") .child(CommandSpec.builder() .description(t("Go to a specific page")) .arguments(integer(t("page"))) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().specificPage(args.<Integer>getOne("page").get()); return CommandResult.success(); } }).build(), "page") .build(), "pagination", "page"); registerDefaultPaginationCalculators(); }</code><technical_language>Is **not** register command if pagination service is used? API allow removing services (or changing provider) for some stupid reason, removing commands exposed casting</technical_language>

Target:
public SpongePaginationService() { registerDefaultPaginationCalculators(); }
Source:
<code>public final Collection<GrantedAuthority> getGrantedAuthorities( final DirContextOperations user, final String username, final String password) { final String userDn = user.getNameInNamespace(); if (logger.isDebugEnabled()) { logger.debug("Getting authorities for user " + userDn); } final List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(); if (password != null) { <START> Supplier<DirContext> ctxSupplier = <END> () -> ldapTemplate.getContextSource().getContext(userDn, password); ldapTemplate.authenticate( DistinguishedName.EMPTY_PATH, userDn, password, new AuthenticatedLdapEntryContextCallback() { @Override public void executeWithContext( DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { getAllRoles(user, userDn, result, username, ctxSupplier); } }); } else { getAllRoles(user, userDn, result, username, null); } return result; }</code><technical_language>Is this needed? authenticate ctx ldapTemplate.authenticate anymore</technical_language>

Target:
public final Collection<GrantedAuthority> getGrantedAuthorities( final DirContextOperations user, final String username, final String password) { final String userDn = user.getNameInNamespace(); if (logger.isDebugEnabled()) { logger.debug("Getting authorities for user " + userDn); } final List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(); if (password != null) { Consumer<Consumer<DirContext>> ctxConsumer = (ctxFunc) -> { ldapTemplate.authenticate( LdapUtils.emptyLdapName(), userDn, password, new AuthenticatedLdapEntryContextCallback() { @Override public void executeWithContext( DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { ctxFunc.accept(ctx); } }); }; ldapTemplate.authenticate( LdapUtils.emptyLdapName(), userDn, password, new AuthenticatedLdapEntryContextCallback() { @Override public void executeWithContext( DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { getAllRoles(user, userDn, result, username, ctxConsumer); } }); } else { getAllRoles(user, userDn, result, username, (func) -> func.accept(null)); } return result; }
Source:
<code>public void handle(Message<T> message) { Handler<Message<T>> theHandler; synchronized (this) { if (paused) { if (pending.size() < maxBufferedMessages) { pending.add(message); } else { <START> if (discardHandler != null) { <END> discardHandler.handle(message); } else { log.warn("Discarding message as more than " + maxBufferedMessages + " buffered in paused consumer (address {0})", address); } } return; } else { if (pending.size() > 0) { pending.add(message); message = pending.poll(); } theHandler = handler; } } deliver(theHandler, message); }</code><technical_language>renamed dropHandler</technical_language>

Target:
public void handle(Message<T> message) { Handler<Message<T>> theHandler; synchronized (this) { if (paused) { if (pending.size() < maxBufferedMessages) { pending.add(message); } else { if (discardHandler != null) { discardHandler.handle(message); } else { log.warn("Discarding message as more than " + maxBufferedMessages + " buffered in paused consumer. address: " + address); } } return; } else { if (pending.size() > 0) { pending.add(message); message = pending.poll(); } theHandler = handler; } } deliver(theHandler, message); }
Source:
<code>public WorkspaceDto update( @ApiParam("The workspace id") @PathParam("id") String id, @ApiParam(value = "The workspace update", required = true) WorkspaceDto update) throws BadRequestException, ServerException, ForbiddenException, NotFoundException, ConflictException { <START> if (update.getDevfile() != null) { <END> update.setConfig(null); } relativizeRecipeLinks(update.getConfig()); return asDtoWithLinksAndToken(doUpdate(id, update)); }</code><technical_language>I this is meant a temporary fix this handled a slightly level in REST service</technical_language>

Target:
public WorkspaceDto update( @ApiParam("The workspace id") @PathParam("id") String id, @ApiParam(value = "The workspace update", required = true) WorkspaceDto update) throws BadRequestException, ServerException, ForbiddenException, NotFoundException, ConflictException { checkArgument( update.getConfig() != null || update.getDevfile() != null, "Required non-null workspace configuration or devfile update"); if (update.getDevfile() != null) { update.setConfig(null); } relativizeRecipeLinks(update.getConfig()); return asDtoWithLinksAndToken(doUpdate(id, update)); }
Source:
<code>private static SSLFactory getSSLFactoryIfRequired(VerifiableProperties verifiableProperties) throws Exception { <START> if (new ClusterMapConfig(verifiableProperties).clusterMapHttp2Enable) { <END> return new NettySslHttp2Factory(new SSLConfig(verifiableProperties)); } boolean sslRequired = new NettyConfig(verifiableProperties).nettyServerEnableSSL || new ClusterMapConfig(verifiableProperties).clusterMapSslEnabledDatacenters.length() > 0; return sslRequired ? SSLFactory.getNewInstance(new SSLConfig(verifiableProperties)) : null; }</code><technical_language>create instance of ClusterMapConfig ? need create ClusterMapConfig in some cases</technical_language>

Target:
private static SSLFactory getSSLFactoryIfRequired(VerifiableProperties verifiableProperties) throws Exception { ClusterMapConfig clusterMapConfig = new ClusterMapConfig(verifiableProperties); if (clusterMapConfig.clusterMapHttp2NetworkClientEnabled) { return new NettySslHttp2Factory(new SSLConfig(verifiableProperties)); } boolean sslRequired = new NettyConfig(verifiableProperties).nettyServerEnableSSL || clusterMapConfig.clusterMapSslEnabledDatacenters.length() > 0; return sslRequired ? SSLFactory.getNewInstance(new SSLConfig(verifiableProperties)) : null; }
Source:
<code>private void setIsSuicide(final Boolean s) { setIsSuicideOnAttack(s); <START> setIsSuicideOnDefense(s && !Properties.getDefendingSuicideAndMunitionUnitsDoNotFire(getData())); <END> setIsFirstStrike(s); }</code><technical_language>is this condition for suicide defense? !Properties.getDefendingSuicideAndMunitionUnitsDoNotFire(getData()));</technical_language>

Target:
private void setIsSuicide(final Boolean s) { setIsSuicideOnAttack(s); setIsSuicideOnDefense(s && !Properties.getDefendingSuicideAndMunitionUnitsDoNotFire(getData())); setIsFirstStrike(s); if (s) { canNotTarget = null; } else { resetCanNotTarget(); } }
Source:
<code>public synchronized void startForMaintenance(ServiceProvider<MaintainableService> serviceProvider) { <START> if (rootDirectory == null) { <END> return; } internalStart(); }</code><technical_language>is error</technical_language>

Target:
public synchronized void startForMaintenance(ServiceProvider<MaintainableService> serviceProvider) { internalStart(); }
Source:
<code>public void updateAccounts(Collection<Account> accounts) throws AccountServiceException { primaryAccountService.updateAccounts(accounts); try { secondaryAccountService.updateAccounts(accounts); } catch (Exception e) { <START> logger.error("Update accounts failed for secondary source", e); <END> accountServiceMetrics.updateAccountInconsistencyCount.inc(); } }</code><technical_language>I throw exception fail update. secondary service (mysql) error counter track failure, inconsistency reported background thread comparison. (And inconsistency disappear if client retries failed operation.)</technical_language>

Target:
public void updateAccounts(Collection<Account> accounts) throws AccountServiceException { primaryAccountService.updateAccounts(accounts); secondaryAccountService.updateAccounts(accounts); }
Source:
<code>public void checkin(CriticalComponent criticalService) { for (CriticalComponentImpl csi : this.criticalServiceList) { if (criticalService.equals(csi.getCriticalComponent())) { <START> csi.update(); <END> } } }</code><technical_language>add break statement</technical_language>

Target:
public void checkin(CriticalComponent criticalService) { for (CriticalComponentImpl csi : this.criticalComponentList) { if (criticalService.equals(csi.getCriticalComponent())) { csi.update(); break; } } }
Source:
<code>public void deleteHealthCheck(String healthCheckName) { log.info("Deleting Health Check: " + healthCheckName); try { Operation operation = compute.httpHealthChecks().delete(PROJECT_ID, healthCheckName).execute(); waitForGlobalOperationCompletion(operation.getName()); } catch (Exception e) { log.warn("Could not get delete health check " + healthCheckName + " " + e); } <START> log.info("Health check: " + healthCheckName + " was deleted"); <END> }</code><technical_language>This log.info message is relevant.IMO need try block</technical_language>

Target:
public void deleteHealthCheck(String healthCheckName) { log.info("Deleting Health Check: " + healthCheckName); try { Operation operation = compute.httpHealthChecks().delete(PROJECT_ID, healthCheckName).execute(); waitForGlobalOperationCompletion(operation.getName()); log.info("Health check: " + healthCheckName + " was deleted"); } catch (Exception e) { log.error("Could not get delete health check " + healthCheckName, e); } }
Source:
<code>private void removeGlusterVolumesFromDb() { List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(getVdsGroupId()); if (volumes.size() > 0) { for (GlusterVolumeEntity volume : volumes) { <START> getGlusterVolumeDao().remove(volume.getId()); <END> } } }</code><technical_language>is a single database call remove volumes of cluster</technical_language>

Target:
private void removeGlusterVolumesFromDb() { List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(getVdsGroupId()); if (volumes.size() > 0) { getGlusterVolumeDao().removeByClusterId(getVdsGroupId()); } }
Source:
<code>private static String removeBranchFromKey(String componentKey) { <START> return StringUtils.substringBeforeLast(componentKey, ":BRANCH:"); <END> }</code><technical_language>CompontentDto.BRANCH_KEY_SEPARATOR instead of hardcoding :BRANCH:</technical_language>

Target:
private static String removeBranchFromKey(String componentKey) { return StringUtils.substringBeforeLast(componentKey, ComponentDto.BRANCH_KEY_SEPARATOR); }
Source:
<code>public String getHostName(String host) { <START> String hostname = getInformation(host, SshToken.HOSTNAME); <END> if (hostname != null) { return hostname; } else { return "localhost"; } }</code><technical_language>new method isHostNameDefined here</technical_language>

Target:
public String getHostName(String host) { String hostName = getInformation(host, SshToken.HOSTNAME); if (hostName != null) { return hostName; } else { return host; } }
Source:
<code>public void start() { <START> Thread t = new Thread(this); <END> t.setDaemon(true); LOG.info("Starting FileWatcher on {}", watchedFile); t.start(); }</code><technical_language>Please provide names for Thread prefix Thread t = new Thread(basics, "FileWatcher-" + watchedFile.getName());</technical_language>

Target:
public void start() { Thread t = new Thread(this, "FileWatcher-" + watchedFile.getFileName()); t.setDaemon(true); LOG.info("Starting FileWatcher on {}", watchedFile); t.start(); }
Source:
<code>private BufferingPrologControl newEmptyMachine(ClassLoader cl) { BufferingPrologControl ctl = new BufferingPrologControl(); ctl.setMaxArity(PrologEnvironment.MAX_ARITY); ctl.setMaxDatabaseSize(DB_MAX); ctl.setPrologClassLoader(new PrologClassLoader(new PredicateClassLoader( predicateProviders, cl))); ctl.setEnabled(EnumSet.allOf(Prolog.Feature.class), false); <START> List<String> packages = new LinkedList<String>(PACKAGE_LIST); <END> for (PredicateProvider predicateProvider : predicateProviders) { packages.addAll(predicateProvider.getPackages()); } ctl.initialize(packages.toArray(new String[packages.size()])); return ctl; }</code><technical_language>Lists.newArrayList(); packages.addAll(PACKAGE_LIST); LinkedList is faster ArrayList. more memory efficient. a double linked list LinkedList is 4x memory usage entry of ArrayList. In general ArrayList frequent insertion removal in middle of list Iterator</technical_language>

Target:
private BufferingPrologControl newEmptyMachine(ClassLoader cl) { BufferingPrologControl ctl = new BufferingPrologControl(); ctl.setMaxArity(PrologEnvironment.MAX_ARITY); ctl.setMaxDatabaseSize(DB_MAX); ctl.setPrologClassLoader(new PrologClassLoader(new PredicateClassLoader( predicateProviders, cl))); ctl.setEnabled(EnumSet.allOf(Prolog.Feature.class), false); List<String> packages = Lists.newArrayList(); packages.addAll(PACKAGE_LIST); for (PredicateProvider predicateProvider : predicateProviders) { packages.addAll(predicateProvider.getPackages()); } ctl.initialize(packages.toArray(new String[packages.size()])); return ctl; }
Source:
<code>public Path generate(String id, String version, String... dependencyList) throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException { NugetArtifactCoordinates nac = new NugetArtifactCoordinates(id, version, "nupkg"); <START> Path basePath = Paths.get(getBasedir()).normalize().toAbsolutePath(); <END> Path nupkgPath = basePath.resolve(nac.toPath()).normalize().toAbsolutePath(); Files.createDirectories(nupkgPath.getParent()); SemanticVersion semanticVersion = SemanticVersion.parse(version); logger.debug("Version of the nupkg package: {}", semanticVersion.toString()); generate(nupkgPath, id, semanticVersion, dependencyList); return nupkgPath; }</code><technical_language>@ptirador need this basedir a java.nio.file.Path, basedir = basedir.normalize().toAbsolutePath() in constructor</technical_language>

Target:
public Path generate(String id, String version, String... dependencyList) throws IOException, NoSuchAlgorithmException, JAXBException, NugetFormatException { NugetArtifactCoordinates nac = new NugetArtifactCoordinates(id, version, "nupkg"); Path nupkgPath = basedir.resolve(nac.toPath()).normalize().toAbsolutePath(); Files.createDirectories(nupkgPath.getParent()); SemanticVersion semanticVersion = SemanticVersion.parse(version); logger.debug("Version of the nupkg package: {}", semanticVersion.toString()); generate(nupkgPath, id, semanticVersion, dependencyList); return nupkgPath; }
Source:
<code>private boolean validateWebhook(String receivedSignature, String payload) { StringCredentials webhookSecret = CredentialsProvider.findCredentialById(step.webhookSecretId, StringCredentials.class, getContextClass(Run.class)); CredentialsProvider.track(getContextClass(Run.class), webhookSecret); if (webhookSecret != null) { boolean isValidPayload = isValidSignature(receivedSignature, payload, webhookSecret.getSecret().getPlainText()); if (!isValidPayload) { <START> log("The incoming webhook was verified using the configured webhook secret and was found to be invalid"); <END> getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification ")); } else { log("The incoming webhook was verified using the configured webhook secret and was found to be valid"); } return isValidPayload; } else { log("A webhook secret id was configured, but the corresponding credential could not be found"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification")); return false; } }</code><technical_language>I find this phrasing a bit long. about: suggestion log("The incoming webhook match configured secret");</technical_language>

Target:
private boolean validateWebhook(String receivedSignature, String payload) { StringCredentials webhookSecret = CredentialsProvider.findCredentialById(step.webhookSecretId, StringCredentials.class, getContextClass(Run.class)); CredentialsProvider.track(getContextClass(Run.class), webhookSecret); if (webhookSecret != null) { boolean isValidPayload = isValidSignature(receivedSignature, payload, webhookSecret.getSecret().getPlainText()); if (!isValidPayload) { log("The incoming webhook didn't match the configured webhook secret"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification ")); } else { log("The incoming webhook matched the configured webhook secret"); } return isValidPayload; } else if (step.webhookSecretId != null && !step.webhookSecretId.isEmpty()) { log("A webhook secret id was configured, but the corresponding credential could not be found"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification")); return false; } return true; }
Source:
<code>public void handle(Request wsRequest, Response wsResponse) throws Exception { String query = wsRequest.param(PARAM_QUERY); String more = wsRequest.param(PARAM_MORE); List<String> recentlyBrowsedParam = wsRequest.paramAsStrings(PARAM_RECENTLY_BROWSED); Set<String> recentlyBrowsedKeys; if (recentlyBrowsedParam == null) { recentlyBrowsedKeys = emptySet(); } else { recentlyBrowsedKeys = recentlyBrowsedParam.stream().limit(MAXIMUM_RECENTLY_BROWSED).collect(Collectors.toSet()); } <START> Set<String> favoriteKeys = favoriteFinder.list().stream().map(ComponentDto::getKey).collect(Collectors.toSet()); <END> List<String> qualifiers = getQualifiers(more); SuggestionsWsResponse searchWsResponse; if (query == null) { searchWsResponse = suggestionsWithoutSearch(more, recentlyBrowsedKeys, favoriteKeys, qualifiers); } else { searchWsResponse = suggestionsFromSearch(query, more, recentlyBrowsedKeys, favoriteKeys, qualifiers); } writeProtobuf(searchWsResponse, wsRequest, wsResponse); }</code><technical_language>recentlyBrowsedKeys extracted a specific method: Set<String> recentlyBrowsedKeys = getRecentlyBrowsedKeys(wsRequest);</technical_language>

Target:
public void handle(Request wsRequest, Response wsResponse) throws Exception { String query = wsRequest.param(PARAM_QUERY); String more = wsRequest.param(PARAM_MORE); Set<String> recentlyBrowsedKeys = getRecentlyBrowsedKeys(wsRequest); List<String> qualifiers = getQualifiers(more); int skip = more == null ? 0 : DEFAULT_LIMIT; int limit = more == null ? DEFAULT_LIMIT : EXTENDED_LIMIT; SuggestionsWsResponse searchWsResponse = loadSuggestions(query, skip, limit, recentlyBrowsedKeys, qualifiers); writeProtobuf(searchWsResponse, wsRequest, wsResponse); }
Source:
<code>public ByteBuffer encrypt(byte[] input, int offset, int len){ try{ if(type == CryptByteBufferType.RijndaelPCFB){ return ByteBuffer.wrap(encryptPCFB.blockEncipher(input, offset, len)); } <START> else if(type.cipherName == "RIJNDAEL"){ <END> byte[] result = new byte[len]; blockCipher.encipher(extractSmallerArray(input, offset, len), result); return ByteBuffer.wrap(result); } else{ return ByteBuffer.wrap(encryptCipher.doFinal(input, offset, len)); } } catch (GeneralSecurityException e) { e.printStackTrace(); Logger.error(CryptByteBuffer.class, "Internal error; please report:", e); } return null; }</code><technical_language>assuming necessary Rijndael</technical_language>

Target:
public ByteBuffer encrypt(byte[] input, int offset, int len){ try{ if(type == CryptByteBufferType.RijndaelPCFB){ return ByteBuffer.wrap(encryptPCFB.blockEncipher(input, offset, len)); } else if(type.cipherName.equals("RIJNDAEL")){ byte[] result = new byte[len]; blockCipher.encipher(extractSmallerArray(input, offset, len), result); return ByteBuffer.wrap(result); } else{ return ByteBuffer.wrap(encryptCipher.doFinal(input, offset, len)); } } catch (GeneralSecurityException e) { e.printStackTrace(); Logger.error(CryptByteBuffer.class, "Internal error; please report:", e); } return null; }
Source:
<code>public Node<View<Decision>, ?> nodeFromDMN(final org.kie.dmn.model.api.Decision dmn) { @SuppressWarnings("unchecked") Node<View<Decision>, ?> node = (Node<View<Decision>, ?>) factoryManager.newElement(dmn.getId(), Decision.class).asNode(); Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); Name name = new Name(dmn.getName()); InformationItem informationItem = InformationItemPropertyConverter.wbFromDMN(dmn.getVariable()); Expression expression = ExpressionPropertyConverter.wbFromDMN(dmn.getExpression()); Decision decision = new Decision(id, description, name, new Question(), new AllowedAnswers(), informationItem, expression, new BackgroundSet(), new FontSet(), new RectangleDimensionsSet()); <START> decision.setQuestion(new Question(dmn.getQuestion())); <END> decision.setAllowedAnswers(new AllowedAnswers(dmn.getAllowedAnswers())); node.getContent().setDefinition(decision); if (informationItem != null) { informationItem.setParent(decision); } if (expression != null) { expression.setParent(decision); } return node; }</code><technical_language>DMN's null</technical_language>

Target:
public Node<View<Decision>, ?> nodeFromDMN(final org.kie.dmn.model.api.Decision dmn) { @SuppressWarnings("unchecked") Node<View<Decision>, ?> node = (Node<View<Decision>, ?>) factoryManager.newElement(dmn.getId(), Decision.class).asNode(); Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); Name name = new Name(dmn.getName()); InformationItem informationItem = InformationItemPropertyConverter.wbFromDMN(dmn.getVariable()); Expression expression = ExpressionPropertyConverter.wbFromDMN(dmn.getExpression()); Decision decision = new Decision(id, description, name, new Question(), new AllowedAnswers(), informationItem, expression, new BackgroundSet(), new FontSet(), new RectangleDimensionsSet()); decision.setQuestion(QuestionPropertyConverter.wbFromDMN(dmn.getQuestion())); decision.setAllowedAnswers(AllowedAnswersPropertyConverter.wbFromDMN(dmn.getAllowedAnswers())); node.getContent().setDefinition(decision); if (informationItem != null) { informationItem.setParent(decision); } if (expression != null) { expression.setParent(decision); } return node; }
Source:
<code>public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); <START> trackingFile.write( <END> Json.createObjectBuilder() .add(NATSClient.SERVER_HOST_PROPERTY,client.getServerHost()) .add(NATSClient.SERVER_PORT_PROPERTY,client.getServerPort()) .add(NATSClient.CLUSTER_ID_PROPERTY,client.getClusterId()) .add(NATSClient.CLIENT_ID_PROPERTY,client.getClientId()) .add(NATSClient.SUBJECT_PROPERTY,subject) .add(SEQUENCE_PROPERTY,sequence) .build() ); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess.":"") + " Stack Trace: " + e); LOGGER.log(Level.FINE, "[" + getName() + "] Message: " + message.getData()); } }</code><technical_language>WebsocketNotificationReceiver, watch indentation</technical_language>

Target:
public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); writeTrackingFile(); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess.":"") + " Stack Trace: " + e); LOGGER.log(Level.FINE, "[" + getName() + "] Message: " + message.getData()); } }
Source:
<code><START> public Config.ExporterStatus getSynapseExporterStatus() { return this.synapseExporterStatus; } <END></code><technical_language>I pull this constant out RecordExportStatusRequest resides, this is enum in Config inconsistent</technical_language>

Target:
public ExporterStatus getSynapseExporterStatus() { return this.synapseExporterStatus; }
Source:
<code>private void processHealthcheck(ServiceEvent event) { String[] splitted = event.getHealthcheckUuid().split("_"); HealthcheckInstanceHostMap hostMap = null; String uuid = null; if (splitted.length > 2) { hostMap = serviceDao.getHealthCheckInstanceUUID(splitted[0], splitted[1]); if (hostMap != null) { uuid = hostMap.getUuid(); } } else { uuid = splitted[0]; } <START> if (uuid != null && event.getExternalTimestamp() != null) { <END> healthcheckService.updateHealthcheck(uuid, event.getExternalTimestamp(), getHealthState(event.getReportedHealth())); } }</code><technical_language>@kinarashah log a warning external timestamp is nil</technical_language>

Target:
private void processHealthcheck(ServiceEvent event) { String[] splitted = event.getHealthcheckUuid().split("_"); HealthcheckInstanceHostMap hostMap = null; String uuid = null; if (splitted.length > 2) { hostMap = serviceDao.getHealthCheckInstanceUUID(splitted[0], splitted[1]); if (hostMap != null) { uuid = hostMap.getUuid(); } } else { uuid = splitted[0]; } if (uuid != null) { if(event.getExternalTimestamp() == null) { log.warn("ExternalTimestamp null for event hostMapUUID {}", event.getId(), uuid); return; } healthcheckService.updateHealthcheck(uuid, event.getExternalTimestamp(), getHealthState(event.getReportedHealth())); } }
Source:
<code>public Object getAndReplace(Data key, Object value, ExpiryPolicy expiryPolicy, UUID source, int completionId) { long now = Clock.currentTimeMillis(); <START> long startNano = isStatisticsEnabled() ? timer.nanos() : 0; <END> boolean replaced = false; R record = records.get(key); expiryPolicy = getExpiryPolicy(record, expiryPolicy); boolean isExpired = record != null && record.isExpiredAt(now); try { Object obj = toValue(record); if (recordNotExistOrExpired(record, isExpired)) { obj = null; if (isEventsEnabled()) { publishEvent(createCacheCompleteEvent(toEventData(key), completionId)); } } else { replaced = updateRecordWithExpiry(key, value, record, expiryPolicy, now, false, completionId, source); } onReplace(key, null, value, expiryPolicy, source, false, record, isExpired, replaced); if (isStatisticsEnabled()) { statistics.addGetTimeNanos(timer.nanosElapsedSince(startNano)); if (obj != null) { statistics.increaseCacheHits(1); statistics.increaseCachePuts(1); statistics.addPutTimeNanos(timer.nanosElapsedSince(startNano)); } else { statistics.increaseCacheMisses(1); } } return obj; } catch (Throwable error) { onReplaceError(key, null, value, expiryPolicy, source, false, record, isExpired, replaced, error); throw ExceptionUtil.rethrow(error); } }</code><technical_language>I call this startNanos startNs</technical_language>

Target:
public Object getAndReplace(Data key, Object value, ExpiryPolicy expiryPolicy, UUID source, int completionId) { long now = Clock.currentTimeMillis(); long startNanos = isStatisticsEnabled() ? Timer.nanos() : 0; boolean replaced = false; R record = records.get(key); expiryPolicy = getExpiryPolicy(record, expiryPolicy); boolean isExpired = record != null && record.isExpiredAt(now); try { Object obj = toValue(record); if (recordNotExistOrExpired(record, isExpired)) { obj = null; if (isEventsEnabled()) { publishEvent(createCacheCompleteEvent(toEventData(key), completionId)); } } else { replaced = updateRecordWithExpiry(key, value, record, expiryPolicy, now, false, completionId, source); } onReplace(key, null, value, expiryPolicy, source, false, record, isExpired, replaced); if (isStatisticsEnabled()) { statistics.addGetTimeNanos(Timer.nanosElapsed(startNanos)); if (obj != null) { statistics.increaseCacheHits(1); statistics.increaseCachePuts(1); statistics.addPutTimeNanos(Timer.nanosElapsed(startNanos)); } else { statistics.increaseCacheMisses(1); } } return obj; } catch (Throwable error) { onReplaceError(key, null, value, expiryPolicy, source, false, record, isExpired, replaced, error); throw ExceptionUtil.rethrow(error); } }
Source:
<code>public List<StreamsDatum> process(StreamsDatum entry) { StreamsDatum result = null; try { Object item = entry.getDocument(); ObjectNode node; LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); if( item instanceof String ) { if( String.class.equals(outClass)) { result = entry; } else { node = (ObjectNode)mapper.readTree((String)item); Class inClass = TwitterEventClassifier.detectClass((String) item); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } else if( item instanceof ObjectNode ) { node = (ObjectNode)mapper.valueToTree(item); <START> Class inClass = TwitterEventClassifier.detectClass(item.toString()); <END> Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } catch (Exception e) { e.printStackTrace(); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }</code><technical_language>mapper.writeValueAsString</technical_language>

Target:
public List<StreamsDatum> process(StreamsDatum entry) { StreamsDatum result = null; try { Object item = entry.getDocument(); ObjectNode node; LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); if( item instanceof String ) { if( String.class.equals(outClass)) { result = entry; } else { node = (ObjectNode)mapper.readTree((String)item); Class inClass = TwitterEventClassifier.detectClass((String) item); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } else if( item instanceof ObjectNode ) { node = (ObjectNode)mapper.valueToTree(item); Class inClass = TwitterEventClassifier.detectClass(mapper.writeValueAsString(item)); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } catch (Exception e) { e.printStackTrace(); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }
Source:
<code>private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) <START> .setClusterHost("192.168.1.56") <END> .setClusterPort(17001) .setClusterManager(clusterManager); return options; }</code><technical_language>is clusterHost clusterPort required</technical_language>

Target:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterManager(clusterManager); return options; }
Source:
<code>public static Channel createChannel(final TransportOptions transportOptions, final ChannelOptions channelOptions, final ExecutorService executor, boolean createPool) { Preconditions.checkArgument( transportOptions.getTransport() == TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, "Bigtable requires the NETTY_TLS transport."); <START> int channelCount = createPool ? channelOptions.getChannelCount() : 1; <END> long timeoutMs = channelOptions.getTimeoutMs(); Channel channels[] = new Channel[channelCount]; for (int i = 0; i < channelCount; i++) { ReconnectingChannel reconnectingChannel = createReconnectingChannel(transportOptions, executor, timeoutMs); channelOptions.addClientCloseHandler(reconnectingChannel); channels[i] = reconnectingChannel; } Channel channel = new ChannelPool(channels); return wrapChannel(channelOptions, executor, channel); }</code><technical_language>is createPool necessary? Shouldnt this controled channelOptions.getChannelCount()</technical_language>

Target:
public static CloseableChannel createChannel(final TransportOptions transportOptions, final ChannelOptions channelOptions, final ExecutorService executor, boolean createPool) { Preconditions.checkArgument( transportOptions.getTransport() == TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, "Bigtable requires the NETTY_TLS transport."); int channelCount = channelOptions.getChannelCount(); long timeoutMs = channelOptions.getTimeoutMs(); CloseableChannel channel = null; if (channelCount > 1 && createPool) { CloseableChannel channels[] = new CloseableChannel[channelCount]; for (int i = 0; i < channelCount; i++) { CloseableChannel channelImpl = createRefreshingChannel(transportOptions, executor, timeoutMs); channels[i] = channelImpl; } CloseableChannel pooledChannel = new ChannelPool(channels); channel = pooledChannel; } else { channel = createRefreshingChannel(transportOptions, executor, timeoutMs); } return wrapChannel(channelOptions, executor, channel, createChannelClose(channel)); }