auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>MetricsInterceptor( Provider<Registry> registry, OkHttpMetricsInterceptorProperties okHttpMetricsInterceptorProperties) { this.registry = registry; this.okHttpMetricsInterceptorProperties = okHttpMetricsInterceptorProperties; <START> this.headerCheckPattern = okHttpMetricsInterceptorProperties.getHeaderCheckRegExPattern(); <END> this.log = LoggerFactory.getLogger(getClass()); }</code><technical_language>Small nitpick: This tripped up. Instead of creating a member variable headerCheckPattern assigning okHttpMetricsInterceptorProperties I fine call okHttpMetricsInterceptorProperties.getHeaderCheckRegExPattern() below</technical_language>

Target:
MetricsInterceptor( Provider<Registry> registry, OkHttpMetricsInterceptorProperties okHttpMetricsInterceptorProperties) { this.registry = registry; this.okHttpMetricsInterceptorProperties = okHttpMetricsInterceptorProperties; this.log = LoggerFactory.getLogger(getClass()); }
Source:
<code>public boolean exists(K key) throws GoraException { try { <START> ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); <END> KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(table); scannerBuilder.limit(1); scannerBuilder.setProjectedColumnIndexes(new ArrayList<>()); scannerBuilder.addPredicate(KuduClientUtils.createEqualPredicate(column, key)); KuduScanner build = scannerBuilder.build(); RowResult waitFirstResult = KuduClientUtils.waitFirstResult(build); build.close(); return waitFirstResult != null; } catch (Exception e) { throw new GoraException(e); } }</code><technical_language>This code ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(table); scannerBuilder.limit(1); scannerBuilder.setProjectedColumnNames(dbFields); scannerBuilder.addPredicate(KuduClientUtils.createEqualPredicate(column, key)); KuduScanner build = scannerBuilder.build(); is duplicated exists(K key), get(K key, String[] fields) other places. move this code a common place/method</technical_language>

Target:
public boolean exists(K key) throws GoraException { try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); ArrayList<KuduPredicate> equalPredicate = new ArrayList<>(); equalPredicate.add(KuduClientUtils.createEqualPredicate(column, key)); KuduScanner build = createScanner(equalPredicate, new ArrayList<>(), 1); RowResult waitFirstResult = KuduClientUtils.waitFirstResult(build); build.close(); return waitFirstResult != null; } catch (Exception e) { throw new GoraException(e); } }
Source:
<code>private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; <START> } <END> } }</code><technical_language>default: throw new IllegalArgumentException..</technical_language>

Target:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: throw new IllegalArgumentException(); } } }
Source:
<code>private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if <START> (borderedStyle.getBorderSize() == null || borderSize <END> == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }</code><technical_language>Remove this (and check resulting code is consistent DiagramBorderNodeEditPartOperation)</technical_language>

