auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void test_with_prefix_and_matching_pattern_and_single_host_and_replace_host() throws Exception { MockBundle bundle = new MockBundle(-1); MockComponentContext ctx = new MockComponentContext(bundle); ctx.setProperty("prefixes", new String[] { "/content/dam" }); ctx.setProperty("attributes", new String[] { "img:src" }); ctx.setProperty("host.pattern", "static.host.com"); ctx.setProperty("matchingPatterns", "img:src;(\\/content\\/dam\\/.+?\\.(png|jpg))"); <START> ctx.setProperty("replaceHost", "true"); <END> StaticReferenceRewriteTransformerFactory factory = new StaticReferenceRewriteTransformerFactory(); factory.activate(ctx); Transformer transformer = factory.createTransformer(); transformer.setContentHandler(handler); AttributesImpl imageWithJustSrc = new AttributesImpl(); imageWithJustSrc.addAttribute(null, "src", null, "CDATA", "<LINK_0>"); transformer.startElement(null, "img", null, imageWithJustSrc); verify(handler, only()).startElement(isNull(String.class), eq("img"), isNull(String.class), attributesCaptor.capture()); List<Attributes> values = attributesCaptor.getAllValues(); assertEquals("<LINK_1>", values.get(0).getValue(0)); }</code><technical_language>I matters PropertiesUtil handles this case, this a boolean true a string</technical_language>

Target:
public void test_with_prefix_and_matching_pattern_and_single_host_and_replace_host() throws Exception { MockBundle bundle = new MockBundle(-1); MockComponentContext ctx = new MockComponentContext(bundle); ctx.setProperty("prefixes", new String[] { "/content/dam" }); ctx.setProperty("attributes", new String[] { "img:src" }); ctx.setProperty("host.pattern", "static.host.com"); ctx.setProperty("matchingPatterns", "img:src;(\\/content\\/dam\\/.+?\\.(png|jpg))"); ctx.setProperty("replaceHost", true); StaticReferenceRewriteTransformerFactory factory = new StaticReferenceRewriteTransformerFactory(); factory.activate(ctx); Transformer transformer = factory.createTransformer(); transformer.setContentHandler(handler); AttributesImpl imageWithJustSrc = new AttributesImpl(); imageWithJustSrc.addAttribute(null, "src", null, "CDATA", "<LINK_0>"); transformer.startElement(null, "img", null, imageWithJustSrc); verify(handler, only()).startElement(isNull(String.class), eq("img"), isNull(String.class), attributesCaptor.capture()); List<Attributes> values = attributesCaptor.getAllValues(); assertEquals("<LINK_1>", values.get(0).getValue(0)); }
Source:
<code>public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { <START> DirCacheIterator i = state.walk.getTree(state.dirCacheTree, <END> DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && !isModified(ent, false )) return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }</code><technical_language>iterator added state object retrieved TreeWalk</technical_language>

Target:
public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.DIFFER_BY_TIMESTAMP) return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }
Source:
<code>private Document parse (String s) { try { <START> BufferedReader r = new BufferedReader (new StringReader(s)); <END> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = factory.newDocumentBuilder (); return builder.parse (new InputSource (r)); } catch (ParserConfigurationException e) { throw new IllegalArgumentException ("Parser Config Exception: " + e.getMessage (), e); } catch (SAXException e) { throw new IllegalArgumentException ("SAX Exception: " + e.getMessage (), e); } catch (IOException e) { throw new IllegalArgumentException ("IO Exception: " + e.getMessage (), e); } }</code><technical_language>close BufferedReader, this create a ResourceLeak, wrap in a try resource statement try (BufferedReader br = new BufferedReader){ .... }</technical_language>

Target:
private Document parse(String s) { try (BufferedReader r = new BufferedReader(new StringReader(s))) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(r)); } catch (ParserConfigurationException e) { throw new IllegalArgumentException("Parser Config Exception: " + e.getMessage(), e); } catch (SAXException e) { throw new IllegalArgumentException("SAX Exception: " + e.getMessage(), e); } catch (IOException e) { throw new IllegalArgumentException("IO Exception: " + e.getMessage(), e); } }
Source:
<code>private void checkPasswordStrength(String password){ <START> if(password == null){ <END> throw new IllegalArgumentException("Null password is not allowed"); } if(password.length() < 8){ throw new IllegalArgumentException("Password should be at least 8 characters long"); } if(password.length() > 128){ throw new IllegalArgumentException("Password can be up to 128 characters long"); } long satisfiedCategories = Stream.of(PASSWORD_CATEGORY_VALIDATION_PATTERNS) .filter(p -> p.matcher(password).find()) .count(); if(satisfiedCategories < 3){ throw new IllegalArgumentException( "Password must contains characters from three of the following four categories:\n" + " - Latin uppercase letters (A through Z)\n" + " - Latin lowercase letters (a through z)\n" + " - Base 10 digits (0 through 9)\n" + " - Non-alphanumeric characters such as: exclamation point (!), dollar sign ($), number sign (#), " + "or percent (%)." ); } }</code><technical_language>suggestion if (password == null) { Code style</technical_language>

Target:
private void checkPasswordStrength(String password) { if (password == null) { throw new IllegalArgumentException("Null password is not allowed"); } if (password.length() < 8) { throw new IllegalArgumentException("Password should be at least 8 characters long"); } if (password.length() > 128) { throw new IllegalArgumentException("Password can be up to 128 characters long"); } long satisfiedCategories = Stream.of(PASSWORD_CATEGORY_VALIDATION_PATTERNS) .filter(p -> p.matcher(password).find()) .count(); if (satisfiedCategories < 3) { throw new IllegalArgumentException( "Password must contain characters from three of the following four categories:\n" + " - Latin uppercase letters (A through Z)\n" + " - Latin lowercase letters (a through z)\n" + " - Base 10 digits (0 through 9)\n" + " - Non-alphanumeric characters such as: exclamation point (!), dollar sign ($), number sign (#), " + "or percent (%)." ); } }
Source:
<code>public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); JavaSonarWayProfile definition = new JavaSonarWayProfile(ruleFinder()); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getLanguage()).isEqualTo(Java.KEY); <START> List<ActiveRule> activeRules = profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY); <END> int numberOfRules = 197; assertThat(activeRules) .overridingErrorMessage("Expected " + numberOfRules + " rules for Sonar Way profile, but got " + activeRules.size() + " active rules.") .hasSize(numberOfRules); assertThat(profile.getName()).isEqualTo("Sonar way"); assertThat(validation.hasErrors()).isFalse(); }</code><technical_language>This do in this pull request. (but fine this improvement in a separate commit, need for review)</technical_language>

