auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; Parameter param = null; for (int k = 0; k < series.length; k++) { ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { continue; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]) - e.x; int ys = yAxis.getPixelCoordinate(yS[i]) - e.y; <START> double currentDistance = Math.sqrt(xs * xs + ys * ys); <END> if ((currentDistance < smallestDistance) && (currentDistance < HIGHLIGHT_RADIUS)) { smallestDistance = currentDistance; fHighlightX = xs + e.x; fHighlightY = ys + e.y; if (param == null) { param = new Parameter(); } param.setSeriesIndex(k); param.setDataIndex(i); } } } String tooltip = null; if (param != null) { tooltip = createToolTipText(param); if (tooltip != null) { fIsHighlight = true; getChart().redraw(); } } getChart().getPlotArea().setToolTipText(tooltip); } }</code><technical_language>need for sqrt</technical_language>

Target:
public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; Parameter param = null; for (int k = 0; k < series.length; k++) { ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { continue; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]) - e.x; int ys = yAxis.getPixelCoordinate(yS[i]) - e.y; double currentDistance = xs * xs + ys * ys; if ((currentDistance < smallestDistance) && (currentDistance < (HIGHLIGHT_RADIUS * HIGHLIGHT_RADIUS))) { smallestDistance = currentDistance; fHighlightX = xs + e.x; fHighlightY = ys + e.y; if (param == null) { param = new Parameter(); } param.setSeriesIndex(k); param.setDataIndex(i); } } } String tooltip = null; if (param != null) { tooltip = createToolTipText(param); if (tooltip != null) { fIsHighlight = true; getChart().redraw(); } } getChart().getPlotArea().setToolTipText(tooltip); } }
Source:
<code>public void fetch(@NonNull final Intent intent) { checkNotNull(intent); final int repositoryId = intent.getIntExtra("id", -1); <START> if (repositoryId > -1) { <END> fetchGitHubRepository(repositoryId); } else { Log.e(TAG, "No repositoryId provided in the intent extras"); } }</code><technical_language>repositoryId >= 0 more readable</technical_language>

Target:
public void fetch(@NonNull final Intent intent) { checkNotNull(intent); final int repositoryId = intent.getIntExtra("id", -1); if (repositoryId >= 0) { fetchGitHubRepository(repositoryId); } else { Log.e(TAG, "No repositoryId provided in the intent extras"); } }
Source:
<code>private Platform() { final String platformOs = System.getProperty("os.name").toLowerCase(); <START> if (platformOs.equals("linux")) { <END> this.os = "linux"; } else if (platformOs.startsWith("mac os")) { this.os = "mac"; } else if (platformOs.startsWith("windows")) { this.os = "windows"; } else { this.os = platformOs; } final String platformArch = System.getProperty("os.arch"); if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { this.arch = "64"; } else if (platformArch.equals("x86")) { this.arch = "32"; } else { this.arch = platformArch; } }</code><technical_language>this alwyas _equals_ "linux" startsWith a safer option</technical_language>

Target:
private Platform() { final String platformOs = System.getProperty("os.name").toLowerCase(); if (platformOs.startsWith("linux")) { os = "linux"; } else if (platformOs.startsWith("mac os")) { os = "mac"; } else if (platformOs.startsWith("windows")) { os = "windows"; } else { os = platformOs; } final String platformArch = System.getProperty("os.arch"); if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { arch = "64"; } else if (platformArch.equals("x86") || platformArch.equals("i386")) { arch = "32"; } else { arch = platformArch; } }
Source:
<code>public T get() { <START> throw new UnsupportedOperationException("#get()"); <END> }</code><technical_language>I change this "#get()" more meaningful, "there is here, has() first, check"</technical_language>

Target:
public T get() { throw new UnsupportedOperationException( "there is nothing here, use has() first, to check" ); }
Source:
<code>public void removeFilter(@NonNull ViewerFilter filter) { fTimeGraphCtrl.removeFilter(filter); refresh(); <START> fTimeGraphCtrl.fireFilterApplied(); <END> }</code><technical_language>a bit misleading call filterApplied() removing. I propose filterChanged(), separate methods. In option, carry filter in event, necessary</technical_language>

Target:
public void removeFilter(@NonNull ViewerFilter filter) { fTimeGraphCtrl.removeFilter(filter); refresh(); }
Source:
<code>public static String stringToHtml(String inxml, String infilexsl) { Document doc = null; File stylesheet = null; StringReader inReader = new StringReader(inxml); StringWriter writer = new StringWriter(); try { stylesheet = new File(infilexsl); DocumentBuilder builder = XmlUtils.newXxeDisabledDocumentBuilderFactory().newDocumentBuilder(); doc = builder.parse(new InputSource(inReader)); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) { showDialogForGUI(); logger.error(e.getMessage(), e); <START> return inxml; <END> } finally { } return writer.toString(). replace("&lt;p&gt;", "<p>"). replace("&lt;/p&gt;", "</p>"); }</code><technical_language>This is necessary, next statement return (without I/O operation)</technical_language>