Target:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderSize == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }
Source:
<code>public static void respond(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (CORS_ENABLED) { res.headers().add("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); } if (res.content() != null) { HttpUtil.setContentLength(res, res.content().readableBytes()); } boolean isKeepAlive = HttpUtil.isKeepAlive(req); if (isKeepAlive) { res.headers().add(CONNECTION, KEEP_ALIVE); } ctx.channel().write(res); if (req == null || !isKeepAlive) { <START> log.debug("Closing channel. isKeepAlive:" + isKeepAlive); <END> ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }</code><technical_language>print channel info too</technical_language>

Target:
public static void respond(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (CORS_ENABLED) { res.headers().add("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); } if (res.content() != null) { setContentLength(res, res.content().readableBytes()); } boolean isKeepAlive = isKeepAlive(req); if (isKeepAlive) { res.headers().add(CONNECTION, KEEP_ALIVE); } ctx.channel().write(res); if (req == null || !isKeepAlive) { log.debug("Closing channel. isKeepAlive:" + isKeepAlive + " on channel: " + ctx.channel().toString()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
Source:
<code>public boolean isTaskHandled(Task task) { boolean handled = false; if(this.handledTasksId == null) { <START> this.handledTasksId = new ArrayList<>(); <END> } for (Long handledTaskId : this.handledTasksId) { if (handledTaskId.equals(task.getId())) { handled = true; break; } } return handled; }</code><technical_language>remove this</technical_language>

Target:
private boolean isTaskHandled(Task task) { boolean handled = false; if (this.handledTasksId.contains(task.getId())) { handled = true; } return handled; }
Source:
<code>public void getTableMetaDataViewThrowsExceptionWhenGetConnectionHasSqlException() throws SQLException { <START> when(dataSource.getConnection()).thenThrow(SQLException.class); <END> Throwable throwable = catchThrowable(() -> service.getTableMetaDataView(mapping)); assertThat(throwable).isInstanceOf(JdbcConnectorException.class).hasMessageContaining( "Exception thrown while connecting to datasource \"dataSource\": null"); verify(connection, never()).close(); }</code><technical_language>Minor pick. I recommend some error message for SQLException, e.g. String reason = "connection failed"; when(dataSource.getConnection()).thenThrow(new SQLException(reason)); error message in next lines Exception thrown while connecting datasource \"dataSource\": connection failed, instead of Exception thrown while connecting datasource \"dataSource\": null</technical_language>

Target:
public void getTableMetaDataViewThrowsExceptionWhenGetConnectionHasSqlException() throws SQLException { String reason = "connection failed"; when(dataSource.getConnection()).thenThrow(new SQLException(reason)); Throwable throwable = catchThrowable(() -> service.getTableMetaDataView(mapping)); assertThat(throwable).isInstanceOf(JdbcConnectorException.class).hasMessageContaining( String.format("Exception thrown while connecting to datasource \"dataSource\": %s", reason)); verify(connection, never()).close(); }
Source:
<code>private void doInitialize(RequestMonitor requestMonitor) { fSessionInitializationComplete = false; fCommandControl = getServicesTracker().getService(IGDBControl.class); fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory(); fBackend = getServicesTracker().getService(IGDBBackend.class); fFetchCPUInfoCache = new CommandCache(getSession(), new CPUInfoManager()); fFetchCPUInfoCache.setContextAvailable(fCommandControl.getContext(), true); fLoadInfoRequestCache = new ArrayList<LoadInfoRequest>(); getSession().addServiceEventListener(this, null); <START> register(new String[] { IGDBHardwareAndOS.class.getName(), <END> GDBHardwareAndOS.class.getName() }, new Hashtable<String, String>()); requestMonitor.done(); }</code><technical_language>register name IGDBHardwareAndOS2</technical_language>

Target:
private void doInitialize(RequestMonitor requestMonitor) { fSessionInitializationComplete = false; fCommandControl = getServicesTracker().getService(IGDBControl.class); fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory(); fBackend = getServicesTracker().getService(IGDBBackend.class); fFetchCPUInfoCache = new CommandCache(getSession(), new CPUInfoManager()); fFetchCPUInfoCache.setContextAvailable(fCommandControl.getContext(), true); fLoadInfoRequestCache = new HashMap<IDMContext, DataRequestMonitor<ILoadInfo>>(); getSession().addServiceEventListener(this, null); register(new String[] { IGDBHardwareAndOS.class.getName(), IGDBHardwareAndOS2.class.getName(), GDBHardwareAndOS.class.getName() }, new Hashtable<String, String>()); requestMonitor.done(); }
Source:
<code>public CategoryPage openCategoryPage(String name) { <START> WebElement link = categoryList.findElement(By.cssSelector("a[title=\"" + name + "\"]")); <END> PageObjectLogging.logInfo("Open category page named: " + name); wait.forElementClickable(link); link.click(); loading.handleAsyncPageReload(); Assertion.assertTrue(driver.getCurrentUrl().contains("/wiki/Category:"), "Url is different than /wiki/Category:"); PageObjectLogging.logInfo("You were redirected to /wiki/Category:"); return new CategoryPage(); }</code><technical_language>String.format - cleaner string concatenation worry "</technical_language>

Target:
public CategoryPage openCategoryPage(String name) { WebElement link = categoryList.findElement( By.cssSelector(String.format("a[title=\"%s\"]", name)) ); PageObjectLogging.logInfo(String.format("Open category page named: \"%s\".", name)); wait.forElementClickable(link); link.click(); loading.handleAsyncPageReload(); Assertion.assertTrue(driver.getCurrentUrl().contains("/wiki/Category:"), "Url is different than /wiki/Category:"); PageObjectLogging.logInfo("You were redirected to /wiki/Category:"); return new CategoryPage(); }
Source:
<code>public PatientData<Map<String, String>> readJSON(JSONObject json) { Object testGeneJson = json.get(this.getJsonPropertyName()); if (testGeneJson == null) { return null; } try { JSONArray genesJson = json.getJSONArray(this.getJsonPropertyName()); List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>(); for (Object geneJsonUncast : genesJson) { JSONObject geneJson = JSONObject.fromObject(geneJsonUncast); Map<String, String> singleGene = new LinkedHashMap<String, String>(); for (String property : getProperties()) { if (geneJson.has(property)) { String field = geneJson.getString(property); if (field != null) { singleGene.put(property, field); } } } <START> allGenes.add(singleGene); <END> } if (allGenes.isEmpty()) { return null; } else { return new IndexedPatientData<Map<String, String>>(getName(), allGenes); } } catch (Exception e) { this.logger.error("Could not load genes from JSON", e.getMessage()); } return null; }</code><technical_language>Is a possibility singleGene is empty map this point</technical_language>

Target:
public PatientData<Map<String, String>> readJSON(JSONObject json) { Object testGeneJson = json.get(this.getJsonPropertyName()); if (testGeneJson == null) { return null; } try { JSONArray genesJson = json.getJSONArray(this.getJsonPropertyName()); List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>(); for (Object geneJsonUncast : genesJson) { JSONObject geneJson = JSONObject.fromObject(geneJsonUncast); Map<String, String> singleGene = new LinkedHashMap<String, String>(); for (String property : this.getProperties()) { if (geneJson.has(property)) { String field = geneJson.getString(property); if (field != null) { singleGene.put(property, field); } } } if (!singleGene.isEmpty()) { allGenes.add(singleGene); } } if (allGenes.isEmpty()) { return null; } else { return new IndexedPatientData<Map<String, String>>(getName(), allGenes); } } catch (Exception e) { this.logger.error("Could not load genes from JSON", e.getMessage()); } return null; }
Source:
<code>public boolean delete(ResourcePath path) { final SearchResults results = searchFor(path, 0, true); if (results.isEmpty()) { return false; } for (final Result result : results) { for(String metricName: result.getMetrics()) { Metric metric = Metric.builder() .tag(CommonTagNames.resourceId, result.getResource().getId()) .tag(CommonTagNames.name, metricName) <START> .tag(Metric.MandatoryTag.mtype.name(), Metric.Mtype.gauge.name()) END> .tag(Metric.MandatoryTag.unit.name(), CommonTagValues.unknown) .build(); try { storage.delete(metric); } catch (StorageException e) { LOG.error("Could not delete {}, will ignore problem and continue ", metric, e); } } } return true; }</code><technical_language>current model, type write - read delete</technical_language>

Target:
public boolean delete(ResourcePath path) { final SearchResults results = searchFor(path, 0, true); if (results.isEmpty()) { return false; } for (final Result result : results) { for(String metricName: result.getMetrics()) { Metric metric = ImmutableMetric.builder() .intrinsicTag(CommonTagNames.resourceId, result.getResource().getId()) .intrinsicTag(CommonTagNames.name, metricName) .build(); try { storageManager.get().delete(metric); } catch (StorageException e) { LOG.error("Could not delete {}, will ignore problem and continue ", metric, e); } } } return true; }
Source:
<code><START> private static File getFileFromClassLoader4Luna(String filename, ClassLoader classLoader) <END> throws AssertionFailedError { String AssertionFailedErrorMessage = "no file found " + filename; try { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); if (classpathManager != null) { Object generation = MethodUtils.invokeExactMethod(classpathManager, "getGeneration", null); if (generation != null) { Object bundleFile = MethodUtils.invokeExactMethod(generation, "getBundleFile", null); if (bundleFile != null) { File file = (File) MethodUtils.invokeExactMethod(bundleFile, "getFile", new Object[] { filename, true }, new Class[] { String.class, boolean.class }); if (file != null) { return file; } } } } } catch (NoSuchMethodException e) { AssertionFailedErrorMessage = "got NoSuchMethodException " + e.getMessage(); } catch (IllegalAccessException e) { AssertionFailedErrorMessage = "got IllegalAccessException " + e.getMessage(); } catch (InvocationTargetException e) { AssertionFailedErrorMessage = "got InvocationTargetException " + e.getMessage(); } throw new AssertionFailedError(AssertionFailedErrorMessage); }</code><technical_language>getFileFromClassLoader* methods pretty same. Is a chance create a single method, accepting params for Luna cases</technical_language>

Target:
private static File getFileFromClassLoader4Luna(String filename, ClassLoader classLoader) throws Exception { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); Object generation = MethodUtils.invokeExactMethod(classpathManager, "getGeneration", null); Object bundleFile = MethodUtils.invokeExactMethod(generation, "getBundleFile", null); File file = (File) MethodUtils.invokeExactMethod(bundleFile, "getFile", new Object[] { filename, true }, new Class[] { String.class, boolean.class }); return file; }
Source:
<code>public SolenoidSet(SolenoidSubsystem system, SolenoidState state) { <START> this(system, state, () -> { return false; }); } <END></code><technical_language>replace this(system, state)</technical_language>

Target:
public SolenoidSet(SolenoidSubsystem system, SolenoidState state) { this("SolenoidSet", system, state); }
Source:
<code>public void cloneSnapshot(String snapshotName, TableName tableName) throws IOException, TableExistsException, RestoreSnapshotException { BigtableInstanceName instanceName = options.getInstanceName(); BigtableClusterName clusterName = this.connection.getSession().getClusterName(); String btSnapshotName = clusterName.toSnapshotName(snapshotName); <START> bigtableTableAdminClient.createTableFromSnapshot(CreateTableFromSnapshotRequest.newBuilder() <END> .setParent(instanceName.toString()) .setTableId(tableName.getNameAsString()) .setSourceSnapshot(btSnapshotName) .build()); }</code><technical_language>snapshot(), this is a LRO, need poll</technical_language>

Target:
public void cloneSnapshot(String snapshotName, TableName tableName) throws IOException, TableExistsException, RestoreSnapshotException { CreateTableFromSnapshotRequest request = CreateTableFromSnapshotRequest.newBuilder() .setParent(options.getInstanceName().toString()) .setTableId(tableName.getNameAsString()) .setSourceSnapshot(getClusterName().toSnapshotName(snapshotName)) .build(); waitForOperation(bigtableTableAdminClient.createTableFromSnapshot(request)); }
Source:
<code><START> void replace(final int word, final int oldTopicIdx, final int newTopicIdx, final int delta) { <END> if (!changedTopicCounts.contains(word, oldTopicIdx)) { changedTopicCounts.put(word, oldTopicIdx, 0); } changedTopicCounts.put(word, oldTopicIdx, changedTopicCounts.get(word, oldTopicIdx) - delta); if (!changedTopicCounts.contains(word, newTopicIdx)) { changedTopicCounts.put(word, newTopicIdx, 0); } changedTopicCounts.put(word, newTopicIdx, changedTopicCounts.get(word, newTopicIdx) + delta); }</code><technical_language>change this method done for increment method</technical_language>

Target:
void replace(final int word, final int oldTopicIdx, final int newTopicIdx, final int delta) { final Integer countOldTopic = changedTopicCounts.get(word, oldTopicIdx); if (countOldTopic == null) { changedTopicCounts.put(word, oldTopicIdx, -delta); } else { changedTopicCounts.put(word, oldTopicIdx, countOldTopic - delta); } final Integer countNewTopic = changedTopicCounts.get(word, newTopicIdx); if (countNewTopic == null) { changedTopicCounts.put(word, newTopicIdx, delta); } else { changedTopicCounts.put(word, newTopicIdx, countNewTopic + delta); } }
Source:
<code>protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(AppIntroFragment.newInstance("Welcome", "The global OpenMRS community works together to build the world's leading open source enterprise electronic medical record system platform.", R.drawable.openmrs_action_logo, Color.parseColor("#5B57A6"))); addSlide(AppIntroFragment.newInstance("Register Patients", "You can register your new patients to our server", R.drawable.ico_registry, Color.parseColor("#F26522"))); addSlide(AppIntroFragment.newInstance("Find Patients", "You can find and monitor those patients", R.drawable.ico_search, Color.parseColor("#009384"))); <START> addSlide(AppIntroFragment.newInstance("Monitor Visits", "We help you monitor patient's visits too... Exciting ??? Lets get started", R.drawable.ico_visits, Color.parseColor("#F0A815"))); <END> if(!mOpenMRS.getFirstTime()) { startActivity(new Intent(this, DashboardActivity.class)); finish(); } }</code><technical_language>hard-code [these strings](<LINK_0> strings.xml instead</technical_language>

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_welcome),"",getString(R.string.intro_welcome_desc),"", R.drawable.openmrs_logo, Color.parseColor("#ffffff"),Color.parseColor("#000000"),Color.parseColor("#000000"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_register), getString(R.string.intro_register_desc), R.drawable.ico_registry, Color.parseColor("#000000"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_find), getString(R.string.intro_find_desc), R.drawable.ico_search, Color.parseColor("#009384"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_monitor), getString(R.string.intro_monitor_desc), R.drawable.ico_visits, Color.parseColor("#F0A815"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_manage), getString(R.string.intro_manage_desc), R.drawable.ic_provider_big, Color.parseColor("#F26522"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_location), getString(R.string.intro_location_desc), R.drawable.ic_location_big, Color.parseColor("#009384"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_settings), getString(R.string.intro_settings_desc), R.drawable.ic_settings_big, Color.parseColor("#F0A815"))); if(!mOpenMRS.getFirstTime()) { startActivity(new Intent(this, DashboardActivity.class)); finish(); } }
Source:
<code>public void shouldBypassWebsocketRequests() throws Exception{ HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); handler.setRequestingStaticFile(false); vRaptor.doFilter(request, response, chain); assertThat(handler.isDeferProcessingToContainerCalled(), is(false)); <START> } <END></code><technical_language>test fail. I change lines 75 76 test if chain.doFilter called, this: java vRaptor.doFilter(request, response, chain); verify(chain).doFilter(request, response); verify(handler, never()).requestingStaticFile(request); This test ensure chain is called rest of code wont. Methods verify org.mockito. think</technical_language>

