auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<MentionedActorReference, List<String>> groupAnchorsByUserReference(List<MacroBlock> mentions) { Map<MentionedActorReference, List<String>> ret = new HashMap<>(); for (MacroBlock block : mentions) { String userReference = block.getParameter(REFERENCE_PARAM_NAME); <START> ret.merge(new MentionedActorReference(userReference, block.getParameter(TYPE_PARAM_NAME)), <END> new ArrayList<>(singletonList(block.getParameter(ANCHORID_PARAM_NAME))), (l1, l2) -> { l1.addAll(l2); return l1; }); } return ret; }</code><technical_language>Note type parameter is new, need consider this parameter exist for some mentions: handled in code</technical_language>

Target:
public Map<MentionedActorReference, List<String>> groupAnchorsByUserReference(List<MacroBlock> mentions) { Map<MentionedActorReference, List<String>> ret = new HashMap<>(); for (MacroBlock block : mentions) { String userReference = block.getParameter(REFERENCE_PARAM_NAME); String type = Optional.ofNullable(block.getParameter(TYPE_PARAM_NAME)).orElse(USER_MENTION_TYPE); ret.merge(new MentionedActorReference(userReference, type), new ArrayList<>(singletonList(block.getParameter(ANCHORID_PARAM_NAME))), (l1, l2) -> { l1.addAll(l2); return l1; }); } return ret; }
Source:
<code>public static Object[][] testPositiveByteValues() { final List<Byte> positiveByteTests = IOTestCases.byteTests() .stream() .filter(b -> b >= 0) .collect(Collectors.toList()); final List<Byte> shuffled = new ArrayList<>(positiveByteTests); <START> Collections.shuffle(shuffled); <END> return new Object[][]{ {positiveByteTests}, {shuffled} }; }</code><technical_language>shuffle these? If need shuffle a set random seed? TestUtil.RANDOM_SEED is a good option</technical_language>

Target:
public static Object[][] testPositiveByteValues() { final List<Byte> positiveByteTests = IOTestCases.byteTests() .stream() .filter(b -> b >= 0) .collect(Collectors.toList()); final List<Byte> shuffled = new ArrayList<>(positiveByteTests); Collections.shuffle(shuffled, RANDOM); return new Object[][]{ {positiveByteTests}, {shuffled} }; }
Source:
<code><START> public InstrumentedInterceptor(MetricRegistry registry, String name) { <END> informational = registry.meter(MetricRegistry.name(name, "response", "code", "1xx")); successful = registry.meter(MetricRegistry.name(name, "response", "code", "2xx")); redirection = registry.meter(MetricRegistry.name(name, "response", "code", "3xx")); clientError = registry.meter(MetricRegistry.name(name, "response", "code", "4xx")); serverError = registry.meter(MetricRegistry.name(name, "response", "code", "5xx")); other = registry.meter(MetricRegistry.name(name, "response", "code", "other")); }</code><technical_language>hooked OkHttp client right now, envisioning wiring in metric registry</technical_language>

Target:
InstrumentedInterceptor(MetricRegistry registry, String name) { informational = registry.meter(MetricRegistry.name(name, "response", "family", "informational")); successful = registry.meter(MetricRegistry.name(name, "response", "family", "successful")); redirection = registry.meter(MetricRegistry.name(name, "response", "family", "redirection")); clientError = registry.meter(MetricRegistry.name(name, "response", "family", "client-error")); serverError = registry.meter(MetricRegistry.name(name, "response", "family", "server-error")); other = registry.meter(MetricRegistry.name(name, "response", "family", "other")); }
Source:
<code>protected void setUp() throws Exception { super.setUp(); File origRepo = getTestFile( "target/test-classes/test-repo-git" ); File testRepo = getTestFile( "target/test-classes/test-repo-git-test" ); FileUtils.deleteDirectory( testRepo ); FileUtils.copyDirectoryStructure( origRepo, testRepo ); <START> repository = "scm:git:file://" + testRepo.toURI().getPath(); <END> }</code><technical_language>Note File#toURI() produces invalid URI. Convert NIO Path URI</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); File origRepo = getTestFile( "target/test-classes/test-repo-git" ); File testRepo = getTestFile( "target/test-classes/test-repo-git-test" ); FileUtils.deleteDirectory( testRepo ); FileUtils.copyDirectoryStructure( origRepo, testRepo ); repository = "scm:git:" + testRepo.toPath().toUri(); }
Source:
<code>private List<ERepositoryObjectType> getAllMetaDataType() { List<ERepositoryObjectType> list = new ArrayList<ERepositoryObjectType>(); list.add(ERepositoryObjectType.METADATA_CONNECTIONS); list.add(ERepositoryObjectType.METADATA_FILE_FTP); list.add(ERepositoryObjectType.METADATA_LDAP_SCHEMA); list.add(ERepositoryObjectType.METADATA_MDMCONNECTION); list.add(ERepositoryObjectType.METADATA_SAPCONNECTIONS); <START> list.add(ERepositoryObjectType.METADATA_SAPCONNECTIONS); <END> if (GlobalServiceRegister.getDefault().isServiceRegistered(INOSQLService.class)) { INOSQLService nosqlService = (INOSQLService) GlobalServiceRegister.getDefault().getService(INOSQLService.class); if (nosqlService != null) { list.add(nosqlService.getNOSQLRepositoryType()); } } return list; }</code><technical_language>please remove this duplicated line</technical_language>