Target:
public static String stringToHtml(String inxml, String infilexsl) { Document doc = null; File stylesheet = null; StringReader inReader = new StringReader(inxml); StringWriter writer = new StringWriter(); try { stylesheet = new File(infilexsl); DocumentBuilder builder = XmlUtils.newXxeDisabledDocumentBuilderFactory().newDocumentBuilder(); doc = builder.parse(new InputSource(inReader)); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) { showDialogForGUI(); logger.error(e.getMessage(), e); } finally { } return writer.toString(). replace("&lt;p&gt;", "<p>"). replace("&lt;/p&gt;", "</p>"); }
Source:
<code>public Response generateEdges() { List<DeviceOrganizationVisEdge> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); result = dops.generateEdges(); if (result.isEmpty()) { String msg = "No Edge connections available and visible"; log.error(msg); <START> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); <END> } return Response.status(Response.Status.OK).entity(result).build(); }</code><technical_language>IMO, this is error. log a debug log. response NOT_FOUND devices enrolled system in order generate edges</technical_language>

Target:
public Response generateEdges() { List<DeviceOrganizationVisEdge> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); result = dops.generateEdges(); if (result.isEmpty()) { String msg = "No Edge connections available and visible"; if (log.isDebugEnabled()) { log.debug(msg); } return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); }
Source:
<code>protected boolean isUnsupportedXmlnsAttribute(Attr attribute) { <START> return StringUtils.startsWith(attribute.getName(), XMLNS_ATTRIBUTE_PREFIX) <END> && !ALLOWED_XMLNS_ATTRIBUTES_PATTERN.matcher(attribute.getName()).matches(); }</code><technical_language>this starts ignore case</technical_language>

Target:
protected boolean isUnsupportedXmlnsAttribute(Attr attribute) { String attributeName = StringUtils.lowerCase(attribute.getName()); return StringUtils.startsWith(attributeName, XMLNS_ATTRIBUTE_PREFIX) && !ALLOWED_XMLNS_ATTRIBUTES_PATTERN.matcher(attributeName).matches(); }
Source:
<code>StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = message.getOrCreateSession(channel); <START> if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); <END> streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }</code><technical_language>Based understanding, calling getOrCreateSession StreamInitMessage IncomingStreamMessage is guaranty return a StreamSession calling getOrCreateSession another type of message throw UnsupportedOperationException. consequence, this null check is useless. I missing something</technical_language>

Target:
StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = message.getOrCreateSession(channel); streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }
Source:
<code>private Set<RelationalSymbolicValue> transitiveRelations(Set<RelationalSymbolicValue> knownRelations) { Set<RelationalSymbolicValue> newRelations = new HashSet<>(); Deque<RelationalSymbolicValue> workList = new ArrayDeque<>(); int iterations = 0; workList.add(this); while (!workList.isEmpty()) { if (newRelations.size() > MAX_DEDUCED_RELATIONS || iterations > MAX_ITERATIONS) { throw new RelationalSymbolicValue.TransitiveRelationExceededException("Used relations: " + newRelations.size() + ". Iterations " + iterations); } iterations++; RelationalSymbolicValue relation = workList.pop(); for (RelationalSymbolicValue knownRelation : knownRelations) { RelationalSymbolicValue r = relation.deduceTransitiveOrSimplified(knownRelation); if (r != null && !knownRelations.contains(r) && !newRelations.contains(r)) { <START> newRelations.add(r); <END> workList.add(r); } } } return newRelations; }</code><technical_language>done slightly : if (r != null && !knownRelations.contains(r)) { if(newRelations.add(r)) { worklist.add(r); } } if in turn collapsed : readability though..</technical_language>