Target:
public void shouldBypassWebsocketRequests() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); vRaptor.doFilter(request, response, chain); verify(request).getHeader("Upgrade"); verify(chain).doFilter(request, response); verifyNoMoreInteractions(request, response); }
Source:
<code>private void testButton(JoystickButtonManager manager, int i) { try { manager.getifAvailable(i); assertTrue(false); <START> } catch (Exception e) <END> { } }</code><technical_language>Newline close brace</technical_language>

Target:
private void testButton(JoystickButtonManager manager, int i) { try { manager.getifAvailable(i); fail(); } catch (Exception e) { } }
Source:
<code>protected SortedProperties createUnsafeMapping() throws ProjectBuildingException, IOException, MojoExecutionException { String path = missingFile.getAbsolutePath().substring( getProject().getBasedir().getAbsolutePath().length() + 1 ); if ( isVerbose() ) { <START> LOG.info( "Use missing file path: ", path ); <END> } SortedProperties unsafeMappings = new SortedProperties( getEncoding() ); for ( Object o : reactorProjects ) { MavenProject p = (MavenProject) o; File file = new File( p.getBasedir(), path ); if ( file.exists() ) { SortedProperties tmp = getHelper().loadUnsafeMapping( licenseMap, file, null, projectDependencies ); unsafeMappings.putAll( tmp ); } SortedSet<MavenProject> unsafe = getHelper().getProjectsWithNoLicense( licenseMap ); if ( CollectionUtils.isEmpty( unsafe ) ) { break; } } return unsafeMappings; }</code><technical_language>Add for path</technical_language>