Target:
private List<ERepositoryObjectType> getAllMetaDataType() { List<ERepositoryObjectType> list = new ArrayList<ERepositoryObjectType>(); list.add(ERepositoryObjectType.METADATA_CONNECTIONS); list.add(ERepositoryObjectType.METADATA_FILE_FTP); list.add(ERepositoryObjectType.METADATA_LDAP_SCHEMA); list.add(ERepositoryObjectType.METADATA_MDMCONNECTION); list.add(ERepositoryObjectType.METADATA_SAPCONNECTIONS); if (GlobalServiceRegister.getDefault().isServiceRegistered(INOSQLService.class)) { INOSQLService nosqlService = (INOSQLService) GlobalServiceRegister.getDefault().getService(INOSQLService.class); if (nosqlService != null) { list.add(nosqlService.getNOSQLRepositoryType()); } } return list; }
Source:
<code>public BoardPanel(BoardSize boardSize, SquareConfig squareConfig, Function<BoardCoordinate, Set<BoardCoordinate>> getMovesCallback) { super(false); mSquareConfig = squareConfig; mGetMovesCallback = getMovesCallback; mBoardSize = boardSize; mSquareLabels = new ArrayList<>(boardSize.width * boardSize.height); <START> GridLayout gridLayout = new GridLayout(mBoardSize.height + 1, mBoardSize.width + 2); <END> setLayout(gridLayout); createGrid(gridLayout); }</code><technical_language>have: private static final int VERTICAL_PADDING = 1 private static final int HORIZONTAL_PADDING = 2 instead of magic 1's 2's everywhere</technical_language>

Target:
public BoardPanel(BoardSize boardSize, SquareConfig squareConfig, Function<BoardCoordinate, Set<BoardCoordinate>> getMovesCallback) { super(false); mSquareConfig = squareConfig; mGetMovesCallback = getMovesCallback; mBoardSize = boardSize; mTotalBoardSize = BoardSize.withDimensions(mBoardSize.width + HORIZONTAL_PADDING, mBoardSize.height + VERTICAL_PADDING); mSquareLabels = new ArrayList<>(boardSize.width * boardSize.height); GridLayout gridLayout = new GridLayout(mTotalBoardSize.height, mTotalBoardSize.width); setLayout(gridLayout); createGrid(gridLayout); }
Source:
<code>protected Handler createAppServlet(Server server, JerseyEnvironment jersey, ObjectMapper objectMapper, Validator validator, MutableServletContextHandler handler, @Nullable Servlet jerseyContainer, MetricRegistry metricRegistry) { configureSessionsAndSecurity(handler, server); handler.addFilter(AllowedMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)) .setInitParameter(AllowedMethodsFilter.ALLOWED_METHODS_PARAM, Joiner.on(',').join(allowedMethods)); handler.addFilter(ThreadNameFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); serverPush.addFilter(handler); if (jerseyContainer != null) { if (jerseyRootPath.isPresent()) { String urlPattern = jerseyRootPath.get(); <START> if (!urlPattern.endsWith("*") && !urlPattern.endsWith("/")) { <END> urlPattern += "/"; } if (!urlPattern.endsWith("*")) { urlPattern += "*"; } jersey.setUrlPattern(urlPattern); } jersey.register(new JacksonMessageBodyProvider(objectMapper)); jersey.register(new HibernateValidationFeature(validator)); if (registerDefaultExceptionMappers == null || registerDefaultExceptionMappers) { jersey.register(new LoggingExceptionMapper<Throwable>() { }); jersey.register(new JerseyViolationExceptionMapper()); jersey.register(new JsonProcessingExceptionMapper()); jersey.register(new EarlyEofExceptionMapper()); } handler.addServlet(new NonblockingServletHolder(jerseyContainer), jersey.getUrlPattern()); } final InstrumentedHandler instrumented = new InstrumentedHandler(metricRegistry); instrumented.setServer(server); instrumented.setHandler(handler); return instrumented; }</code><technical_language>do moving this logic for "normalizing" urlPattern JerseyEnvironment#setUrlPattern, if expect users invoke this method application class</technical_language>

Target:
protected Handler createAppServlet(Server server, JerseyEnvironment jersey, ObjectMapper objectMapper, Validator validator, MutableServletContextHandler handler, @Nullable Servlet jerseyContainer, MetricRegistry metricRegistry) { configureSessionsAndSecurity(handler, server); handler.addFilter(AllowedMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)) .setInitParameter(AllowedMethodsFilter.ALLOWED_METHODS_PARAM, Joiner.on(',').join(allowedMethods)); handler.addFilter(ThreadNameFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); serverPush.addFilter(handler); if (jerseyContainer != null) { if (jerseyRootPath.isPresent()) { jersey.setUrlPattern(jerseyRootPath.get()); } jersey.register(new JacksonMessageBodyProvider(objectMapper)); jersey.register(new HibernateValidationFeature(validator)); if (registerDefaultExceptionMappers == null || registerDefaultExceptionMappers) { jersey.register(new LoggingExceptionMapper<Throwable>() { }); jersey.register(new JerseyViolationExceptionMapper()); jersey.register(new JsonProcessingExceptionMapper()); jersey.register(new EarlyEofExceptionMapper()); } handler.addServlet(new NonblockingServletHolder(jerseyContainer), jersey.getUrlPattern()); } final InstrumentedHandler instrumented = new InstrumentedHandler(metricRegistry); instrumented.setServer(server); instrumented.setHandler(handler); return instrumented; }
Source:
<code>public RepositoryDTO fetchInstallableApplications() { try { final List<CategoryDTO> categoryDTOs = new ArrayList<>(); Resource[] resources = resourceResolver.getResources(packagePath + "/*"); for (Resource resource : resources) { final CategoryDTO category = buildCategory(resource.getFilename()); if (!category.getApplications().isEmpty()) { categoryDTOs.add(category); } } Collections.sort(categoryDTOs, Comparator.comparing(CategoryDTO::getName)); final RepositoryDTO.Builder repositoryDTOBuilder = new RepositoryDTO.Builder() .withName("classpath repository").withCategories(categoryDTOs); return repositoryDTOBuilder.build(); } catch (IOException e) { LOGGER.warn("Error while reading resource directory", e); <START> return null; <END> } }</code><technical_language>return empty RepositoryDTO</technical_language>