Target:
Set<RelationalSymbolicValue> transitiveRelations(Set<RelationalSymbolicValue> knownRelations) { Set<RelationalSymbolicValue> newRelations = new HashSet<>(); Deque<RelationalSymbolicValue> workList = new ArrayDeque<>(); int iterations = 0; workList.add(this); while (!workList.isEmpty()) { if (newRelations.size() > MAX_DEDUCED_RELATIONS || iterations > MAX_ITERATIONS) { throw new RelationalSymbolicValue.TransitiveRelationExceededException("Used relations: " + newRelations.size() + ". Iterations " + iterations); } iterations++; RelationalSymbolicValue relation = workList.pop(); for (RelationalSymbolicValue knownRelation : knownRelations) { RelationalSymbolicValue r = relation.deduceTransitiveOrSimplified(knownRelation); if (r != null && !knownRelations.contains(r) && newRelations.add(r)) { workList.add(r); } } } return newRelations; }
Source:
<code>public void removeMember(PerunSession sess, List<Group> groups, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException { Collections.sort(groups); <START> Collections.reverse(groups); <END> for (Group group : groups) { if (group.getName().equals(VosManager.MEMBERS_GROUP)) { throw new InternalErrorException("Cannot remove member directly from the members group."); } else { try { this.removeDirectMember(sess, group, member); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex){ throw new InternalErrorException(ex); } } } }</code><technical_language>I this code is more effective. Collections.sort(groups, Collections.reverseOrder());</technical_language>

Target:
public void removeMember(PerunSession sess, List<Group> groups, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException { Collections.sort(groups, Collections.reverseOrder()); for (Group group : groups) { if (group.getName().equals(VosManager.MEMBERS_GROUP)) { throw new InternalErrorException("Cannot remove member directly from the members group."); } else { try { this.removeDirectMember(sess, group, member); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex){ throw new InternalErrorException(ex); } } } }
Source:
<code>public void retryableConfigurationExceptionsTest() throws Exception { doTestHttpClient(new Runnable() { @Override public void run() { System.setProperty( "maven.wagon.http.retryhandler.class", "default" ); System.setProperty( "maven.wagon.http.retryhandler.nonRetryableClasses", IOException.class.getName() ); final HttpRequestRetryHandler handler = getCurrentHttpClient(); assertNotNull( handler ); assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); assertEquals( 3, impl.getRetryCount() ); assertFalse( impl.isRequestSentRetryEnabled() ); try { final Field nonRetriableClasses = handler.getClass().getSuperclass() .getDeclaredField( "nonRetriableClasses" ); <START> if (!nonRetriableClasses.isAccessible()) <END> { nonRetriableClasses.setAccessible(true); } final Set<?> exceptions = Set.class.cast( nonRetriableClasses.get(handler) ); assertEquals( 1, exceptions.size() ); assertTrue( exceptions.contains( IOException.class ) ); } catch ( final Exception e ) { fail( e.getMessage() ); } } }); }</code><technical_language>this work Java 10/11</technical_language>

Target:
public void retryableConfigurationExceptionsTest() throws Exception { doTestHttpClient( new Runnable() { @Override public void run() { System.setProperty( "maven.wagon.http.retryhandler.class", "default" ); System.setProperty( "maven.wagon.http.retryhandler.nonRetryableClasses", IOException.class.getName() ); final HttpRequestRetryHandler handler = getCurrentHandler(); assertNotNull( handler ); assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); assertEquals( 3, impl.getRetryCount() ); assertFalse( impl.isRequestSentRetryEnabled() ); try { final Field nonRetriableClasses = handler.getClass().getSuperclass() .getDeclaredField( "nonRetriableClasses" ); if ( !nonRetriableClasses.isAccessible() ) { nonRetriableClasses.setAccessible(true); } final Set<?> exceptions = Set.class.cast( nonRetriableClasses.get(handler) ); assertEquals( 1, exceptions.size() ); assertTrue( exceptions.contains( IOException.class ) ); } catch ( final Exception e ) { fail( e.getMessage() ); } } }); }
Source:
<code>private Callback<ModelField[]> fieldCompletionsCallback(String factName, Callback<FactModelTree> aggregatorCallback) { return result -> { Map<String, String> simpleProperties = new HashMap<>(); for (ModelField modelField : result) { if (!modelField.getName().equals("this")) { simpleProperties.put(modelField.getName(), modelField.getClassName()); } } String factPackageName; String fullFactClassName = oracle.getFQCNByFactName(factName); if (fullFactClassName != null && fullFactClassName.contains(".")) { factPackageName = fullFactClassName.substring(0, fullFactClassName.lastIndexOf(".")); } else { factPackageName = packageName; } <START> FactModelTree toSend = new FactModelTree(factName, factPackageName, simpleProperties); <END> aggregatorCallback.callback(toSend); }; }</code><technical_language>shorten code slightly, please notice whitespaces && fullFactClassName.contains(".") java String factPackageName = packageName; String fullFactClassName = oracle.getFQCNByFactName(factName); if (fullFactClassName != null && fullFactClassName.contains(".")) { factPackageName = fullFactClassName.substring(0, fullFactClassName.lastIndexOf(".")); } forget unit tests. Manual check pending</technical_language>

Target:
protected Callback<ModelField[]> fieldCompletionsCallback(String factName, Callback<FactModelTree> aggregatorCallback) { return result -> { FactModelTree toSend = getFactModelTree(factName, result); aggregatorCallback.callback(toSend); }; }
Source:
<code>protected void tearDown() throws Exception { <START> Locale.getDefault(); <END> Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }</code><technical_language>is this needed</technical_language>

Target:
protected void tearDown() throws Exception { Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }
Source:
<code>public Response removeUser(@PathParam("username") String username, @QueryParam("domain") String domain) { <START> if (domain != null) { <END> username = domain + '/' + username; } try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } }</code><technical_language>add isEmpty() check for domain</technical_language>