Target:
public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); JavaSonarWayProfile definition = new JavaSonarWayProfile(ruleFinder()); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getLanguage()).isEqualTo(Java.KEY); List<ActiveRule> activeRules = profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY); assertThat(activeRules) .overridingErrorMessage("Expected " + NUMBER_OF_RULES_IN_PROFILE + " rules for Sonar Way profile, but got " + activeRules.size() + " active rules.") .hasSize(NUMBER_OF_RULES_IN_PROFILE); assertThat(profile.getName()).isEqualTo("Sonar way"); assertThat(validation.hasErrors()).isFalse(); }
Source:
<code>public void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { <START> throw new RuntimeException(String.format("Invalid volume id %s", volumeId)); <END> } } if(clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchRemobeBricksStatusDetails()); }</code><technical_language>throw more meaningful? this query? feel in this case</technical_language>

Target:
public void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.INVALID_VOLUME_ID.toString()); } } if(clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchRemobeBricksStatusDetails()); }
Source:
<code>private <T, U extends T> Supplier<T> createSupplier(ClassLoader threadContextClassLoader, Consumer<Runnable> securityContextActionConsumer, U event, EventMetadata metadata, ObserverExceptionHandler exceptionHandler, boolean handleExceptions, Runnable notifyAction) { return () -> { ClassLoader originalCl = GetContextClassLoaderAction.INSTANCE.run(); final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); final RequestContext requestContext = requestContextHolder.get(); securityContextActionConsumer.accept(() -> { try { <START> new SetContextClassLoaderAction(threadContextClassLoader).run(); <END> requestContext.activate(); notifyAction.run(); } finally { stack.pop(); requestContext.invalidate(); requestContext.deactivate(); new SetContextClassLoaderAction(originalCl).run(); } }); if (handleExceptions) { handleExceptions(exceptionHandler); } return event; }; }</code><technical_language>Again, this work SM enabled</technical_language>

Target:
private <T, U extends T> Supplier<T> createSupplier(ClassLoader threadContextClassLoader, Consumer<Runnable> securityContextActionConsumer, U event, EventMetadata metadata, ObserverExceptionHandler exceptionHandler, boolean handleExceptions, Runnable notifyAction) { return () -> { ClassLoader originalCl = SecurityActions.getContextClassLoader(); final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); final RequestContext requestContext = requestContextHolder.get(); securityContextActionConsumer.accept(() -> { try { SecurityActions.setContextClassLoader(threadContextClassLoader); requestContext.activate(); notifyAction.run(); } finally { stack.pop(); requestContext.invalidate(); requestContext.deactivate(); SecurityActions.setContextClassLoader(originalCl); } }); if (handleExceptions) { handleExceptions(exceptionHandler); } return event; }; }
Source:
<code>public void finish() { synchronized ( lock ) { if ( state == Worker.STATE_DEAD ) { return; } state = Worker.STATE_DEAD; try { <START> final AbstractReportProcessor processor = ReportProcessorThreadHolder.getProcessor(); <END> if ( processor != null ) { processor.cancel(); } } catch ( SecurityException se ) { } } }</code><technical_language>I cancellation code moved PreviewPane. Technically location work, conceptually, if a worker, expect bound a specific runnable type. "printReportProcessor.cancel()" PreviewPane cancellation request granted. PreviewPane, direct access report-processor, need ReportProcessorThreadHolder for cancellation. This intent of code clearer. Another advantage (unnoticeable ordinary user): longer kill worker (state = STATE_DEAD), thread reused for next task</technical_language>