Target:
public RepositoryDTO fetchInstallableApplications() { try { final List<CategoryDTO> categoryDTOs = new ArrayList<>(); Resource[] resources = resourceResolver.getResources(packagePath + "/*"); for (Resource resource : resources) { final CategoryDTO category = buildCategory(resource.getFilename()); if (!category.getApplications().isEmpty()) { categoryDTOs.add(category); } } Collections.sort(categoryDTOs, Comparator.comparing(CategoryDTO::getName)); final RepositoryDTO.Builder repositoryDTOBuilder = new RepositoryDTO.Builder() .withName("classpath repository").withCategories(categoryDTOs); return repositoryDTOBuilder.build(); } catch (IOException e) { LOGGER.warn("Error while reading resource directory", e); return new RepositoryDTO.Builder().build(); } }
Source:
<code>private void readChannelsByNames(final KuraResponsePayload respPayload, final String assetPid, final String channelName) { requireNonNull(respPayload, message.respPayloadNonNull()); requireNonNull(assetPid, message.assetPidNonNull()); requireNonNull(channelName, message.channelIdNonNull()); final String channelDelim = "#"; <START> Set<String> channelIds = null; <END> if (channelName.contains(channelDelim)) { channelIds = CollectionUtil.newHashSet(Arrays.asList(channelName.split(channelDelim))); channelIds.removeAll(Collections.singleton("")); } final Asset asset = this.assets.get(assetPid); final AssetConfiguration configuration = asset.getAssetConfiguration(); final Map<String, Channel> assetConfiguredChannels = configuration.getAssetChannels(); final Set<String> channelNamesToRead = CollectionUtil.newHashSet(); if (channelIds == null) { channelNamesToRead.add(channelName); } else { for (final String chName : channelIds) { channelNamesToRead.add(chName); } } if (assetConfiguredChannels != null) { List<AssetRecord> assetRecords = null; try { assetRecords = asset.read(channelNamesToRead); } catch (final KuraException e) { logger.warn(message.connectionException() + e); respPayload.addMetric(message.errorMessage(), message.connectionException()); } if (assetRecords != null) { this.prepareResponse(respPayload, assetRecords); } } }</code><technical_language>channelIds => channelNames</technical_language>

Target:
private void readChannelsByNames(final KuraResponsePayload respPayload, final String assetPid, final String channelName) { requireNonNull(respPayload, message.respPayloadNonNull()); requireNonNull(assetPid, message.assetPidNonNull()); requireNonNull(channelName, message.channelNameNonNull()); final String channelDelim = "#"; Set<String> channelNames = null; if (channelName.contains(channelDelim)) { channelNames = CollectionUtil.newHashSet(Arrays.asList(channelName.split(channelDelim))); channelNames.removeAll(Collections.singleton("")); } final Asset asset = this.assets.get(assetPid); final AssetConfiguration configuration = asset.getAssetConfiguration(); final Map<String, Channel> assetConfiguredChannels = configuration.getAssetChannels(); final Set<String> channelNamesToRead = CollectionUtil.newHashSet(); if (channelNames == null) { channelNamesToRead.add(channelName); } else { for (final String chName : channelNames) { channelNamesToRead.add(chName); } } if (assetConfiguredChannels != null) { List<AssetRecord> assetRecords = null; try { assetRecords = asset.read(channelNamesToRead); } catch (final KuraException e) { logger.warn(message.connectionException() + e); respPayload.addMetric(message.errorMessage(), message.connectionException()); } if (assetRecords != null) { this.prepareResponse(respPayload, assetRecords); } } }
Source:
<code>public int run() { boolean hasRequired = false; if (helpCommands.isEmpty()) { console.info( "\nUsage: [options] [command] [command options]", programName); console.info("\n Options:\n"); for (ParameterDescription param : jc.getParameters()) { hasRequired = printOption(console, param) || hasRequired; } if (hasRequired) { console.info("\n * = required"); } console.info("\n Commands:\n"); for (String command : jc.getCommands().keySet()) { console.info(" {}\n\t{}", command, jc.getCommandDescription(command)); } console.info("\n Examples:"); console.info("\n # print information for create\n help create", programName); console.info("\n See '{} help <command>' for more information on a " + "specific command.", programName); } else { for (String cmd : helpCommands) { JCommander commander = jc.getCommands().get(cmd); if (commander == null) { <START> console.error("Unknown command: {}", cmd); <END> return 1; } console.info("\nUsage: [general options] [command options]", new Object[] { programName, cmd, commander.getMainParameterDescription()}); console.info("\n Description:"); console.info("\n {}", jc.getCommandDescription(cmd)); if (!commander.getParameters().isEmpty()) { console.info("\n Command options:\n"); for (ParameterDescription param : commander.getParameters()) { hasRequired = printOption(console, param) || hasRequired; } if (hasRequired) { console.info("\n * = required"); } } List<String> examples = ((Command) commander.getObjects().get(0)).getExamples(); if (examples != null) { console.info("\n Examples:"); for (String example : examples) { if (example.startsWith("#")) { console.info("\n {}", example); } else { console.info(" {}", new Object[] {programName, cmd, example}); } } } console.info(""); } } return 0; }</code><technical_language>list set of commands here</technical_language>

Target:
public int run() { if (helpCommands.isEmpty()) { printGenericHelp(); } else { for (String cmd : helpCommands) { JCommander commander = jc.getCommands().get(cmd); if (commander == null) { console.error("\nUnknown command: {}\n", cmd); printGenericHelp(); return 1; } boolean hasRequired = false; console.info("\nUsage: [general options] [command options]", new Object[] { programName, cmd, commander.getMainParameterDescription()}); console.info("\n Description:"); console.info("\n {}", jc.getCommandDescription(cmd)); if (!commander.getParameters().isEmpty()) { console.info("\n Command options:\n"); for (ParameterDescription param : commander.getParameters()) { hasRequired = printOption(console, param) || hasRequired; } if (hasRequired) { console.info("\n * = required"); } } List<String> examples = ((Command) commander.getObjects().get(0)).getExamples(); if (examples != null) { console.info("\n Examples:"); for (String example : examples) { if (example.startsWith("#")) { console.info("\n {}", example); } else { console.info(" {}", new Object[] {programName, cmd, example}); } } } console.info(""); } } return 0; }
Source:
<code>public boolean equals(Object obj) { if ( this == obj ) <START> return true; <END> if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; RegistrationId other = (RegistrationId) obj; if ( department == null ) { if ( other.department != null ) return false; } else if ( !department.equals( other.department ) ) return false; if ( studentId != other.studentId ) return false; return true; }</code><technical_language>Missing braces here, checkstyle is failing</technical_language>