Target:
public Response removeUser(@PathParam("username") String username, @QueryParam("domain") String domain) { if (domain != null && !domain.isEmpty()) { username = domain + '/' + username; } try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } }
Source:
<code>public void run() { int reconnectAttempts = 0; for (; ; ) { if (Thread.currentThread().isInterrupted()) { return; } LOG.debug("Start connection loop channels ", wsUri, channels); try { connect(wsUri, channels); reconnectAttempts = 0; LOG.debug("Connection complete"); return; } catch (IOException | DeploymentException e) { LOG.warn("Not able to connect to because {}. Retrying ", wsUri, e.getLocalizedMessage()); LOG.debug(e.getLocalizedMessage(), e); if (reconnectAttempts++ > MAX_ATTEMPTS) { <START> LOG.error(WORKSPACE_AGENT_STOPPED_MESSAGE); <END> try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception ex) { LOG.info(e.getLocalizedMessage(), ex); } System.exit(0); } synchronized (this) { try { wait(WS_CONNECTION_TIMEOUT * 2 * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } catch (Throwable e) { LOG.error("Unexpected here"); LOG.error(e.getLocalizedMessage(), e); } LOG.debug("Iteration complete"); } }</code><technical_language>log.warn</technical_language>

Target:
public void run() { for (; ; ) { if (Thread.currentThread().isInterrupted()) { return; } LOG.debug("Start connection loop channels ", wsUri, channels); try { connect(wsUri, channels); LOG.debug("Connection complete"); return; } catch (IOException | DeploymentException e) { LOG.warn("Not able to connect to because {}. Retrying ", wsUri, e.getLocalizedMessage()); LOG.debug(e.getLocalizedMessage(), e); synchronized (this) { try { wait(WS_CONNECTION_TIMEOUT * 2 * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } catch (Throwable e) { LOG.error("Unexpected here"); LOG.error(e.getLocalizedMessage(), e); } LOG.debug("Iteration complete"); } }
Source:
<code>public ImageFormat determineImageFormat(final InputStream is) throws IOException { Preconditions.checkNotNull(is); final byte[] imageHeaderBytes = new byte[mMaxHeaderLength]; final int headerSize = readHeaderFromStream(mMaxHeaderLength, is, imageHeaderBytes); <START> ImageFormat format = mDefaultFormatChecker.determineFormat(imageHeaderBytes, headerSize); <END> if (format != null && format != ImageFormat.UNKNOWN) { return format; } if (mCustomImageFormatCheckers != null) { for (ImageFormat.FormatChecker formatChecker : mCustomImageFormatCheckers) { format = formatChecker.determineFormat(imageHeaderBytes, headerSize); if (format != null && format != ImageFormat.UNKNOWN) { return format; } } } return ImageFormat.UNKNOWN; }</code><technical_language>Unfortunately, pull request import squash of commits one, in changeset. open a separate pull request for changing order commit title blame more sense? Thanks</technical_language>

Target:
public ImageFormat determineImageFormat(final InputStream is) throws IOException { Preconditions.checkNotNull(is); final byte[] imageHeaderBytes = new byte[mMaxHeaderLength]; final int headerSize = readHeaderFromStream(mMaxHeaderLength, is, imageHeaderBytes); if (mCustomImageFormatCheckers != null) { for (ImageFormat.FormatChecker formatChecker : mCustomImageFormatCheckers) { ImageFormat format = formatChecker.determineFormat(imageHeaderBytes, headerSize); if (format != null && format != ImageFormat.UNKNOWN) { return format; } } } ImageFormat format = mDefaultFormatChecker.determineFormat(imageHeaderBytes, headerSize); if (format == null) { format = ImageFormat.UNKNOWN; } return format; }
Source:
<code>public static GitWebType fromName(final String name) { final GitWebType type; if (name == null || name.isEmpty() || name.equalsIgnoreCase("gitweb")) { type = new GitWebType(); type.setProject("?p=${project}.git;a=summary"); type.setRevision("?p=${project}.git;a=commit;h=${commit}"); type.setBranch("?p=${project}.git;a=shortlog;h=${branch}"); } else if (name.equalsIgnoreCase("gitweb-pathinfo")) { type = new GitWebType(); type.setProject("/${project_path}.git/summary"); type.setRevision("/${project_path}.git/commit/${commit}"); <START> type.setBranch("/${project_path}.git/shortlog/${branch_path}"); <END> } else if (name.equalsIgnoreCase("cgit")) { type = new GitWebType(); type.setProject("${project}/summary"); type.setRevision("${project}/commit/?id=${commit}"); type.setBranch("${project}/log/?h=${branch}"); } else if (name.equalsIgnoreCase("custom")) { type = new GitWebType(); } else { type = null; } return type; }</code><technical_language>reason for leading slash</technical_language>

Target:
public static GitWebType fromName(final String name) { final GitWebType type; if (name == null || name.isEmpty() || name.equalsIgnoreCase("gitweb")) { type = new GitWebType(); type.setProject("?p=${project}.git;a=summary"); type.setRevision("?p=${project}.git;a=commit;h=${commit}"); type.setBranch("?p=${project}.git;a=shortlog;h=${branch}"); } else if (name.equalsIgnoreCase("gitweb-pathinfo")) { type = new GitWebType(); type.setProject("${project}.git/summary"); type.setRevision("${project}.git/commit/${commit}"); type.setBranch("${project}.git/shortlog/${branch}"); type.setPathInfo(true); } else if (name.equalsIgnoreCase("cgit")) { type = new GitWebType(); type.setProject("${project}/summary"); type.setRevision("${project}/commit/?id=${commit}"); type.setBranch("${project}/log/?h=${branch}"); } else if (name.equalsIgnoreCase("custom")) { type = new GitWebType(); } else { type = null; } return type; }
Source:
<code>private void runChecks(SensorContext context, XmlFile xmlFile, NewXmlFile newXmlFile) { XmlSourceCode sourceCode = new XmlSourceCode(xmlFile); if (sourceCode.parseSource()) { checks.all().stream() .filter(AbstractXmlCheck.class::isInstance) .map(AbstractXmlCheck.class::cast) .forEach(check -> runCheck(check, sourceCode)); saveIssues(context, sourceCode); } checks.all().stream() .filter(NewXmlCheck.class::isInstance) .map(NewXmlCheck.class::cast) .forEach(check -> { RuleKey ruleKey = checks.ruleKey(check); if (ruleKey == null) { <START> throw new IllegalStateException("Failed to get rule key for rule " + check.getClass()); <END> } runCheck(context, check, ruleKey, newXmlFile); }); }</code><technical_language>If fail here, fail file everytime try execute this rule. Do want log for file</technical_language>

Target:
private void runChecks(SensorContext context, XmlFile xmlFile, NewXmlFile newXmlFile) { XmlSourceCode sourceCode = new XmlSourceCode(xmlFile); if (sourceCode.parseSource()) { checks.all().stream() .filter(AbstractXmlCheck.class::isInstance) .map(AbstractXmlCheck.class::cast) .forEach(check -> runCheck(check, sourceCode)); saveIssues(context, sourceCode); } checks.all().stream() .filter(NewXmlCheck.class::isInstance) .map(NewXmlCheck.class::cast) .forEach(check -> runCheck(context, check, checks.ruleKey(check), newXmlFile)); }
Source:
<code><START> private void validateRetentionPolicy(String retentionPolicy) throws FalconException { <END> if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }</code><technical_language>method static</technical_language>

Target:
public static void validateRetentionPolicy(String retentionPolicy) throws FalconException { if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }
Source:
<code>private void handleRegularArgument(RegularArgument regularArgument, SubscriptionContext ctx) { Name keywordArgument = regularArgument.keywordArgument(); if (keywordArgument != null && isCredential(keywordArgument.name(), variablePatterns()) <START> && regularArgument.expression().is(Tree.Kind.STRING_LITERAL) && !isEmptyStringLiteral((StringLiteral) regularArgument.expression())) { <END> ctx.addIssue(regularArgument, MESSAGE); } }</code><technical_language>I factorize conditions in a separate method: java private static boolean isNonEmptyStringLiteral(Tree tree) { return tree.is(Kind.STRING_LITERAL) && !isEmptyStringLiteral((StringLiteral)tree) }</technical_language>

Target:
private void handleRegularArgument(RegularArgument regularArgument, SubscriptionContext ctx) { Name keywordArgument = regularArgument.keywordArgument(); if (keywordArgument != null && isCredential(keywordArgument.name(), variablePatterns()) && isNonEmptyStringLiteral(regularArgument.expression())) { ctx.addIssue(regularArgument, MESSAGE); } }
Source:
<code>public String getMessage() { return "Impossible to delete some children when computing the folder: \n" + <START> String.join("\n", exceptions.stream().map(e -> e.getMessage()).collect(Collectors.toList())); <END> }</code><technical_language>Do adding some indentation in message visually understand end of list? suggestion String.join("\n\t", exceptions.stream().map(e -> e.getMessage()).collect(Collectors.toList()));</technical_language>

Target:
public String getMessage() { return "Impossible to delete some children when computing the folder. The first errors are: \n\t" + String.join("\n\t", exceptions.stream().limit(3).map(e -> e.getMessage()).collect(Collectors.toList())); }
Source:
<code>public void markCompleted() { if(isTXCommit) { InflightMessageList.InflightMessage message = inflightMessages.completeMessage(position); if (message != null) { context.setPosition(message.position); Metrics metrics = context.getMetrics(); <START> Timer timer = metrics.getRegistry().timer(metrics.metricName("message", "publish", "time")); <END> timer.update(message.timeSinceSendMS(), TimeUnit.MILLISECONDS); } } }</code><technical_language>able reuse timer here</technical_language>

Target:
public void markCompleted() { if(isTXCommit) { InflightMessageList.InflightMessage message = inflightMessages.completeMessage(position); if (message != null) { context.setPosition(message.position); metricsTimer.update(message.timeSinceSendMS(), TimeUnit.MILLISECONDS); } } }
Source:
<code>public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { <START> response = Response.status(Response.Status.OK).entity(DispoUtil.itemArtToItemData(result)).build(); <END> } return response; }</code><technical_language>this part of a commit</technical_language>

Target:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { response = Response.status(Response.Status.OK).entity(result).build(); } return response; }
Source:
<code>public static String generateServletActionFailureLogMessage(HttpServletRequest req, Exception e) { String[] actionTaken = req.getServletPath().split("/"); String action = req.getServletPath(); if (actionTaken.length > 0) { action = actionTaken[actionTaken.length - 1]; } String url = HttpRequestHelper.getRequestedURL(req); StringBuilder message = new StringBuilder(100); message.append("<span class=\"text-danger\">Servlet Action failure in ").append(action).append("<br>") .append(e.getClass()).append(": ").append(TeammatesException.toStringWithStackTrace(e)).append("<br>") <START> .append(HttpRequestHelper.printRequestParameters(req)).append("</span>"); <END> String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.COURSE_ID); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.STUDENT_EMAIL); ActivityLogEntry exceptionLog = new ActivityLogEntry(action, Const.ACTION_RESULT_FAILURE, null, message.toString(), url, courseId, studentEmail); return exceptionLog.generateLogMessage(); }</code><technical_language>Again, message assigned old-fashioned way</technical_language>

Target:
public static String generateServletActionFailureLogMessage(HttpServletRequest req, Exception e) { String[] actionTaken = req.getServletPath().split("/"); String action = req.getServletPath(); if (actionTaken.length > 0) { action = actionTaken[actionTaken.length - 1]; } String url = HttpRequestHelper.getRequestedURL(req); String message = "<span class=\"text-danger\">Servlet Action failure in " + action + "<br>" + e.getClass() + ": " + TeammatesException.toStringWithStackTrace(e) + "<br>" + HttpRequestHelper.printRequestParameters(req) + "</span>"; String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.COURSE_ID); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.STUDENT_EMAIL); ActivityLogEntry exceptionLog = new ActivityLogEntry(action, Const.ACTION_RESULT_FAILURE, null, message, url, courseId, studentEmail); return exceptionLog.generateLogMessage(); }
Source:
<code>public void setup() { doReturn(viewport).when(gridPanel).getViewport(); doReturn(viewportMediators).when(viewport).getMediators(); doReturn(gridPanelElement).when(gridPanel).getElement(); this.view = new ExpressionEditorViewImpl(exitButton, expressionEditorControls, document, <START> ts, <END> gridPanel, gridLayer, mousePanMediator, sessionManager, sessionCommandManager); }</code><technical_language>translationService insead of ts ? is easy derive multiparameter constructor</technical_language>