Target:
public void finish() { synchronized ( lock ) { if ( state == Worker.STATE_DEAD ) { return; } state = Worker.STATE_DEAD; try { this.interrupt(); } catch ( SecurityException se ) { } } }
Source:
<code>public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { List<Pattern> patterns = getPatterns(); int confidence = Alert.CONFIDENCE_MEDIUM; List<String> evidence = new ArrayList<String>(); if (msg.getResponseBody().length() > 0 && msg.getResponseHeader().isText()) { StringBuilder todoComments = new StringBuilder(); if (msg.getResponseHeader().isJavaScript()) { String[] lines = msg.getResponseBody().toString().split("\n"); for (String line : lines) { for (Pattern pattern : patterns) { if (pattern.matcher(line).find()) { todoComments.append( Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern, line)); todoComments.append("\n"); confidence = Alert.CONFIDENCE_LOW; evidence.add(line); break; } } } } else { List<Tag> tags = source.getAllTags(StartTagType.COMMENT); for (Tag tag : tags) { String tagStr = tag.toString(); for (Pattern pattern : patterns) { if (pattern.matcher(tagStr).find()) { todoComments.append( Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern, tagStr)); todoComments.append("\n"); evidence.add(tagStr); break; } } } Element el; int offset = 0; while ((el = source.getNextElement(offset, HTMLElementName.SCRIPT)) != null) { String elStr = el.toString(); for (Pattern pattern : patterns) { if (pattern.matcher(elStr).find()) { todoComments.append( Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern, elStr)); todoComments.append("\n"); confidence = Alert.CONFIDENCE_LOW; evidence.add(elStr); break; } } offset = el.getEnd(); } } <START> for (String e : evidence) { <END> this.raiseAlert(msg, id, todoComments.toString(), confidence, e); } } }</code><technical_language>IMO easier manage a single alert message</technical_language>

Target:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { List<Pattern> patterns = getPatterns(); int confidence = Alert.CONFIDENCE_MEDIUM; if (msg.getResponseBody().length() > 0 && msg.getResponseHeader().isText()) { if (msg.getResponseHeader().isJavaScript()) { String[] lines = msg.getResponseBody().toString().split("\n"); for (String line : lines) { for (Pattern pattern : patterns) { if (pattern.matcher(line).find()) { String other = Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern); confidence = Alert.CONFIDENCE_LOW; this.raiseAlert(msg, id, other, confidence, line); break; } } } } else { List<Tag> tags = source.getAllTags(StartTagType.COMMENT); for (Tag tag : tags) { String tagStr = tag.toString(); for (Pattern pattern : patterns) { if (pattern.matcher(tagStr).find()) { String other = Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern); this.raiseAlert(msg, id, other, confidence, tagStr); break; } } } Element el; int offset = 0; while ((el = source.getNextElement(offset, HTMLElementName.SCRIPT)) != null) { String elStr = el.toString(); for (Pattern pattern : patterns) { if (pattern.matcher(elStr).find()) { String other = Constant.messages.getString( MESSAGE_PREFIX + "otherinfo", pattern); confidence = Alert.CONFIDENCE_LOW; this.raiseAlert(msg, id, other, confidence, elStr); break; } } offset = el.getEnd(); } } } }
Source:
<code>public static CreateFirewallPolicy create(final String name, final String description, List<Rule.CreatePayload> rules) { <START> return new AutoValue_FirewallPolicy_CreateFirewallPolicy(name, description, rules == null ? ImmutableList.<Rule.CreatePayload>of() : rules); <END> }</code><technical_language>here. copyOf for lists present enforce immutability</technical_language>

Target:
public static CreateFirewallPolicy create(final String name, final String description, List<Rule.CreatePayload> rules) { return new AutoValue_FirewallPolicy_CreateFirewallPolicy(name, description, rules == null ? ImmutableList.<Rule.CreatePayload>of() : ImmutableList.copyOf(rules)); }
Source:
<code>public PipelinePagination(int currentPage, int totalCount, int pagingSize, String moveLink) { this.currentPage = currentPage; this.totalCount = totalCount; this.pageSize = pagingSize == 0 ? 10 : pagingSize; this.moveLink = moveLink; try { rootUrl = Hudson.getInstance().getRootUrlFromRequest(); } catch (Exception e) { <START> <END> } }</code><technical_language>logged if is crucial work. 1. fail? 2. Do need catch Exception</technical_language>

Target:
public PipelinePagination(int currentPage, int totalCount, int pagingSize, String moveLink) { this.currentPage = currentPage; this.totalCount = totalCount; this.pageSize = pagingSize == 0 ? 10 : pagingSize; this.moveLink = moveLink; this.rootUrl = Jenkins.getInstance() != null ? Jenkins.getInstance().getRootUrlFromRequest() : "/"; }
Source:
<code>public void obtainsAuthor() throws Exception { final String alias = "charlie"; final Aliases aliases = new DyBase().user(new URN("urn:test:89636")).aliases(); aliases.add(alias); final Inbox inbox = aliases.iterate().iterator().next().inbox(); <START> final Bout bout = inbox.bout(inbox.start()); <END> final Attachments attachments = bout.attachments(); final String name = "name"; attachments.create(name); final Attachment attachment = attachments.get(name); MatcherAssert.assertThat( attachment.author(), Matchers.equalTo(alias) ); attachments.delete(name); }</code><technical_language>@CarlosGines bout inlined</technical_language>