Target:
public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } RegistrationId other = (RegistrationId) obj; if ( department == null ) { if ( other.department != null ) { return false; } } else if ( !department.equals( other.department ) ) { return false; } return studentId == other.studentId; }
Source:
<code>public void onEvent(BrokerEvent event) { <START> if (!workspaceId.equals(event.getRuntimeId().getWorkspaceId())) { <END> return; } switch (event.getStatus()) { case DONE: List<ChePlugin> tooling = event.getTooling(); if (tooling != null) { finishFuture.complete(tooling); } else { finishFuture.completeExceptionally( new InternalInfrastructureException( format( "Plugin brokering process for workspace `%s` is finished but plugins list is missing", workspaceId))); } break; case FAILED: finishFuture.completeExceptionally( new InfrastructureException( format( "Plugin broking process for workspace %s failed with error: %s", workspaceId, event.getError()))); break; case STARTED: default: } }</code><technical_language>Please, check runtime is NULL</technical_language>

Target:
public void onEvent(BrokerEvent event) { if (event.getRuntimeId() == null || !workspaceId.equals(event.getRuntimeId().getWorkspaceId())) { return; } switch (event.getStatus()) { case DONE: List<ChePlugin> tooling = event.getTooling(); if (tooling != null) { finishFuture.complete(tooling); } else { finishFuture.completeExceptionally( new InternalInfrastructureException( format( "Plugin brokering process for workspace `%s` is finished but plugins list is missing", workspaceId))); } break; case FAILED: finishFuture.completeExceptionally( new InfrastructureException( format( "Plugin broking process for workspace %s failed with error: %s", workspaceId, event.getError()))); break; case STARTED: default: } }
Source:
<code>public void onItemClick(int position){ switch (position) { case IMPORTANT_TO_ME: startActivity(new Intent(getApplicationContext(), BehaviorProgressActivity.class)); break; case MY_PRIORITIES: startActivity(new Intent(getApplicationContext(), MyPrioritiesActivity.class)); break; case MYSELF: startActivity(new Intent(getApplicationContext(), UserProfileActivity.class)); break; case MY_PRIVACY: <START> break; <END> case SETTINGS: Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); startActivityForResult(intent, Constants.SETTINGS_REQUEST_CODE); break; case TOUR: startActivity(new Intent(getApplicationContext(), TourActivity.class)); break; case DRAWER_COUNT: break; } mDrawerLayout.closeDrawers(); }</code><technical_language>this a mistake</technical_language>

Target:
public void onItemClick(int position){ switch (position) { case IMPORTANT_TO_ME: startActivity(new Intent(getApplicationContext(), BehaviorProgressActivity.class)); break; case MY_PRIORITIES: startActivity(new Intent(getApplicationContext(), MyPrioritiesActivity.class)); break; case MYSELF: startActivity(new Intent(getApplicationContext(), UserProfileActivity.class)); break; case MY_PRIVACY: startActivity(new Intent(getApplicationContext(), PrivacyActivity.class)); break; case SETTINGS: Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); startActivityForResult(intent, Constants.SETTINGS_REQUEST_CODE); break; case TOUR: startActivity(new Intent(getApplicationContext(), TourActivity.class)); break; case DRAWER_COUNT: break; } mDrawerLayout.closeDrawers(); }
Source:
<code>private boolean isLockable(StudyEventDefinitionBean sed, StudyEventDAO sedao, EventCRFDAO ecdao, ItemDataDAO iddao) { ArrayList events = (ArrayList) sedao.findAllByDefinition(sed.getId()); for (int j = 0; j < events.size(); j++) { StudyEventBean event = (StudyEventBean) events.get(j); <START> if ((event.getRemoved()!=null && event.getRemoved()) || (event.getArchived()!=null && event.getArchived())) { <END> return false; } ArrayList eventCRFs = ecdao.findAllByStudyEvent(event); for (int k = 0; k < eventCRFs.size(); k++) { EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k); if ((eventCRF.getRemoved()!=null && eventCRF.getRemoved()) || (eventCRF.getArchived()!=null && eventCRF.getArchived())) { return false; } ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId()); for (int a = 0; a < itemDatas.size(); a++) { ItemDataBean item = (ItemDataBean) itemDatas.get(a); if (!(item.getStatus().equals(Status.UNAVAILABLE) || item.getStatus().equals(Status.DELETED))) { return false; } } } } return true; }</code><technical_language>a lot of instances. Please update BooleanUtils</technical_language>

Target:
private boolean isLockable(StudyEventDefinitionBean sed, StudyEventDAO sedao, EventCRFDAO ecdao, ItemDataDAO iddao) { ArrayList events = (ArrayList) sedao.findAllByDefinition(sed.getId()); for (int j = 0; j < events.size(); j++) { StudyEventBean event = (StudyEventBean) events.get(j); if ( BooleanUtils.isTrue(event.getRemoved()) || BooleanUtils.isTrue(event.getArchived())) { return false; } ArrayList eventCRFs = ecdao.findAllByStudyEvent(event); for (int k = 0; k < eventCRFs.size(); k++) { EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k); if (BooleanUtils.isTrue(eventCRF.getRemoved()) || BooleanUtils.isTrue(eventCRF.getArchived())) { return false; } ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId()); for (int a = 0; a < itemDatas.size(); a++) { ItemDataBean item = (ItemDataBean) itemDatas.get(a); if (!(item.getStatus().equals(Status.UNAVAILABLE) || item.getStatus().equals(Status.DELETED))) { return false; } } } } return true; }
Source:
<code>@Override protected void handleException(Throwable t) { super.handleException(t); server.abort("Unrecoverable exception while closing " + this.regionInfo.getRegionNameAsString(), t); <START> } <END></code><technical_language>new *Handler code, clear handle exceptions locally vs. handle this handleException method. I guess hooks for operating confines of a Runnable a thread pool somewhere</technical_language>