Target:
public void setup() { doReturn(viewport).when(gridPanel).getViewport(); doReturn(viewportMediators).when(viewport).getMediators(); doReturn(gridPanelElement).when(gridPanel).getElement(); this.view = new ExpressionEditorViewImpl(exitButton, expressionEditorControls, document, translationService, gridPanel, gridLayer, mousePanMediator, sessionManager, sessionCommandManager); }
Source:
<code><START> private boolean needAck(Message message) { <END> if (message.getSequence() == message.getBatch().getWindowSize()) { return true; } else { return false; } }</code><technical_language>java private boolean needAck(Message message) { return message.getSequence() == message.getBatch().getWindowSize() }</technical_language>

Target:
private boolean needAck(Message message) { return message.getSequence() == message.getBatch().getBatchSize(); }
Source:
<code>private ButtonFieldActionDescriptor extractButtonFieldActionDescriptor(final String tableName, final String fieldName, final int adProcessId) { if (adProcessId > 0) { if (WindowConstants.FIELDNAME_DocAction.equals(fieldName) <START> || WindowConstants.FIELDNAME_Processing.equals(fieldName)) <END> { return null; } return ButtonFieldActionDescriptor.processCall(ProcessId.ofAD_Process_ID(adProcessId)); } if (tableName != null) { if (adColumnBL.isRecordIdColumnName(fieldName)) { final String zoomIntoTableIdFieldName = adColumnBL.getTableIdColumnName(tableName, fieldName).orElse(null); if (zoomIntoTableIdFieldName != null) { return ButtonFieldActionDescriptor.genericZoomInto(zoomIntoTableIdFieldName); } } } return null; }</code><technical_language>reason of this change</technical_language>