Target:
public void obtainsAuthor() throws Exception { final String alias = "charlie"; final Aliases aliases = new DyBase().user(new URN("urn:test:89636")).aliases(); aliases.add(alias); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Attachments attachments = inbox.bout(inbox.start()) .attachments(); final String name = "name"; attachments.create(name); final Attachment attachment = attachments.get(name); MatcherAssert.assertThat( attachment.author(), Matchers.equalTo(alias) ); attachments.delete(name); }
Source:
<code>void assertMutationMetrics(String tableName, int numRows, Map<String, Map<MetricType, Long>> mutationMetrics) { assertTrue("No mutation metrics present when there should have been", mutationMetrics.size() > 0); for (Map.Entry<String, Map<MetricType, Long>> entry : mutationMetrics.entrySet()) { String t = entry.getKey(); assertEquals("Table name didn't match for mutation metrics", tableName, t); Map<MetricType, Long> p = entry.getValue(); <START> assertEquals("There should have been four metrics", 5, p.size()); <END> for (Map.Entry<MetricType, Long> metric : p.entrySet()) { MetricType metricType = metric.getKey(); long metricValue = metric.getValue(); if (metricType.equals(MetricType.MUTATION_BATCH_SIZE)) { assertEquals("Mutation batch sizes didn't match!", numRows, metricValue); } else if (metricType.equals(MetricType.MUTATION_COMMIT_TIME)) { assertTrue("Mutation commit time should be greater than zero", metricValue > 0); } else if (metricType.equals(MetricType.MUTATION_BYTES)) { assertTrue("Mutation bytes size should be greater than zero", metricValue > 0); } else if (metricType.equals(MetricType.MUTATION_BATCH_FAILED_SIZE)) { assertEquals("Zero failed mutations expected", 0, metricValue); } else if (metricType.equals(MetricType.PHASE_THREE_FAILURE_SIZE)) { assertEquals("Zero failed phase 3 mutations expected", 0, metricValue); } } } }</code><technical_language>nit: in text number in place of text assigning a variable</technical_language>

Target:
void assertMutationMetrics(String tableName, int numRows, Map<String, Map<MetricType, Long>> mutationMetrics) { assertTrue("No mutation metrics present when there should have been", mutationMetrics.size() > 0); for (Map.Entry<String, Map<MetricType, Long>> entry : mutationMetrics.entrySet()) { String t = entry.getKey(); assertEquals("Table name didn't match for mutation metrics", tableName, t); Map<MetricType, Long> p = entry.getValue(); assertEquals("There should have been five metrics", 5, p.size()); for (Map.Entry<MetricType, Long> metric : p.entrySet()) { MetricType metricType = metric.getKey(); long metricValue = metric.getValue(); if (metricType.equals(MetricType.MUTATION_BATCH_SIZE)) { assertEquals("Mutation batch sizes didn't match!", numRows, metricValue); } else if (metricType.equals(MetricType.MUTATION_COMMIT_TIME)) { assertTrue("Mutation commit time should be greater than zero", metricValue > 0); } else if (metricType.equals(MetricType.MUTATION_BYTES)) { assertTrue("Mutation bytes size should be greater than zero", metricValue > 0); } else if (metricType.equals(MetricType.MUTATION_BATCH_FAILED_SIZE)) { assertEquals("Zero failed mutations expected", 0, metricValue); } else if (metricType.equals(MetricType.INDEX_COMMIT_FAILURE_SIZE)) { assertEquals("Zero failed phase 3 mutations expected", 0, metricValue); } } } }
Source:
<code><START> private void setup() throws Exception { <END> address = new ModelNode(); address.add(SUBSYSTEM, "resource-adapters"); address.add("resource-adapter", rarDeploymentName); address.protect(); ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("archive").set(rarDeploymentName); executeOperation(operation); ModelNode addr = address.clone(); addr.add("admin-objects", "ij_Pool3"); operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(addr); operation.get("jndi-name").set("java:jboss/Name3"); operation .get("class-name") .set("org.jboss.as.test.integration.jca.rar.MultipleAdminObject1Impl"); executeOperation(operation); operation = new ModelNode(); operation.get(OP).set("activate"); operation.get(OP_ADDR).set(address); executeOperation(operation); }</code><technical_language>need rollback changes done setup() clean configuration. Notice server configuration file is re-used other tests. ensure configuration backs initial state test finish, if test assertion fails</technical_language>

Target:
private ModelNode setup() throws Exception { ModelNode address = new ModelNode(); address.add(SUBSYSTEM, "resource-adapters"); address.add("resource-adapter", rarDeploymentName); address.protect(); ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("archive").set(rarDeploymentName); executeOperation(operation); ModelNode addr = address.clone(); addr.add("admin-objects", "ij_Pool3"); operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(addr); operation.get("jndi-name").set("java:jboss/Name3"); operation .get("class-name") .set("org.jboss.as.test.integration.jca.rar.MultipleAdminObject1Impl"); executeOperation(operation); operation = new ModelNode(); operation.get(OP).set("activate"); operation.get(OP_ADDR).set(address); executeOperation(operation); return address; }
Source:
<code>public Response findAll(@Auth AuthUser authUser, @QueryParam("withUsers") Optional<Boolean> withUsers) { List<Dac> dacs = new ArrayList<>(); final Boolean includeUsers = withUsers.isPresent() ? withUsers.get() : true; <START> dacs.addAll(dacService.findDacsByUser(authUser, includeUsers)); <END> return Response.ok().entity(dacs).build(); }</code><technical_language>Minor optimization. Get rid of line 46 create list line 48: suggestion List<Dac> dacs = dacService.findDacsByUser(authUser, includeUsers);</technical_language>