Target:
@Override protected void handleException(Throwable t) { server.abort("Unrecoverable exception while closing " + this.regionInfo.getRegionNameAsString(), t); }
Source:
<code>public void judgmentReindexingJob_ONLY_SC_JUDGMENTS() throws Exception { JobParameters jobParameters = new JobParameters(ImmutableMap.of("sourceCode", new JobParameter(SourceCode.SUPREME_COURT.name()))); JobExecution jobExecution = jobLauncher.run(judgmentReindexingJob, jobParameters); JobExecutionAssertUtils.assertJobExecution(jobExecution, 0, SUPREME_COURT_JUDGMENTS_COUNT); solrJudgmentsServer.commit(); <START> assertAllMarkedAsIndexed(); <END> assertAllInIndex(SUPREME_COURT_JUDGMENTS_COUNT); }</code><technical_language>given/ execute/ assert</technical_language>

Target:
public void judgmentReindexingJob_ONLY_SC_JUDGMENTS() throws Exception { JobParameters jobParameters = new JobParameters(ImmutableMap.of("sourceCode", new JobParameter(SourceCode.SUPREME_COURT.name()))); JobExecution jobExecution = jobLauncher.run(judgmentReindexingJob, jobParameters); solrJudgmentsServer.commit(); JobExecutionAssertUtils.assertJobExecution(jobExecution, 0, SUPREME_COURT_JUDGMENTS_COUNT); assertAllMarkedAsIndexed(); assertAllInIndex(SUPREME_COURT_JUDGMENTS_COUNT); assertAllInIndexIsOfType(SUPREME_COURT_JUDGMENTS_COUNT, CourtType.SUPREME); }
Source:
<code>private void store() throws IOException { byte[] serialized = state.toCbor().serialize(); System.out.println("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, <START> StandardOpenOption.CREATE); <END> }</code><technical_language>do this atomically</technical_language>

Target:
private synchronized void store() throws IOException { byte[] serialized = state.toCbor().serialize(); System.out.println("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, StandardOpenOption.CREATE); }
Source:
<code>public static URL getResource(String name) { <START> final ClassLoader loader = Thread.currentThread().getContextClassLoader(); <END> String callerName = Thread.currentThread().getStackTrace()[2].getClassName(); final String relativePath = callerName.replace('.', '/').concat(".class"); final String fullPath = loader.getResource(relativePath).getPath(); final String basePath = fullPath.substring(0, fullPath.indexOf(relativePath)); try { Enumeration<URL> resources = loader.getResources(name); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (resource.getPath().startsWith(basePath)) { return resource; } } } catch (IOException e) { return null; } return loader.getResource(name); }</code><technical_language>remove final keywords</technical_language>

Target:
public static URL getResource(String name) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String callerName = Thread.currentThread().getStackTrace()[2].getClassName(); String relativePath = callerName.replace('.', '/').concat(".class"); String fullPath = loader.getResource(relativePath).getPath(); String basePath = fullPath.substring(0, fullPath.indexOf(relativePath)); try { Enumeration<URL> resources = loader.getResources(name); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (resource.getPath().startsWith(basePath)) { return resource; } } } catch (IOException e) { return null; } return loader.getResource(name); }
Source:
<code>public MutationBuilder put(Column col, Bytes value) { <START> Flutation.put(null, mutation, col, ColumnConstants.DATA_PREFIX | 0, value.toArray()); <END> Flutation.put(null, mutation, col, ColumnConstants.WRITE_PREFIX | 1, WriteValue.encode(0, false, false)); return this; }</code><technical_language>creating a separate put method Environment parameter avoid null</technical_language>

Target:
public MutationBuilder put(Column col, Bytes value) { Flutation.put(mutation, col, ColumnConstants.DATA_PREFIX | 0, value.toArray()); Flutation.put(mutation, col, ColumnConstants.WRITE_PREFIX | 1, WriteValue.encode(0, false, false)); return this; }
Source:
<code>public QfdHelper(Connector connector, String indexTable, String shardTable, StoreConfig config, ShardBuilder<T> shardBuilder, TypeRegistry<String> typeRegistry, KeyValueIndex<T> keyValueIndex) throws TableExistsException, AccumuloSecurityException, AccumuloException, TableNotFoundException { <START> this(connector, indexTable, shardTable, config, shardBuilder, typeRegistry, keyValueIndex, new SimpleLexiMetadataSerdeFactory()); <END> }</code><technical_language>serializer lexi encoding default here? Simple type encoders faster potentially smaller</technical_language>

Target:
public QfdHelper(Connector connector, String indexTable, String shardTable, StoreConfig config, ShardBuilder<T> shardBuilder, TypeRegistry<String> typeRegistry, KeyValueIndex<T> keyValueIndex) throws TableExistsException, AccumuloSecurityException, AccumuloException, TableNotFoundException { this(connector, indexTable, shardTable, config, shardBuilder, typeRegistry, keyValueIndex, new SimpleMetadataSerdeFactory()); }
Source:
<code><START> public static Map<String, String> splitAndFilterEmptyMap(String s, String separator) { <END> return Splitter.on(separator) .omitEmptyStrings() .trimResults() .withKeyValueSeparator("=") .split(s); }</code><technical_language>This public - want folks plugin calling this</technical_language>

Target:
private static Map<String, String> splitAndFilterEmptyMap(String s, String separator) { Map<String, String> result = new LinkedHashMap<>(); for (String o : Splitter.on(separator).omitEmptyStrings().split(s)) { String[] parts = o.trim().split("=", 2); if (parts.length == 2) result.put(parts[0].trim(), parts[1].trim()); } return result; }
Source:
<code>public synchronized void processFoxml() throws XMLStreamException, IOException { if (getResult() == null) { final ApplicationContext context = new ClassPathXmlApplicationContext("spring/exported-foxml.xml"); this.result = (DummyHandler) context.getBean("dummyHandler"); <START> this.fetcher = (DummyURLFetcher) context.getBean("dummyFetcher"); <END> final Migrator m = (Migrator) context.getBean("migrator"); m.run(); ((ConfigurableApplicationContext) context).close(); } }</code><technical_language>Spring test framework injecting this stuff annotation</technical_language>

Target:
public synchronized void processFoxml() throws XMLStreamException, IOException { if (getResult() == null) { final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/exported-foxml.xml"); this.result = (DummyHandler) context.getBean("dummyHandler"); this.fetcher = (DummyURLFetcher) context.getBean("dummyFetcher"); final Migrator m = (Migrator) context.getBean("migrator"); m.run(); context.close(); } }
Source:
<code>public String createToken(final String to) { try { val token = UUID.randomUUID().toString(); val claims = new JwtClaims(); claims.setJwtId(token); claims.setIssuer(issuer); claims.setAudience(issuer); claims.setExpirationTimeMinutesInTheFuture(properties.getReset().getExpirationMinutes()); claims.setIssuedAtToNow(); val holder = ClientInfoHolder.getClientInfo(); if (holder != null) { <START> if (properties.getReset().isCheckServerIpAddress()) { claims.setStringClaim("origin", holder.getServerIpAddress()); } if (properties.getReset().isCheckClientIpAddress()) { claims.setStringClaim("client", holder.getClientIpAddress()); } <END> } claims.setSubject(to); LOGGER.debug("Creating password management token for [{}]", to); val json = claims.toJson(); LOGGER.debug("Encoding the generated JSON token..."); return this.cipherExecutor.encode(json); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }</code><technical_language>Extract properties.getRest() a variable</technical_language>

Target:
public String createToken(final String to) { try { val token = UUID.randomUUID().toString(); val claims = new JwtClaims(); val resetProperties = properties.getReset(); claims.setJwtId(token); claims.setIssuer(issuer); claims.setAudience(issuer); claims.setExpirationTimeMinutesInTheFuture(resetProperties.getExpirationMinutes()); claims.setIssuedAtToNow(); val holder = ClientInfoHolder.getClientInfo(); if (holder != null) { if (resetProperties.isIncludeServerIpAddress()) { claims.setStringClaim("origin", holder.getServerIpAddress()); } if (resetProperties.isIncludeClientIpAddress()) { claims.setStringClaim("client", holder.getClientIpAddress()); } } claims.setSubject(to); LOGGER.debug("Creating password management token for [{}]", to); val json = claims.toJson(); LOGGER.debug("Encoding the generated JSON token..."); return this.cipherExecutor.encode(json); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
Source:
<code>public void run() { VanillaSelectionKeySet selectionKeys = null; try { socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setSoTimeout(0); socketChannel.socket().setSoLinger(false, 0); if (builder.receiveBufferSize() > 0) { socketChannel.socket().setReceiveBufferSize(builder.receiveBufferSize()); } if (builder.sendBufferSize() > 0) { socketChannel.socket().setSendBufferSize(builder.sendBufferSize()); <START> } <END> final VanillaSelector selector = new VanillaSelector() .open() .register(socketChannel, SelectionKey.OP_READ, new Attached()); tailer = builder.chronicle().createTailer(); appender = builder.chronicle().createAppender(); sourceTcpHandler.setTailer(tailer); sourceTcpHandler.setAppender(appender); selectionKeys = selector.vanillaSelectionKeys(); if (selectionKeys != null) { vanillaNioLoop(selector, selectionKeys); } else { nioLoop(selector); } } catch (EOFException e) { if (running.get()) { logger.info("Connection died", socketChannel); } } catch (Exception e) { if (running.get()) { String msg = e.getMessage(); if (msg != null && (msg.contains("reset by peer") || msg.contains("Broken pipe") || msg.contains("was aborted by"))) { logger.info("Connection closed from the other end: ", socketChannel, e.getMessage()); } else { logger.info("Connection died", socketChannel, e); } } } finally { if (selectionKeys != null) { selectionKeys.clear(); } } try { close(); } catch (IOException e) { logger.warn("", e); } }</code><technical_language>SocketChannel is configured in SourceTcp/SinkTcp TcpEventHandler (i.e. send buffer size, etc) , a single a duplicated place socket is configured</technical_language>

Target:
public void run() { sessionActive = true; VanillaSelectionKeySet selectionKeys = null; try { final VanillaSelector selector = new VanillaSelector() .open() .register(socketChannel, SelectionKey.OP_READ, new Attached()); tailer = builder.chronicle().createTailer(); appender = builder.chronicle().createAppender(); sourceTcpHandler.setTailer(tailer); sourceTcpHandler.setAppender(appender); selectionKeys = selector.vanillaSelectionKeys(); if (selectionKeys != null) { vanillaNioLoop(selector, selectionKeys); } else { nioLoop(selector); } } catch (InvalidEventHandlerException e) { if (running.get()) { logger.info("Connection died", socketChannel); } } catch (Exception e) { if (running.get()) { logger.info("Connection died", socketChannel, e); } } finally { if (selectionKeys != null) { selectionKeys.clear(); } } try { close(); } catch (IOException e) { logger.warn("", e); } }
Source:
<code>public static Object eval(final String expression) { ExpressionCompiler compiler = new ExpressionCompiler(getRevisedExpression(expression), WID_PARSER_CONTEXT); if(KiePolicyHelper.isPolicyEnabled()) { return AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return MVEL.executeExpression(compiler.compile(), new HashMap()); } }, KiePolicyHelper.getAccessContext()); } return MVEL.executeExpression(compiler.compile(), <START> new HashMap()); <END> }</code><technical_language>this in else statement right I executed in case security manager is enabled</technical_language>

Target:
public static Object eval(final String expression) { ExpressionCompiler compiler = new ExpressionCompiler(getRevisedExpression(expression), WID_PARSER_CONTEXT); if(KiePolicyHelper.isPolicyEnabled()) { return AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return MVEL.executeExpression(compiler.compile(), new HashMap()); } }, KiePolicyHelper.getAccessContext()); } else { return MVEL.executeExpression(compiler.compile(), new HashMap()); } }
Source:
<code>public int getFixedSize() { <START> return SIZE_OF_LONG * 2 + 1; <END> }</code><technical_language>Long.BYTES</technical_language>