Target:
private ButtonFieldActionDescriptor extractButtonFieldActionDescriptor(final String tableName, final String fieldName, final int adProcessId) { if (adProcessId > 0) { if ( WindowConstants.FIELDNAME_Processing.equals(fieldName)) { return null; } return ButtonFieldActionDescriptor.processCall(ProcessId.ofAD_Process_ID(adProcessId)); } if (tableName != null) { if (adColumnBL.isRecordIdColumnName(fieldName)) { final String zoomIntoTableIdFieldName = adColumnBL.getTableIdColumnName(tableName, fieldName).orElse(null); if (zoomIntoTableIdFieldName != null) { return ButtonFieldActionDescriptor.genericZoomInto(zoomIntoTableIdFieldName); } } } return null; }
Source:
<code>public static <V> CompletionStage<V> continueOnExecutor(CompletionStage<V> delay, Executor continuationExecutor, Object traceId) { if (isCompletedSuccessfully(delay)) { if (trace) { log.tracef("Stage for %s was already completed, returning in same thread", traceId); } return delay; } CompletionStage<V> returnedFuture = delay.thenApplyAsync(v -> { if (trace) { log.tracef("Continuing execution of id %s", traceId); } return v; }, continuationExecutor); if (trace) { <START> returnedFuture.exceptionally(t -> { <END> log.tracef("Continuing execution of id %s with exception %s", traceId, t.getMessage()); return null; }); } return returnedFuture; }</code><technical_language>If return returnedFuture.exceptionally(...) need rely implementation details</technical_language>

Target:
public static <V> CompletionStage<V> continueOnExecutor(CompletionStage<V> delay, Executor continuationExecutor, Object traceId) { if (isCompletedSuccessfully(delay)) { if (trace) { log.tracef("Stage for %s was already completed, returning in same thread", traceId); } return delay; } return delay.whenCompleteAsync((v, t) -> { if (t != null) { if (trace) { log.tracef("Continuing execution of id %s with exception %s", traceId, t.getMessage()); } } else if (trace) { log.tracef("Continuing execution of id %s", traceId); } }, continuationExecutor); }
Source:
<code>public void listPatchesAgainstBase() throws Exception { add(git, FILE_D, "4"); createCommit(git, admin.getIdent(), SUBJECT_1); pushHead(git, "refs/heads/master", false); add(git, FILE_A, "1"); rm(git, FILE_D); Commit c = createCommit(git, admin.getIdent(), SUBJECT_2); pushHead(git, "refs/for/master", false); List<PatchListEntry> entries = getCurrentPatches(c.getChangeId()); <START> assertThat(entries.size()).isEqualTo(3); <END> assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertDeleted(FILE_D, entries.get(2)); add(git, FILE_B, "2"); c = amendCommit(git, admin.getIdent(), SUBJECT_2, c.getChangeId()); pushHead(git, "refs/for/master", false); entries = getCurrentPatches(c.getChangeId()); assertThat(entries.size()).isEqualTo(4); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertAdded(FILE_B, entries.get(2)); assertDeleted(FILE_D, entries.get(3)); }</code><technical_language>assertThat(entries).hasSize(3); for occurances</technical_language>