Target:
public Response findAll(@Auth AuthUser authUser, @QueryParam("withUsers") Optional<Boolean> withUsers) { final Boolean includeUsers = withUsers.isPresent() ? withUsers.get() : true; List<Dac> dacs = dacService.findDacsByUser(authUser, includeUsers); return Response.ok().entity(dacs).build(); }
Source:
<code>public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { pos = pos.offset(facing); ItemStack itemstack = player.getHeldItem(hand); if (!player.canPlayerEdit(pos, facing, itemstack)) return EnumActionResult.FAIL; <START> else { <END> if (worldIn.isAirBlock(pos) && NetworkHelper.getSoulNetwork(getBinding(player.getHeldItem(hand))).syphonAndDamage(player, SoulTicket.item(player.getHeldItem(hand), 100)).isSuccess()) { worldIn.playSound(player, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); worldIn.setBlockState(pos, Blocks.FIRE.getDefaultState(), 11); } else return EnumActionResult.FAIL; if (player instanceof EntityPlayerMP) CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP) player, pos, itemstack); return EnumActionResult.SUCCESS; } }</code><technical_language>Nesting this in else is unnecessary reached if if passes</technical_language>

Target:
public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { pos = pos.offset(facing); ItemStack itemstack = player.getHeldItem(hand); if (!player.canPlayerEdit(pos, facing, itemstack)) return EnumActionResult.FAIL; if (worldIn.isAirBlock(pos) && NetworkHelper.getSoulNetwork(getBinding(player.getHeldItem(hand))).syphonAndDamage(player, SoulTicket.item(player.getHeldItem(hand), 100)).isSuccess()) { worldIn.playSound(player, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); worldIn.setBlockState(pos, Blocks.FIRE.getDefaultState(), 11); } else return EnumActionResult.FAIL; if (player instanceof EntityPlayerMP) CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP) player, pos, itemstack); return EnumActionResult.SUCCESS; }
Source:
<code>private void add(AddRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { checkPermissions(request); UserDto user = getUser(dbSession, request); Optional<ComponentDto> project = searchProject(dbSession, request); <START> project.ifPresent(p -> userSession.checkComponentPermission(UserRole.USER, p)); <END> notificationUpdater.add(dbSession, request.getChannel(), request.getType(), user, project.orElse(null)); dbSession.commit(); } }</code><technical_language>perform checks project there, put this in searchProject for consistency</technical_language>

Target:
private void add(AddRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { checkPermissions(request); UserDto user = getUser(dbSession, request); Optional<ComponentDto> project = searchProject(dbSession, request); notificationUpdater.add(dbSession, request.getChannel(), request.getType(), user, project.orElse(null)); dbSession.commit(); } }
Source:
<code>public Instantiator getInstantiator(MockCreationSettings<?> settings) { <START> if (settings != null && settings.getConstructorArgs() != null) { <END> return new ConstructorInstantiator(settings.getConstructorArgs()); } else { return INSTANCE; } }</code><technical_language>A check for settings.getConstructorArgs() != null is required if check null passed MockSetting.useConstructor(Object ...args) above</technical_language>

Target:
public Instantiator getInstantiator(MockCreationSettings<?> settings) { if (settings != null && settings.getConstructorArgs() != null) { return new ConstructorInstantiator(settings.getOuterClassInstance() != null, settings.getConstructorArgs()); } else { return INSTANCE; } }
Source:
<code>public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 <START> && (lines[0].startsWith("%") && cursor <= lines[0].trim().length())) { <END> return getInterpreterCompletion(); } String replName = getRequiredReplName(buffer); if (replName != null && cursor > replName.length()) { cursor -= replName.length() + 1; } String body = getScriptBody(buffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } List completion = repl.completion(body, cursor); return completion; }</code><technical_language>Code text follow interpreter selection line.separator. For example sql %sql select * table In this case, getInterpreterCompletion() invoked if cursor is in select * table. it</technical_language>

Target:
public List<InterpreterCompletion> completion(String buffer, int cursor) { String lines[] = buffer.split(System.getProperty("line.separator")); if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) { int idx = lines[0].indexOf(' '); if (idx < 0 || (idx > 0 && cursor <= idx)) { return getInterpreterCompletion(); } } String replName = getRequiredReplName(buffer); if (replName != null && cursor > replName.length()) { cursor -= replName.length() + 1; } String body = getScriptBody(buffer); Interpreter repl = getRepl(replName); if (repl == null) { return null; } List completion = repl.completion(body, cursor); return completion; }
Source:
<code>public void addLinkedAddress(final Address address) { if (linkedAddresses == null) { linkedAddresses = PlatformDependent.hasUnsafe() ? new NonBlockingHashSet<>() : new ConcurrentHashSet<>(); } <START> assert !linkedAddresses.contains(address); <END> linkedAddresses.add(address); }</code><technical_language>1 asserts, if called wont error simply proceed. Is this a good idea, risk breaking erroring</technical_language>

Target:
public void addLinkedAddress(final Address address) { if (linkedAddresses == null) { linkedAddresses = PlatformDependent.hasUnsafe() ? new NonBlockingHashSet<>() : new ConcurrentHashSet<>(); } linkedAddresses.add(address); }
Source:
<code>public void init( PrimaryIndex... indices ) { <START> String indexCrsCode = null; <END> for (PrimaryIndex primaryindx : indices) { if (indexCrsCode == null) { if (primaryindx.getIndexModel() instanceof CustomCrsIndexModel) { indexCrsCode = ((CustomCrsIndexModel) primaryindx.getIndexModel()).getCrsCode(); } else { indexCrsCode = GeometryUtils.DEFAULT_CRS_STR; } } else { if (primaryindx.getIndexModel() instanceof CustomCrsIndexModel) { if (!indexCrsCode.equals(((CustomCrsIndexModel) primaryindx.getIndexModel()).getCrsCode())) { LOGGER.error("Multiple indices with different CRS is not supported"); throw new RuntimeException( "Multiple indices with different CRS is not supported"); } else { if (!indexCrsCode.equals(GeometryUtils.DEFAULT_CRS_STR)) { LOGGER.error("Multiple indices with different CRS is not supported"); throw new RuntimeException( "Multiple indices with different CRS is not supported"); } } } } } }</code><technical_language>is this set of code necessary all? I read assigned a local variable is unused index is coming fitToIndex this currently unnecessary</technical_language>