Target:
public int getFixedSize() { return Long.BYTES * 2 + 1; }
Source:
<code>public boolean matchingValues(Object object1, Object object2) { final boolean equal; if (object1 == object2) { equal = true; } else if (object1 == null) { equal = "".equals(object2); } else if (object2 == null) { equal = "".equals(object1); } else { MatchSpec currentEObjectMatch = eObjectMatch; if (currentEObjectMatch != null && currentEObjectMatch.matches(object1)) { equal = currentEObjectMatch.matches(object2); } else if (object1 instanceof EObject) { if (object2 instanceof EObject) { equal = matchingEObjects((EObject)object1, (EObject)object2); } else { equal = false; } } else if (object1 instanceof String || object1 instanceof Integer || object1 instanceof Boolean) { equal = object1.equals(object2); } else if (object1.getClass().isArray() && object2.getClass().isArray()) { equal = matchingArrays(object1, object2); } else if (object1 instanceof FeatureMap.Entry && object2 instanceof FeatureMap.Entry) { FeatureMap.Entry featureMapEntry1 = (FeatureMap.Entry)object1; EStructuralFeature key1 = featureMapEntry1.getEStructuralFeature(); FeatureMap.Entry featureMapEntry2 = (FeatureMap.Entry)object2; EStructuralFeature key2 = featureMapEntry2.getEStructuralFeature(); <START> if (key1 == key2) { <END> Object value1 = featureMapEntry1.getValue(); Object value2 = featureMapEntry2.getValue(); equal = matchingValues(value1, value2); } else { equal = false; } } else { equal = object1.equals(object2); } } return equal; }</code><technical_language>This remain a .equals test. Feature maps some peculiar handling I remember "==" a problem</technical_language>