Target:
public void listPatchesAgainstBase() throws Exception { add(git, FILE_D, "4"); createCommit(git, admin.getIdent(), SUBJECT_1); pushHead(git, "refs/heads/master", false); add(git, FILE_A, "1"); rm(git, FILE_D); Commit c = createCommit(git, admin.getIdent(), SUBJECT_2); pushHead(git, "refs/for/master", false); List<PatchListEntry> entries = getCurrentPatches(c.getChangeId()); assertThat(entries).hasSize(3); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertDeleted(FILE_D, entries.get(2)); add(git, FILE_B, "2"); c = amendCommit(git, admin.getIdent(), SUBJECT_2, c.getChangeId()); pushHead(git, "refs/for/master", false); entries = getCurrentPatches(c.getChangeId()); assertThat(entries).hasSize(4); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertAdded(FILE_B, entries.get(2)); assertDeleted(FILE_D, entries.get(3)); }
Source:
<code>public boolean copyInitialTasksForRetry(List<Long> recursiveChildrenIdList) { List<StoredTask> tasks = handle.createQuery( selectTaskDetailsQuery() + " where t.id " + inLargeIdListExpression(recursiveChildrenIdList) + " and " + bitAnd("t.state_flags", Integer.toString(TaskStateFlags.INITIAL_TASK)) + " != 0" + " order by t.id asc" ) .map(stm) .list(); if (tasks.isEmpty()) { return false; } DatabaseTaskControlStore store = new DatabaseTaskControlStore(handle); Map<Long, Long> oldIdToNewId = new HashMap<>(); for (StoredTask task : tasks) { Task newTask = Task.taskBuilder() .from(task) <START> .parentId(task.getParentId().transform(it -> oldIdToNewId.containsKey(it) ? oldIdToNewId.get(it) : it)) <END> .state(TaskStateCode.BLOCKED) .stateFlags(TaskStateFlags.empty()) .build(); long newTaskId = addSubtask(tasks.get(0).getAttemptId(), newTask); oldIdToNewId.put(task.getId(), newTaskId); for (long oldUpstreamId : task.getUpstreams()) { dao.insertTaskDependency(newTaskId, oldIdToNewId.get(oldUpstreamId)); } } return true; }</code><technical_language>simply -> oldIdToNewId.getOrDefault(it, it)</technical_language>

Target:
public boolean copyInitialTasksForRetry(List<Long> recursiveChildrenIdList) { List<StoredTask> tasks = handle.createQuery( selectTaskDetailsQuery() + " where t.id " + inLargeIdListExpression(recursiveChildrenIdList) + " and " + bitAnd("t.state_flags", Integer.toString(TaskStateFlags.INITIAL_TASK)) + " != 0" + " order by t.id asc" ) .map(stm) .list(); if (tasks.isEmpty()) { return false; } DatabaseTaskControlStore store = new DatabaseTaskControlStore(handle); Map<Long, Long> oldIdToNewId = new HashMap<>(); for (StoredTask task : tasks) { Task newTask = Task.taskBuilder() .from(task) .parentId(task.getParentId().transform(it -> oldIdToNewId.getOrDefault(it, it))) .state(TaskStateCode.BLOCKED) .stateFlags(TaskStateFlags.empty()) .build(); long newTaskId = addSubtask(tasks.get(0).getAttemptId(), newTask); oldIdToNewId.put(task.getId(), newTaskId); for (long oldUpstreamId : task.getUpstreams()) { dao.insertTaskDependency(newTaskId, oldIdToNewId.get(oldUpstreamId)); } } return true; }
Source:
<code>private static String assemble(String easting, String northing) { StringBuilder numericBuilder = new StringBuilder(); <START> Runnable appendZero = () -> numericBuilder.append("0"); <END> if (easting.length() < MAX_EASTING_LENGTH) { int numberOfZerosNeeded = MAX_EASTING_LENGTH - easting.length(); repeat(numberOfZerosNeeded, appendZero); } numericBuilder.append(easting); if (northing.length() < MAX_NORTHING_LENGTH) { int numberOfZerosNeeded = MAX_NORTHING_LENGTH - northing.length(); repeat(numberOfZerosNeeded, appendZero); } numericBuilder.append(northing); return numericBuilder.toString(); }</code><technical_language>do new StringBuilder().append("0") new StringBuilder("0")</technical_language>