Target:
protected SortedProperties createUnsafeMapping() throws ProjectBuildingException, IOException, MojoExecutionException { String path = missingFile.getAbsolutePath().substring( getProject().getBasedir().getAbsolutePath().length() + 1 ); if ( isVerbose() ) { LOG.info( "Use missing file path: {}", path ); } SortedProperties unsafeMappings = new SortedProperties( getEncoding() ); for ( Object o : reactorProjects ) { MavenProject p = (MavenProject) o; File file = new File( p.getBasedir(), path ); if ( file.exists() ) { SortedProperties tmp = getHelper().loadUnsafeMapping( licenseMap, file, null, projectDependencies ); unsafeMappings.putAll( tmp ); } SortedSet<MavenProject> unsafe = getHelper().getProjectsWithNoLicense( licenseMap ); if ( CollectionUtils.isEmpty( unsafe ) ) { break; } } return unsafeMappings; }
Source:
<code>public void close(long timeoutMS) { try { <START> if (timeoutMS <= 0) { <END> eventHubClient.closeSync(); } else { CompletableFuture<Void> future = eventHubClient.close(); future.get(timeoutMS, TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.error("Closing the event hub client failed ", e); } }</code><technical_language>Define a constant here, instead</technical_language>

Target:
public void close(long timeoutMS) { try { if (timeoutMS == EventHubClientManager.BLOCK_UNTIL_CLOSE) { eventHubClient.closeSync(); } else { CompletableFuture<Void> future = eventHubClient.close(); future.get(timeoutMS, TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.error("Closing the EventHub client failed", e); } }
Source:
<code>protected String validateConsistentTychoVersion(List<MavenProject> projects) throws MavenExecutionException { Map<String, Set<MavenProject>> versionToProjectsMap = new HashMap<String, Set<MavenProject>>(); for (MavenProject project : projects) { for (Plugin plugin : project.getBuild().getPlugins()) { if (TYCHO_GROUPID.equals(plugin.getGroupId()) && TYCHO_PLUGIN_IDS.contains(plugin.getArtifactId())) { String version = plugin.getVersion(); if (version == null) { continue; } log.debug(TYCHO_GROUPID + ":" + plugin.getArtifactId() + ":" + version + " configured in " + project); Set<MavenProject> projectSet = versionToProjectsMap.get(version); if (projectSet == null) { projectSet = new LinkedHashSet<MavenProject>(); versionToProjectsMap.put(version, projectSet); } projectSet.add(project); } } } if (versionToProjectsMap.size() > 1) { List<String> versions = new ArrayList<String>(versionToProjectsMap.keySet()); Collections.sort(versions); log.error("Several versions of tycho plugins are configured " + versions + ":"); for (String version : versions) { log.error(version + ":"); for (MavenProject project : versionToProjectsMap.get(version)) { log.error("\t" + project.toString()); } } throw new MavenExecutionException("All tycho plugins configured in one reactor must use the same version", projects.get(0).getFile()); } if (versionToProjectsMap.size() == 1) { return versionToProjectsMap.keySet().iterator().next(); } <START> return UNKNOWN_VERSION; <END> }</code><technical_language>unknown version happen</technical_language>

Target:
protected void validateConsistentTychoVersion(List<MavenProject> projects) throws MavenExecutionException { Map<String, Set<MavenProject>> versionToProjectsMap = new HashMap<String, Set<MavenProject>>(); for (MavenProject project : projects) { for (Plugin plugin : project.getBuild().getPlugins()) { if (TYCHO_GROUPID.equals(plugin.getGroupId()) && TYCHO_PLUGIN_IDS.contains(plugin.getArtifactId())) { String version = plugin.getVersion(); if (version == null) { continue; } log.debug(TYCHO_GROUPID + ":" + plugin.getArtifactId() + ":" + version + " configured in " + project); Set<MavenProject> projectSet = versionToProjectsMap.get(version); if (projectSet == null) { projectSet = new LinkedHashSet<MavenProject>(); versionToProjectsMap.put(version, projectSet); } projectSet.add(project); } } } if (versionToProjectsMap.size() > 1) { List<String> versions = new ArrayList<String>(versionToProjectsMap.keySet()); Collections.sort(versions); log.error("Several versions of tycho plugins are configured " + versions + ":"); for (String version : versions) { log.error(version + ":"); for (MavenProject project : versionToProjectsMap.get(version)) { log.error("\t" + project.toString()); } } throw new MavenExecutionException("All tycho plugins configured in one reactor must use the same version", projects.get(0).getFile()); } }
Source:
<code>protected PoolTaskRest action(Context context, HttpServletRequest request, Integer id) throws SQLException, IOException, AuthorizeException { PoolTask task = null; try { task = poolTaskService.find(context, id); XmlWorkflowServiceFactory factory = (XmlWorkflowServiceFactory) XmlWorkflowServiceFactory.getInstance(); Workflow workflow = factory.getWorkflowFactory().getWorkflow(task.getWorkflowItem().getCollection()); Step step = workflow.getStep(task.getStepID()); WorkflowActionConfig currentActionConfig = step.getActionConfig(task.getActionID()); workflowService .doState(context, context.getCurrentUser(), request, task.getWorkflowItem().getID(), workflow, currentActionConfig); context.addEvent(new Event(Event.MODIFY, Constants.ITEM, task.getWorkflowItem().getItem().getID(), null, itemService.getIdentifiers(context, task.getWorkflowItem().getItem()))); } catch (WorkflowConfigurationException | MessagingException | WorkflowException e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } return null; }</code><technical_language>Again, more useful error message please</technical_language>

Target:
protected PoolTaskRest action(Context context, HttpServletRequest request, Integer id) throws SQLException, IOException { PoolTask task = null; try { task = poolTaskService.find(context, id); XmlWorkflowServiceFactory factory = (XmlWorkflowServiceFactory) XmlWorkflowServiceFactory.getInstance(); Workflow workflow = factory.getWorkflowFactory().getWorkflow(task.getWorkflowItem().getCollection()); Step step = workflow.getStep(task.getStepID()); WorkflowActionConfig currentActionConfig = step.getActionConfig(task.getActionID()); workflowService .doState(context, context.getCurrentUser(), request, task.getWorkflowItem().getID(), workflow, currentActionConfig); } catch (AuthorizeException e) { throw new RESTAuthorizationException(e); } catch (WorkflowConfigurationException | MessagingException | WorkflowException e) { throw new UnprocessableEntityException(e.getMessage(), e); } return null; }
Source:
<code>public ListenableFuture<?> execute(TruncateTable statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTableName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName); } <START> accessControl.checkCanDropTable(session.getRequiredTransactionId(), session.getIdentity(), tableName); <END> metadata.truncateTable(session, tableHandle.get()); return immediateFuture(null); }</code><technical_language>"can drop table"? spec, operations perform a similar check, I conflate them. add a separate check for "can truncate table"</technical_language>

Target:
public ListenableFuture<?> execute(TruncateTable statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTableName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName); } accessControl.checkCanTruncateTable(session.getRequiredTransactionId(), session.getIdentity(), tableName); metadata.truncateTable(session, tableHandle.get()); return immediateFuture(null); }
Source:
<code>public void testRemoveProject() throws Exception { String baseUrl = "<LINK_0>"; StringBuilder xmlContent = new StringBuilder(); Set<String> <START> results = <END> new HashSet<>(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"foo\" />") .append("<project path=\"bar\" name=\"bar\" />") .append("<remove-project name=\"foo\" />") .append("<project path=\"foo\" name=\"baz\" />") .append("</manifest>"); ManifestParser parser = new ManifestParser(null, null, "master", baseUrl, null, null); parser.read(new ByteArrayInputStream( xmlContent.toString().getBytes(CHARSET))); results.clear(); results.add("bar"); results.add("baz"); for (RepoProject proj : parser.getProjects()) { assertTrue("Unexpected project is included: " + proj.getName(), results.contains(proj.getName())); results.remove(proj.getName()); } assertTrue( "Expected projects are not included", results.isEmpty()); }</code><technical_language>move use</technical_language>