Target:
public boolean matchingValues(Object object1, Object object2) { final boolean equal; if (object1 == object2) { equal = true; } else if (object1 == null) { equal = "".equals(object2); } else if (object2 == null) { equal = "".equals(object1); } else { MatchSpec currentEObjectMatch = eObjectMatch; if (currentEObjectMatch != null && currentEObjectMatch.matches(object1)) { equal = currentEObjectMatch.matches(object2); } else if (object1 instanceof EObject) { if (object2 instanceof EObject) { equal = matchingEObjects((EObject)object1, (EObject)object2); } else { equal = false; } } else if (object1 instanceof String || object1 instanceof Integer || object1 instanceof Boolean) { equal = object1.equals(object2); } else if (object1.getClass().isArray() && object2.getClass().isArray()) { equal = matchingArrays(object1, object2); } else if (object1 instanceof FeatureMap.Entry && object2 instanceof FeatureMap.Entry) { FeatureMap.Entry featureMapEntry1 = (FeatureMap.Entry)object1; EStructuralFeature key1 = featureMapEntry1.getEStructuralFeature(); FeatureMap.Entry featureMapEntry2 = (FeatureMap.Entry)object2; EStructuralFeature key2 = featureMapEntry2.getEStructuralFeature(); if (key1.equals(key2)) { Object value1 = featureMapEntry1.getValue(); Object value2 = featureMapEntry2.getValue(); equal = matchingValues(value1, value2); } else { equal = false; } } else { equal = object1.equals(object2); } } return equal; }
Source:
<code>public static void setUpOnce() { validator = new WikibaseDataModelValidator(); openTestDatasetStream(); try { parsedDataset = Rio.parse(testDataset, "http://test.dataset", RDFFormat.TURTLE); } catch (IOException ioe) { System.err.println("I/O trouble while reading from [" + TEST_DATASET_FILE_NAME + "]. This shouldn't happen here. Please re-run."); <START> System.exit(1); <END> } catch (RDFParseException rpe) { System.err.println("Parse error: " + rpe.getMessage() + " This shouldn't happen here. Please re-run."); } }</code><technical_language>tests do exit()</technical_language>

Target:
public static void setUpOnce() throws IOException, RDFParseException { validator = new WikibaseDataModelValidator(); goodDataset = openTestDatasetStream(GOOD_DATASET_FILE_NAME); goodParsedDataset = Rio.parse(goodDataset, BASE_URI, RDF_FORMAT); badDataset = openTestDatasetStream(BAD_DATASET_FILE_NAME); badParsedDataset = Rio.parse(badDataset, BASE_URI, RDF_FORMAT); }
Source:
<code>public static void writeSegmentedCopyRatioPlot(final String sample_name, final String tnFile, final String preTnFile, final String segFile, final String outputDir, final Boolean log) { <START> String logArg = "FALSE"; <END> if(log){ logArg = "TRUE"; } final RScriptExecutor executor = new RScriptExecutor(); executor.addScript(new Resource(R_SCRIPT, CopyRatioSegmentedPlotter.class)); executor.addArgs("--args", "--sample_name="+sample_name, "--targets_file="+tnFile, "--pre_tn_file="+preTnFile, "--seg_file="+segFile, "--output_dir="+outputDir, "--log2_input="+logArg); executor.exec(); }</code><technical_language>String logArg = log ? "TRUE" : "FALSE" feels more Pythonic me</technical_language>