Target:
private static String assemble(String easting, String northing) { return leftPad(easting, MAX_COORDINATE_LENGTH, ZERO) + leftPad(northing, MAX_COORDINATE_LENGTH, ZERO); }
Source:
<code>protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.IDP_RESPONSE); mHandler.getOperation().observe(this, new Observer<Resource<Void>>() { @Override public void onChanged(@Nullable Resource<Void> resource) { if (resource == null) { Log.w(TAG, "getSaveOperation:onChanged:null"); return; } <START> if (!resource.isUsed()) { onSaveOperation(resource); } <END> } }); Resource<Void> currentOp = mHandler.getOperation().getValue(); if (currentOp == null) { Log.d(TAG, "Launching save operation."); mHandler.saveCredentials(credential); } else { Log.d(TAG, "Save operation in progress, doing nothing."); } }</code><technical_language>1) is ResourceObserver good for this situation? 2) a usable Resource<Void> is kind of strange ... I get it</technical_language>

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.IDP_RESPONSE); mHandler.getOperation().observe(this, new VoidResourceObserver( this, R.string.fui_progress_dialog_loading) { @Override protected void onSuccess() { finish(RESULT_OK, mIdpResponse.toIntent()); } @Override protected void onFailure(@NonNull Exception e) { finish(RESULT_OK, mIdpResponse.toIntent()); } }); Resource<Void> currentOp = mHandler.getOperation().getValue(); if (currentOp == null) { Log.d(TAG, "Launching save operation."); mHandler.saveCredentials(credential); } else { Log.d(TAG, "Save operation in progress, doing nothing."); } }
Source:
<code>private void synchronizeJavaProjectInTransaction(final EclipseProject model, final IProject project, PersistentModelBuilder persistentModel, SubMonitor progress) throws JavaModelException, CoreException { progress.setWorkRemaining(8); CorePlugin.workspaceOperations().addNature(project, JavaCore.NATURE_ID, progress.newChild(1)); IJavaProject javaProject = JavaCore.create(project); OutputLocationUpdater.update(javaProject, model.getOutputLocation(), progress.newChild(1)); SourceFolderUpdater.update(javaProject, ImmutableList.copyOf(model.getSourceDirectories()), progress.newChild(1)); LibraryFilter.update(javaProject, model, progress.newChild(1)); ClasspathContainerUpdater.update(javaProject, model, progress.newChild(1)); JavaSourceSettingsUpdater.update(javaProject, model, progress.newChild(1)); GradleClasspathContainerUpdater.updateFromModel(javaProject, model, this.locationToProject.values(), persistentModel, progress.newChild(1)); <START> WtpClasspathUpdater.update(javaProject, model, this.internalGradleBuild, progress.newChild(1)); <END> CorePlugin.externalLaunchConfigurationManager().updateClasspathProviders(project); }</code><technical_language>in wtp configurator, illustrate point of configurators</technical_language>

Target:
private void synchronizeJavaProjectInTransaction(final EclipseProject model, final IProject project, PersistentModelBuilder persistentModel, SubMonitor progress) throws JavaModelException, CoreException { progress.setWorkRemaining(7); CorePlugin.workspaceOperations().addNature(project, JavaCore.NATURE_ID, progress.newChild(1)); IJavaProject javaProject = JavaCore.create(project); OutputLocationUpdater.update(javaProject, model.getOutputLocation(), progress.newChild(1)); SourceFolderUpdater.update(javaProject, ImmutableList.copyOf(model.getSourceDirectories()), progress.newChild(1)); LibraryFilter.update(javaProject, model, progress.newChild(1)); ClasspathContainerUpdater.update(javaProject, model, progress.newChild(1)); JavaSourceSettingsUpdater.update(javaProject, model, progress.newChild(1)); GradleClasspathContainerUpdater.updateFromModel(javaProject, model, this.locationToProject.values(), persistentModel, progress.newChild(1)); CorePlugin.externalLaunchConfigurationManager().updateClasspathProviders(project); }
Source:
<code>public static Map<Comparable, Double> getRankingPositionMap(final List<Comparable> unsortedArray, final boolean orderByDescending){ <START> final Comparable[] sorted = unsortedArray.toArray(new Comparable[0]); <END> Arrays.sort(sorted, new Comparator<Comparable>() { @Override public int compare(Comparable o1, Comparable o2) { if(!orderByDescending){ return o1.compareTo(o2); }else{ return -o1.compareTo(o2); } } }); final LinkedHashMap<Comparable, Double> rankingPositions = new LinkedHashMap<>(); for(int i = 0; i < sorted.length; i++){ rankingPositions.put(sorted[i], Double.valueOf(i) / unsortedArray.size()); } return rankingPositions; }</code><technical_language>Guava immutableSortedCopy sort copy list. this cleaner if applicable</technical_language>

Target:
public static Map<Comparable, Double> getRankingPositionMap(final List<Comparable> unsortedArray, final boolean orderByDescending){ List<Comparable> sortedCopy = Ordering.natural().immutableSortedCopy(unsortedArray); if(orderByDescending){ sortedCopy = Ordering.natural().reverse().immutableSortedCopy(unsortedArray); } final LinkedHashMap<Comparable, Double> rankingPositions = new LinkedHashMap<>(); for(int i = 0; i < sortedCopy.size(); i++){ rankingPositions.put(sortedCopy.get(i), Double.valueOf(i) / unsortedArray.size()); } return rankingPositions; }