Target:
public void testRemoveProject() throws Exception { StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"foo\" />") .append("<project path=\"bar\" name=\"bar\" />") .append("<remove-project name=\"foo\" />") .append("<project path=\"foo\" name=\"baz\" />") .append("</manifest>"); ManifestParser parser = new ManifestParser(null, null, "master", "<LINK_0>", null, null); parser.read(new ByteArrayInputStream( xmlContent.toString().getBytes(CHARSET))); Set<String> results = new HashSet<>(); results.add("bar"); results.add("baz"); for (RepoProject proj : parser.getProjects()) { assertTrue("Unexpected project is included: " + proj.getName(), results.contains(proj.getName())); results.remove(proj.getName()); } assertTrue( "Expected projects are not included", results.isEmpty()); }
Source:
<code>public static String path2uid(String path, String date) { <START> return path.replace(File.separatorChar, '\u0000') + "\u0000" + date; <END> }</code><technical_language>Lucene literal backslashes for escaping</technical_language>

Target:
public static String path2uid(String path, String date) { return path.replace('/', '\u0000') + "\u0000" + date; }
Source:
<code>protected void validate(GetPresignedObjectUrlArgs args) { super.validate(args); validateMethod(args.method); <START> validateExpiry(args.expiry); <END> }</code><technical_language>validateExpiry() is needed args.expiry default set invalid this</technical_language>