Target:
public void init( PrimaryIndex... indices ) { }
Source:
<code>public void testInvokeWithSpecifyService() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn(null); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20886")); <START> ProviderModel providerModel = new ProviderModel("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService", new DemoServiceImpl(), DemoService.class); <END> ApplicationModel.initProviderModel("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService", providerModel); String result = invoke.telnet(mockChannel, "echo(\"ok\")"); assertTrue(result.contains("result: \"ok\"")); }</code><technical_language>I ProviderModel providerModel = new ProviderModel(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); approach, avoid problem if class package changes in future. say</technical_language>

Target:
public void testInvokeWithSpecifyService() throws RemotingException { mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn(null); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20886")); ProviderModel providerModel = new ProviderModel(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); ApplicationModel.initProviderModel(DemoService.class.getName(), providerModel); String result = invoke.telnet(mockChannel, "DemoService.echo(\"ok\")"); assertTrue(result.contains("result: \"ok\"")); }
Source:
<code>public void end(int responseCode, Throwable throwable, Context context) { Optional<Object> spanOptional = context.getData(OPENTELEMETRY_SPAN_KEY); if (!spanOptional.isPresent()) { logger.warning("Failed to find span to end it."); return; } <START> Span span = (Span) spanOptional.get(); <END> if (span.getOptions().contains(Options.RECORD_EVENTS)) { span.setStatus(HttpTraceUtil.parseResponseStatus(responseCode, throwable)); } span.end(); }</code><technical_language>I add a guard ensure cast result in invalid cast exception. surprised a spotbugs issue pops up</technical_language>

Target:
public void end(int responseCode, Throwable throwable, Context context) { final Span span = getSpan(context); if (span == null) { return; } if (span.getOptions().contains(Options.RECORD_EVENTS)) { span.setStatus(HttpTraceUtil.parseResponseStatus(responseCode, throwable)); } span.end(); }
Source:
<code>public Downloadable createDownloadable() { <START> if (getId().equals("hudson.tasks.Maven.MavenInstaller") || getId().equals("hudson.tasks.Ant.AntInstaller")) { <END> return new Downloadable(getId()) { @Override public JSONObject reduce(List<JSONObject> jsonList) { List<ToolInstallerEntry> reducedToolEntries = new LinkedList<>(); for (JSONObject jsonToolList : jsonList) { ToolInstallerList toolInstallerList = (ToolInstallerList) JSONObject.toBean(jsonToolList, ToolInstallerList.class); reducedToolEntries.addAll(Arrays.asList(toolInstallerList.list)); } while (hasDuplicates(reducedToolEntries, "id")) { List<ToolInstallerEntry> tmpToolInstallerEntries = new LinkedList<>(); boolean processed[] = new boolean[reducedToolEntries.size()]; for (int i = 0; i < reducedToolEntries.size(); i++) { if (processed[i] == true) { continue; } ToolInstallerEntry data1 = reducedToolEntries.get(i); boolean hasDuplicate = false; for (int j = i + 1; j < reducedToolEntries.size(); j++) { ToolInstallerEntry data2 = reducedToolEntries.get(j); if (data1.id.equals(data2.id)) { hasDuplicate = true; processed[j] = true; tmpToolInstallerEntries.add(data1); break; } } if (!hasDuplicate) { tmpToolInstallerEntries.add(data1); } } reducedToolEntries = tmpToolInstallerEntries; } ToolInstallerList toolInstallerList = new ToolInstallerList(); toolInstallerList.list = new ToolInstallerEntry[reducedToolEntries.size()]; reducedToolEntries.toArray(toolInstallerList.list); JSONObject reducedToolEntriesJsonList = JSONObject.fromObject(toolInstallerList); return reducedToolEntriesJsonList; } }; } return new Downloadable(getId()); }</code><technical_language>more sense DownloadFromUrlInstaller.DescriptorImpl a reduce method (with a static helper method is this simple merge) extension for id if descriptor extends DownloadFromUrlInstaller.DescriptorImpl call reduce method fall wins... Maven Ant descriptors call static helper easy for</technical_language>

Target:
public Downloadable createDownloadable() { if (this instanceof DownloadFromUrlInstaller.DescriptorImpl) { final DownloadFromUrlInstaller.DescriptorImpl delegate = (DownloadFromUrlInstaller.DescriptorImpl)this; return new Downloadable(getId()) { public JSONObject reduce(List<JSONObject> jsonList) { if (isDefualtSchema(jsonList)) { return delegate.reduce(jsonList); } else { return super.reduce(jsonList); } } }; } return new Downloadable(getId()); }
Source:
<code>public void getFileAsString_shouldReturnTheStringContainedInFile() { try { String separator = FileSystems.getDefault().getSeparator(); File file = new File(System.getProperty("user.dir") + separator + "file"); file.createNewFile(); PrintWriter writer = new PrintWriter(file); String output = "The first line" + "\n" + "The second line"; writer.println("The first line"); writer.print("The second line"); writer.close(); assertTrue(output.equals(OpenmrsUtil.getFileAsString(file))); file.delete(); } <START> catch (Exception e) { <END> } }</code><technical_language>* a this <LINK_1> ? * Is this of <LINK_0></technical_language>