Target:
public static void writeSegmentedCopyRatioPlot(final String sample_name, final String tnFile, final String preTnFile, final String segFile, final String outputDir, final Boolean log) { String logArg = log ? "TRUE" : "FALSE"; final RScriptExecutor executor = new RScriptExecutor(); executor.addScript(new Resource(R_SCRIPT, CopyRatioSegmentedPlotter.class)); executor.addArgs("--args", "--sample_name="+sample_name, "--targets_file="+tnFile, "--pre_tn_file="+preTnFile, "--seg_file="+segFile, "--output_dir="+outputDir, "--log2_input="+logArg); executor.exec(); }
Source:
<code>public static String getCurrentBranch(IProject project) throws CoreException { if (project == null) { return null; } <START> Repository repo = EGitUtils.getRepository(project); <END> if (repo == null) { return null; } String currentBranch = EGitUtils.getCurrentBranch(repo); repo.close(); return currentBranch; }</code><technical_language>I try-with-resources here, fix Sonar complaining it. I smth like: java try (Repository repo = EGitUtils.getRepository(project)) { if (repo == null) { return null; } return EGitUtils.getCurrentBranch(repo); }</technical_language>

Target:
public static String getCurrentBranch(IProject project) throws CoreException { if (project == null) { return null; } try (Repository repo = EGitUtils.getRepository(project)) { if (repo == null) { return null; } return EGitUtils.getCurrentBranch(repo); } }
Source:
<code>private Pair<ArrayList<IndexEntry>, Offset> addPutEntries(Offset prevEntryEndOffset, IndexSegment indexSegment, int count, long size, long expiresAtMs) throws IOException, StoreException { ArrayList<IndexEntry> indexEntrys = new ArrayList<>(); for (int i = 0; i < count; i++) { state.appendToLog(size); FileSpan fileSpan = state.log.getFileSpanForMessage(prevEntryEndOffset, size); IndexEntry entry; if (indexSegment != null) { entry = new IndexEntry(state.getUniqueId(), IndexValueTest.getIndexValue(size, prevEntryEndOffset, expiresAtMs, state.time.seconds(), IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, <START> PersistentIndex.VERSION_0)); <END> indexSegment.addEntry(entry, fileSpan.getEndOffset()); } else { entry = new IndexEntry(state.getUniqueId(), IndexValueTest.getIndexValue(size, prevEntryEndOffset, expiresAtMs, state.time.seconds(), IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, PersistentIndex.CURRENT_VERSION)); state.index.addToIndex(entry, fileSpan); } indexEntrys.add(entry); prevEntryEndOffset = fileSpan.getEndOffset(); } return new Pair<>(indexEntrys, prevEntryEndOffset); }</code><technical_language>do indexSegment.getVersion()? (if function)</technical_language>

Target:
private List<IndexEntry> addPutEntries(Offset prevEntryEndOffset, IndexSegment indexSegment, int count, long size, long expiresAtMs) throws IOException, StoreException { List<IndexEntry> indexEntries = new ArrayList<>(); for (int i = 0; i < count; i++) { state.appendToLog(size); FileSpan fileSpan = state.log.getFileSpanForMessage(prevEntryEndOffset, size); IndexEntry entry; if (indexSegment != null) { entry = new IndexEntry(state.getUniqueId(), IndexValueTest.getIndexValue(size, prevEntryEndOffset, expiresAtMs, state.time.milliseconds(), IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, IndexValue.SERVICE_CONTAINER_ID_DEFAULT_VALUE, indexSegment.getVersion())); indexSegment.addEntry(entry, fileSpan.getEndOffset()); } else { entry = new IndexEntry(state.getUniqueId(), new IndexValue(size, prevEntryEndOffset, (byte) 0, expiresAtMs, state.time.milliseconds())); state.index.addToIndex(entry, fileSpan); } indexEntries.add(entry); prevEntryEndOffset = fileSpan.getEndOffset(); } return indexEntries; }
Source:
<code>private static int getPoolSize(Configuration config) { int poolSize = config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1); if (poolSize <= 0) { <START> LOG.warn("{} must be positive.", HConstants.HBASE_CLIENT_IPC_POOL_SIZE); <END> return 1; } else { return poolSize; } }</code><technical_language>include in message ignoring passed config 1</technical_language>

Target:
private static int getPoolSize(Configuration config) { int poolSize = config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1); if (poolSize <= 0) { LOG.warn("{} must be positive. Using default value: 1", HConstants.HBASE_CLIENT_IPC_POOL_SIZE); return 1; } else { return poolSize; } }
Source:
<code>public V get(K key) { V cached; if ((cached = this.cache.get(key)) != null) { if (this.size < this.maxSize / 2) { return cached; } try { this.readLock.lock(); this.queue.add(key); this.queue.remove(key); return cached; } finally { this.readLock.unlock(); } } this.writeLock.lock(); try { if ((cached = this.cache.get(key)) != null) { this.queue.add(key); this.queue.remove(key); return cached; } int cacheSize = this.size; if (cacheSize == this.maxSize) { K leastUsed = this.queue.poll(); if (leastUsed != null) { <START> this.cache.remove(leastUsed); <END> cacheSize--; } } V value = this.generator.apply(key); this.queue.add(key); this.cache.put(key, value); this.size = cacheSize + 1; return value; } finally { this.writeLock.unlock(); } }</code><technical_language>Recommended >= instead of ==, if is a problem write lock, LIMIT Cache</technical_language>

Target:
public V get(K key) { V cached; if ((cached = this.cache.get(key)) != null) { if (this.size < this.maxSize / 2) { return cached; } try { this.readLock.lock(); this.queue.add(key); this.queue.remove(key); return cached; } finally { this.readLock.unlock(); } } this.writeLock.lock(); try { if ((cached = this.cache.get(key)) != null) { this.queue.add(key); this.queue.remove(key); return cached; } V value = this.generator.apply(key); int cacheSize = this.size; if (cacheSize == this.maxSize) { K leastUsed = this.queue.poll(); if (leastUsed != null) { this.cache.remove(leastUsed); cacheSize--; } } this.queue.add(key); this.cache.put(key, value); this.size = cacheSize + 1; return value; } finally { this.writeLock.unlock(); } }