Target:
protected void validate(GetPresignedObjectUrlArgs args) { super.validate(args); validateMethod(args.method); }
Source:
<code>private int computeHashCode() { int hash = getContig().hashCode(); hash = 31 * hash + getSource().hashCode(); hash = 31 * hash + getType().hashCode(); hash = 31 * hash + getStart(); hash = 31 * hash + getEnd(); hash = 31 * hash + Double.hashCode(getScore()); hash = 31 * hash + getPhase(); hash = 31 * hash + getStrand().hashCode(); hash = 31 * hash + getAttributes().hashCode(); if (getId() != null) { hash = 31 * hash + getId().hashCode(); } if (getName() != null) { hash = 31 * hash + getName().hashCode(); } <START> for (final String alias : aliases) { <END> hash = 31 * hash + alias.hashCode(); } return hash; }</code><technical_language>I alias.hashCode(). lists implement correctly</technical_language>

Target:
private int computeHashCode() { int hash = getContig().hashCode(); hash = 31 * hash + getSource().hashCode(); hash = 31 * hash + getType().hashCode(); hash = 31 * hash + getStart(); hash = 31 * hash + getEnd(); hash = 31 * hash + Double.hashCode(getScore()); hash = 31 * hash + getPhase(); hash = 31 * hash + getStrand().hashCode(); hash = 31 * hash + getAttributes().hashCode(); if (getId() != null) { hash = 31 * hash + getId().hashCode(); } if (getName() != null) { hash = 31 * hash + getName().hashCode(); } hash = 31 * hash + aliases.hashCode(); return hash; }
Source:
<code>public void before() { if (schema instanceof SessionKeySchema) { windows[0] = new SessionWindow(10L, 10L); windows[1] = new SessionWindow(500L, 1000L); windows[2] = new SessionWindow(1_000L, 1_500L); windows[3] = new SessionWindow(30_000L, 60_000L); nextSegmentWindow = new SessionWindow(segmentInterval + retention, segmentInterval + retention); } if (schema instanceof WindowKeySchema) { windows[0] = timeWindowForSize(10L, windowSizeForTimeWindow); windows[1] = timeWindowForSize(500L, windowSizeForTimeWindow); windows[2] = timeWindowForSize(1_000L, windowSizeForTimeWindow); windows[3] = timeWindowForSize(60_000L, windowSizeForTimeWindow); nextSegmentWindow = timeWindowForSize(segmentInterval + retention, windowSizeForTimeWindow); } bytesStore = getBytesStore(); stateDir = TestUtils.tempDirectory(); <START> final StreamsMetricsImpl streamsMetrics = niceMock(StreamsMetricsImpl.class); replay(streamsMetrics); <END> context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.Long(), new NoOpRecordCollector(), new ThreadCache(new LogContext("testCache "), 0, streamsMetrics ) ); bytesStore.init(context, bytesStore); }</code><technical_language>question mocks</technical_language>