Target:
public void getFileAsString_shouldReturnTheStringContainedInFile() { try { File file = createFileInUserDirectory("file"); file.createNewFile(); PrintWriter writer = new PrintWriter(file); String output = "The first line" + "\n" + "The second line"; writer.println("The first line"); writer.print("The second line"); writer.close(); assertTrue(output.equals(OpenmrsUtil.getFileAsString(file))); file.delete(); } catch (IOException e) }
Source:
<code>public void verify_count_of_added_components() { ComponentContainer container = new ComponentContainer(); new DaoModule().configure(container); <START> assertThat(container.size()).isEqualTo(2 + 50); <END> }</code><technical_language>FYI, magic number 2 replaced constant ComponentContainer.COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER</technical_language>

Target:
public void verify_count_of_added_components() { ComponentContainer container = new ComponentContainer(); new DaoModule().configure(container); assertThat(container.size()).isEqualTo(ComponentContainer.COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER + 50); }
Source:
<code>public static void main(String[] args) throws Exception { <START> PushGateway pg = new PushGateway(args[0], args[1]); <END> g.set(42); pg.push(pushRegistry, "job"); }</code><technical_language>This throw exception if arg</technical_language>

Target:
public static void main(String[] args) throws Exception { PushGateway pg = new PushGateway(args[0]); g.set(42); pg.push(pushRegistry, "job"); }
Source:
<code>void setManagedConnection(final BaseWrapperManagedConnection mc) { this.mc = mc; if (mc != null) { trackStatements = mc.getTrackStatements(); <START> assert lockCount == 0; <END> if (lockCount > 0) { throw new IllegalStateException("Connection is still in use by another thread"); } } else { closed = true; } }</code><technical_language>remove assertion</technical_language>

Target:
void setManagedConnection(final BaseWrapperManagedConnection mc) { this.mc = mc; if (mc != null) { trackStatements = mc.getTrackStatements(); if (lockCount > 0) { throw new IllegalStateException(bundle.wrappedConnectionInUse()); } } else { closed = true; } }
Source:
<code>private static ModulePropertyDetails createProperties(DetailNode nodeLi) { final ModulePropertyDetails modulePropertyDetails = new ModulePropertyDetails(); final DetailNode propertyNameTag = getFirstChildOfType(nodeLi, JavadocTokenTypes.JAVADOC_INLINE_TAG, 0); final DetailNode propertyType = getFirstChildOfMatchingText(nodeLi, TYPE_TAG); final String propertyDesc = DESC_CLEAN.matcher( constructSubTreeText(nodeLi, propertyNameTag.getIndex() + 1, propertyType.getIndex() - 1)) .replaceAll(Matcher.quoteReplacement("")); modulePropertyDetails.setDescription(propertyDesc.trim()); modulePropertyDetails.setName(getTextFromTag(propertyNameTag)); modulePropertyDetails.setType( getTagTextFromProperty(nodeLi, getFirstChildOfMatchingText(nodeLi, TYPE_TAG))); final DetailNode validationTypeNode = getFirstChildOfMatchingText(nodeLi, VALIDATION_TYPE_TAG); if (validationTypeNode != null) { modulePropertyDetails.setValidationType(getTagTextFromProperty(nodeLi, validationTypeNode)); } final String defaultValue = getPropertyDefaultText(nodeLi); if (!"null".equals(defaultValue) <START> && !"the charset property of the parent".equals(defaultValue)) { <END> modulePropertyDetails.setDefaultValue(defaultValue); } return modulePropertyDetails; }</code><technical_language>Please extract this special default values list change this List#contains</technical_language>

Target:
private static ModulePropertyDetails createProperties(DetailNode nodeLi) { final ModulePropertyDetails modulePropertyDetails = new ModulePropertyDetails(); final Optional<DetailNode> propertyNameNode = getFirstChildOfType(nodeLi, JavadocTokenTypes.JAVADOC_INLINE_TAG, 0); DetailNode propertyNameTag = null; if (propertyNameNode.isPresent()) { propertyNameTag = propertyNameNode.get(); } final Optional<DetailNode> propertyTypeNode = getFirstChildOfMatchingText(nodeLi, TYPE_TAG); DetailNode propertyType = null; if (propertyTypeNode.isPresent()) { propertyType = propertyTypeNode.get(); } final String propertyDesc = DESC_CLEAN.matcher( constructSubTreeText(nodeLi, propertyNameTag.getIndex() + 1, propertyType.getIndex() - 1)) .replaceAll(Matcher.quoteReplacement("")); modulePropertyDetails.setDescription(propertyDesc.trim()); modulePropertyDetails.setName(getTextFromTag(propertyNameTag)); final Optional<DetailNode> typeNode = getFirstChildOfMatchingText(nodeLi, TYPE_TAG); if (typeNode.isPresent()) { modulePropertyDetails.setType(getTagTextFromProperty(nodeLi, typeNode.get())); } final Optional<DetailNode> validationTypeNodeOpt = getFirstChildOfMatchingText(nodeLi, VALIDATION_TYPE_TAG); DetailNode validationTypeNode = null; if (validationTypeNodeOpt.isPresent()) { validationTypeNode = validationTypeNodeOpt.get(); } if (validationTypeNode != null) { modulePropertyDetails.setValidationType(getTagTextFromProperty(nodeLi, validationTypeNode)); } final String defaultValue = getPropertyDefaultText(nodeLi); if (!PROPERTIES_TO_NOT_WRITE.contains(defaultValue)) { modulePropertyDetails.setDefaultValue(defaultValue); } return modulePropertyDetails; }
Source:
<code>public void testResolveFragmentWithDistro() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); <START> File index = IO.getFile("testdata/repo9/index.xml"); <END> File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file;x-whitelist=osgi.wiring.host"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (!resolution.isOK()) { fail("should NOT have failed because 'osgi.wiring.host' capablities are added to the system resource"); } Map<Resource, List<Wire>> runbundles = resolution.getRequired(); assertEquals(1, runbundles.size()); Resource resource = runbundles.entrySet() .iterator() .next() .getKey(); List<Capability> capabilities = resource.getCapabilities("osgi.identity"); assertEquals(1, capabilities.size()); assertEquals("com.liferay.osb.community.blogs.web.fragment", capabilities.get(0) .getAttributes() .get("osgi.identity")); } }</code><technical_language>is this variable for? is used</technical_language>