Target:
public void before() { if (schema instanceof SessionKeySchema) { windows[0] = new SessionWindow(10L, 10L); windows[1] = new SessionWindow(500L, 1000L); windows[2] = new SessionWindow(1_000L, 1_500L); windows[3] = new SessionWindow(30_000L, 60_000L); nextSegmentWindow = new SessionWindow(segmentInterval + retention, segmentInterval + retention); } if (schema instanceof WindowKeySchema) { windows[0] = timeWindowForSize(10L, windowSizeForTimeWindow); windows[1] = timeWindowForSize(500L, windowSizeForTimeWindow); windows[2] = timeWindowForSize(1_000L, windowSizeForTimeWindow); windows[3] = timeWindowForSize(60_000L, windowSizeForTimeWindow); nextSegmentWindow = timeWindowForSize(segmentInterval + retention, windowSizeForTimeWindow); } bytesStore = getBytesStore(); stateDir = TestUtils.tempDirectory(); context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.Long(), new NoOpRecordCollector(), new ThreadCache( new LogContext("testCache "), 0, new StreamsMetricsImpl(new Metrics(), "test", StreamsConfig.METRICS_LATEST) ) ); bytesStore.init(context, bytesStore); }
Source:
<code>private static String getPasswordEncodeFailMessage(String algo) { <START> String errorMessage = "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; <END> return errorMessage; }</code><technical_language>assign a variable for sake of returning</technical_language>

Target:
private static String getPasswordEncodeFailMessage(String algo) { return "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; }
Source:
<code>public MemoryEstimate visitIndexJoin(IndexJoinNode node, EstimationContext context) { PlanCostEstimate sourcesCost = context.sourcesCosts.stream() .reduce(PlanCostEstimate.zero(), CachingCostProvider::addSiblingsCost); return new MemoryEstimate( <START> sourcesCost.getMaxMemory(), <END> context.localMaxMemory + sourcesCost.getMaxMemoryWhenOutputting()); }</code><technical_language>explain this</technical_language>

Target:
public MemoryEstimate visitIndexJoin(IndexJoinNode node, EstimationContext context) { PlanCostEstimate sourcesCost = context.sourcesCosts.stream() .reduce(PlanCostEstimate.zero(), CachingCostProvider::addSiblingsCost); return new MemoryEstimate( sourcesCost.getMaxMemoryWhenOutputting(), context.localMaxMemory + sourcesCost.getMaxMemoryWhenOutputting()); }
Source:
<code>public CompletableFuture<Optional<PublicKeyHash>> getPublicKeyHash(String username) { Optional<PublicKeyHash> local = tofu.getPublicKey(username); if (local.isPresent()) return CompletableFuture.completedFuture(local); return source.getChain(username) .thenCompose(chain -> { if(chain.isEmpty()) { CompletableFuture<Boolean> noSuchUser = new CompletableFuture<>(); <START> noSuchUser.complete(false); <END> return noSuchUser; } else { return tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()); } } ).thenApply(x -> x == false ? Optional.empty() : tofu.getPublicKey(username)); }</code><technical_language>CompletableFuture.completedFuture</technical_language>

Target:
public CompletableFuture<Optional<PublicKeyHash>> getPublicKeyHash(String username) { Optional<PublicKeyHash> local = tofu.getPublicKey(username); if (local.isPresent()) return CompletableFuture.completedFuture(local); return source.getChain(username) .thenCompose(chain -> { if(chain.isEmpty()) { return CompletableFuture.completedFuture(false); } else { return tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()); } } ).thenApply(x -> x == false ? Optional.empty() : tofu.getPublicKey(username)); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RepositoryCache repositoryCache = Activator.getDefault() .getRepositoryCache(); if (repository == null) { Repository[] repositories = repositoryCache.getAllRepositories(); if (repositories.length == 0) { Shell shell = getShell(event); MessageDialog.openInformation(shell, UIText.FetchChangeFromGerritCommand_noRepositorySelectedTitle, UIText.FetchChangeFromGerritCommand_noRepositorySelectedMessage); return null; } else { File activeFile = getActiveFile(); if (activeFile != null) { <START> repository = repositoryCache.getRepository(activeFile); <END> } else { repository = repositories[0]; } } } if (repository == null) { return null; } FetchGerritChangeWizard wiz = new FetchGerritChangeWizard(repository); NonBlockingWizardDialog dlg = new NonBlockingWizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }</code><technical_language>check if getRepository is null</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); if (repository == null) { Shell shell = getShell(event); RepositoryCache repositoryCache = Activator.getDefault() .getRepositoryCache(); Repository[] repositories = repositoryCache.getAllRepositories(); ElementListSelectionDialog repositorySelectionDialog = new ElementListSelectionDialog( shell, new NoRepositorySelectedLabelProvider()); repositorySelectionDialog.setElements(repositories); repositorySelectionDialog.setTitle( UIText.FetchChangeFromGerritCommand_noRepositorySelectedTitle); if (repositorySelectionDialog.open() != Window.OK) { return null; } else { repository = (Repository) repositorySelectionDialog .getResult()[0]; } } FetchGerritChangeWizard wiz = new FetchGerritChangeWizard(repository); NonBlockingWizardDialog dlg = new NonBlockingWizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }
Source:
<code>private String tryReadLine(FileChannel channel, char separator) throws IOException, InterruptedException { int retryNumber = 0; long rePos = 0; StringBuilder sb = new StringBuilder(); while (!Thread.currentThread().isInterrupted()) { if (retryNumber > failureRetryLimit && failureRetryLimit > 0) { LOG.error("fail to read line after attempts", retryNumber); throw new IOException(); } try { rePos = channel.position(); buffer.clear(); boolean end = false; int num; while (((num = channel.read(buffer)) != -1) && !end) { buffer.flip(); CharBuffer charBuffer = charset.decode(buffer); for (int i = 0; i < num; i++) { char ch = charBuffer.charAt(i); if (ch != separator) { sb.append(ch); <START> rePos++; <END> } else { rePos++; end = true; break; } } buffer.clear(); } break; } catch (IOException e) { retryNumber++; Thread.sleep(failureSleepInterval); } } channel.position(rePos); return sb.toString(); }</code><technical_language>this is correct. channel position is measure in byte, char. If file multi-bytes char, this wrong</technical_language>

Target:
private String tryReadLine(FileChannel channel, char separator) throws IOException, InterruptedException { int retryNumber = 0; long position = channel.position(); StringBuilder sb = new StringBuilder(); boolean lineNotRead = true; while (lineNotRead) { if (retryNumber > failureRetryLimit && failureRetryLimit > 0) { LOG.error("fail to read line after attempts", retryNumber); throw new IOException(); } try { readBuffer.clear(); decoded.clear(); int len = channel.read(readBuffer); lineNotRead = false; if (len >= 0) { readBuffer.flip(); decoder.decode(readBuffer, decoded, false); decoded.flip(); for (int i = 0; i < decoded.length(); i++) { char ch = decoded.charAt(i); if (ch != separator) { sb.append(ch); } else { break; } } } } catch (IOException e) { retryNumber++; Thread.sleep(failureSleepInterval); } } String line = sb.toString(); channel.position(position + line.getBytes(charset).length + separatorByteLength); return line; }
Source:
<code>public Host resolveHostNameWithoutDefault(String serverName, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { Host host = hostCache.getHostByAlias(serverName); User systemUser = APILocator.systemUser(); if(host == null){ try { host = findByNameNotDefault(serverName, systemUser, respectFrontendRoles); } catch (Exception e) { return findDefaultHost(systemUser, respectFrontendRoles); } if(host == null){ host = findByAlias(serverName, systemUser, respectFrontendRoles); } if(host != null){ <START> hostCache.addHostAlias(serverName, host); <END> } } if (host != null) { checkHostPermission(user, respectFrontendRoles, host); } return host; }</code><technical_language>This logic moved below. Here: if (host != null) { checkHostPermission(user, respectFrontendRoles, host); }</technical_language>

Target:
public Optional<Host> resolveHostNameWithoutDefault(String serverName, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { Host host = hostCache.getHostByAlias(serverName); User systemUser = APILocator.systemUser(); if(host == null){ host = findByNameNotDefault(serverName, systemUser, respectFrontendRoles); if(host == null){ host = findByAlias(serverName, systemUser, respectFrontendRoles); } if(host != null){ hostCache.addHostAlias(serverName, host); } } if (host != null) { checkHostPermission(user, respectFrontendRoles, host); } return Optional.ofNullable(host); }