Target:
public void testResolveFragmentWithDistro() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file;x-whitelist=osgi.wiring.host"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (!resolution.isOK()) { fail("should NOT have failed because 'osgi.wiring.host' capablities are added to the system resource"); } Map<Resource, List<Wire>> runbundles = resolution.getRequired(); assertEquals(1, runbundles.size()); Resource resource = runbundles.entrySet() .iterator() .next() .getKey(); List<Capability> capabilities = resource.getCapabilities("osgi.identity"); assertEquals(1, capabilities.size()); assertEquals("com.liferay.osb.community.blogs.web.fragment", capabilities.get(0) .getAttributes() .get("osgi.identity")); } }
Source:
<code>protected final void registerObserve(final Request request) { if (!request.getOptions().hasBlock2() <START> || request.getOptions().getBlock2().getNum() == 0) { <END> LOG.debug("registering observe request {}", request); Token token = request.getToken(); if (token == null) { do { token = tokenGenerator.createToken(request); request.setToken(token); } while (observationStore.putIfAbsent(token, new Observation(request, null)) != null); } else { observationStore.put(token, new Observation(request, null)); } request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { failed(); } @Override protected void failed() { observationStore.remove(request.getToken()); } }); } }</code><technical_language>I feel isM is mandatory too. in other hand, translation of early negotiation in spec is M=0,NUM=0: _" influence block size in a response, requester Block2 Option initial request, giving desired size, a block number of zero M bit of zero."_</technical_language>

Target:
protected final void registerObserve(final Request request) { if (!request.getOptions().hasBlock2() || request.getOptions().getBlock2().getNum() == 0) { LOG.debug("registering observe request {}", request); Token token = request.getToken(); if (token == null) { do { token = tokenGenerator.createToken(true); request.setToken(token); } while (observationStore.putIfAbsent(token, new Observation(request, null)) != null); } else { observationStore.put(token, new Observation(request, null)); } request.addMessageObserver(new MessageObserverAdapter() { @Override public void onCancel() { failed(); } @Override protected void failed() { observationStore.remove(request.getToken()); } }); } }
Source:
<code>private void broadcastExcept(String noteId, Message m, NotebookSocket exclude) { synchronized (noteSocketMap) { List<NotebookSocket> socketLists = noteSocketMap.get(noteId); if (socketLists == null || socketLists.size() == 0) { return; } LOG.debug("SEND >> " + m.op); <START> broadcastToWatchers(noteId, StringUtils.EMPTY, m); <END> for (NotebookSocket conn : socketLists) { if (exclude.equals(conn)) { continue; } try { conn.send(serializeMessage(m)); } catch (IOException e) { LOG.error("socket error", e); } } } }</code><technical_language>This one, too. move if statement above</technical_language>

Target:
private void broadcastExcept(String noteId, Message m, NotebookSocket exclude) { synchronized (noteSocketMap) { broadcastToWatchers(noteId, StringUtils.EMPTY, m); List<NotebookSocket> socketLists = noteSocketMap.get(noteId); if (socketLists == null || socketLists.size() == 0) { return; } LOG.debug("SEND >> " + m.op); for (NotebookSocket conn : socketLists) { if (exclude.equals(conn)) { continue; } try { conn.send(serializeMessage(m)); } catch (IOException e) { LOG.error("socket error", e); } } } }
Source:
<code>public void registerConsumers(int numConsumers) { if (registered.get()) { if (isDebug) log.info("Master thread locks at RC"); <START> while (registered.get()) { <END> LockSupport.parkNanos(100L); } if (isDebug) log.info("Master thread unlocks at RC"); } if (externalSource != null && externalSource instanceof Registerable) ((Registerable) externalSource).registerConsumers(numConsumers); currentConsumers.set(numConsumers); registered.set(true); }</code><technical_language>a *little* worried deadlock here. If calls (registerConsumers etc) throws exception, waiting</technical_language>

Target:
public void registerConsumers(int numConsumers) { if (registered.get()) { if (isDebug) log.info("Master thread locks at RC"); while (registered.get()) { LockSupport.parkNanos(100L); if (throwable.isTriggered()) throw new RuntimeException(throwable.get()); } if (isDebug) log.info("Master thread unlocks at RC"); } if (externalSource != null && externalSource instanceof Registerable) ((Registerable) externalSource).registerConsumers(numConsumers); currentConsumers.set(numConsumers); registered.set(true); }