auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void reopenCase(String caseId, String containerId, String caseDefinitionId, String payload, String marshallingType) { <START> containerId = context.getContainer(containerId, LatestContainerLocator.get()).getContainerId(); <END> CaseDefinition caseDef = caseRuntimeDataService.getCase(containerId, caseDefinitionId); if( caseDef == null ) { throw new IllegalStateException("Unable to find case '" + caseDefinitionId + "' in container " + containerId); } logger.debug("About to unmarshal data from payload: '{}'", payload); Map<String, Object> data = marshallerHelper.unmarshal(containerId, payload, marshallingType, Map.class); caseService.reopenCase(caseId, containerId, caseDefinitionId, data); logger.debug("Case successfully reopened", caseId); }</code><technical_language>a question, ByCaseIdContainerLocator? case file objects specific container version</technical_language>

Target:
public void reopenCase(String caseId, String containerId, String caseDefinitionId, String payload, String marshallingType) { containerId = context.getContainer(containerId, new ByCaseIdContainerLocator(caseId)).getContainerId(); CaseDefinition caseDef = caseRuntimeDataService.getCase(containerId, caseDefinitionId); if( caseDef == null ) { throw new IllegalStateException("Unable to find case '" + caseDefinitionId + "' in container " + containerId); } logger.debug("About to unmarshal data from payload: '{}'", payload); Map<String, Object> data = marshallerHelper.unmarshal(containerId, payload, marshallingType, Map.class); caseService.reopenCase(caseId, containerId, caseDefinitionId, data); logger.debug("Case successfully reopened", caseId); }
Source:
<code>public void test_no_usages() throws Exception { highlight("<?php $a = 1; "); <START> checkNoSymbolExists(1, 7); END> checkSymbolExistence(1, 8, true); checkSymbolExistence(1, 9, true); checkNoSymbolExists(1, 10); checkSymbolReferences(1, 8, new LinkedList<>()); }</code><technical_language>@dbmeneses point of changes? (did tests fail before? including in this commit headers update?)</technical_language>

Target:
public void test_no_usages() throws Exception { highlight("<?php $a = 1; "); checkNoSymbolExists(1, 7); checkSymbolExistence(1, 8); checkSymbolExistence(1, 9); checkNoSymbolExists(1, 10); checkSymbolReferences(1, 8, new LinkedList<>()); }
Source:
<code>public DataElementMetadata extract(Element element) throws InvalidElementException { if (element.getKind() != ElementKind.CLASS) { throw new InvalidElementException( "Element must be class, found " + element.toString() ); } AnnotatedElement helper = new AnnotatedElement(element, elementUtils); if (!helper.hasAnnotation(DataElement.class)) { throw new InvalidElementException( "Element is not annotated with DataElement" ); } Fields fields = new Fields(); fields.collect(DefaultFields.get()); fields.collect(extractFields(element)); <START> return DataElementMetadata.builder() .name(extractName(helper)) .packageName(extractPackageName(element)) .fields(fields) .build(); <END> }</code><technical_language>This debugger sad. change this: java DataElementMetadata data = DataElementMetadata.builder() .name(extractName(helper)) .packageName(extractPackageName(element)) .fields(fields) .build(); return data;</technical_language>

Target:
public DataElementMetadata extract(Element element) throws InvalidElementException { if (element.getKind() != ElementKind.CLASS) { throw new InvalidElementException( "Element must be class, found " + element.toString() ); } if (!hasAnnotation(element, DataElement.class)) { throw new InvalidElementException( "Element is not annotated with DataElement" ); } Fields fields = new Fields(); fields.collect(DefaultFields.get()); fields.collect(extractFields(element)); DataElementMetadata data = DataElementMetadata.builder() .name(extractName(element)) .packageName(extractPackageName(element)) .fields(fields) .build(); return data; }
Source:
<code>public boolean equals( final Object obj ) { if( obj instanceof AESharedItemStack ) { final AESharedItemStack other = (AESharedItemStack) obj; Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" ); Preconditions.checkArgument( other.getDefinition().getCount() != 1, "ItemStack#getCount() has to be 1" ); <START> if( this.itemStack == other.itemStack ) <END> { return true; } return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack ); } return false; }</code><technical_language>![CRITICAL](<LINK_0> 'Severity: CRITICAL') Define a constant instead of duplicating this literal "ItemStack#getCount() 1" 6 times. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public boolean equals( final Object obj ) { if( obj instanceof AESharedItemStack ) { final AESharedItemStack other = (AESharedItemStack) obj; Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" ); Preconditions.checkArgument( other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" ); if( this.itemStack == other.itemStack ) { return true; } return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack ); } return false; }
Source:
<code>public static List<String> getAggregateFunctionInputVariables(final String formula, final boolean isWrapped) { final List<String> aggregateInputVariables = new ArrayList<>(); <START> final String agggregateRegex = "(?i)" + DerivedVariableUtils.AGGREGATE_FUNCTIONS + "\\((\\{\\{(\\w+)}})(,[\\s]?\\{\\{(\\w+)}})*\\)"; <END> Pattern aggregatePattern = Pattern.compile(agggregateRegex); Matcher aggregateMatcher = aggregatePattern.matcher(formula); while (aggregateMatcher.find()) { final String aggregateString = aggregateMatcher.group(); final String aggregateInputRegex = "(\\{\\{\\w+}})"; final Pattern aggregateInputPattern = Pattern.compile(aggregateInputRegex); final Matcher aggregateInputMatcher = aggregateInputPattern.matcher(aggregateString); while(aggregateInputMatcher.find()) { String inputVariable = aggregateInputMatcher.group().replaceAll("(\\{)","").replaceAll("}",""); inputVariable = isWrapped? DerivedVariableUtils.wrapTerm(inputVariable) : inputVariable; aggregateInputVariables.add(inputVariable); } } return aggregateInputVariables; }</code><technical_language>Extract agggregateRegex aggregatePattern constants</technical_language>

Target:
public static List<String> getAggregateFunctionInputVariables(final String formula, final boolean isWrapped) { final List<String> aggregateInputVariables = new ArrayList<>(); Pattern aggregatePattern = Pattern.compile(AGGREGATE_REGEX); Matcher aggregateMatcher = aggregatePattern.matcher(formula); while (aggregateMatcher.find()) { final String aggregateString = aggregateMatcher.group(); final Pattern aggregateInputPattern = Pattern.compile(AGGREGATE_INPUT_REGEX); final Matcher aggregateInputMatcher = aggregateInputPattern.matcher(aggregateString); while(aggregateInputMatcher.find()) { String inputVariable = aggregateInputMatcher.group().replaceAll("(\\{)","").replaceAll("}",""); inputVariable = isWrapped? DerivedVariableUtils.wrapTerm(inputVariable) : inputVariable; aggregateInputVariables.add(inputVariable); } } return aggregateInputVariables; }
Source:
<code>public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException { final int size = collection == null ? NULL_VALUE : collection.size(); <START> marshallInt(out, size); <END> if (size <= 0) { return; } for (Integer integer : collection) { out.writeInt(integer); } }</code><technical_language>implementation of marshallInt, kind of wrong call that; marshallSize more appropriate. Personally marshal empty null collections/arrays way, of time null is a valid is considered equivalent empty collection. reading, Collections.emptyList() instead</technical_language>

Target:
public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException { final int size = collection == null ? NULL_VALUE : collection.size(); marshallSize(out, size); if (size <= 0) { return; } for (Integer integer : collection) { out.writeInt(integer); } }
Source:
<code>public void testEndOfYearDates() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); cal.set(2015, 11, 30, 12, 0, 0); Date date = cal.getTime(); assertEquals("30/12/2015", TimeHelper.formatDate(TimeHelper.convertDateToLocalDateTime(date))); assertEquals("Wed, 30 Dec, 2015", TimeHelper.formatDateForSessionsForm(TimeHelper.convertDateToLocalDateTime(date))); <START> assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(TimeHelper.convertDateToLocalDateTime(date))); <END> assertEquals("Wed, 30 Dec 2015, 12:00 NOON UTC+0000", TimeHelper.formatDateTimeForSessions( TimeHelper.convertDateToInstant(date), ZoneId.of("UTC"))); assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage( TimeHelper.convertDateToLocalDateTime(date))); }</code><technical_language>avoid transition methods. Refer patch - touches lines completely removes Calendar</technical_language>

Target:
public void testEndOfYearDates() { LocalDateTime ldt = LocalDateTime.of(2015, Month.DECEMBER, 30, 12, 0); assertEquals("30/12/2015", TimeHelper.formatDate(ldt)); assertEquals("Wed, 30 Dec, 2015", TimeHelper.formatDateForSessionsForm(ldt)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(ldt)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON UTC+0000", TimeHelper.formatDateTimeForSessions(ldt.toInstant(ZoneOffset.UTC), ZoneId.of("UTC"))); assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage(ldt)); }
Source:
<code>public void initialize(String directoryProviderName, Properties properties, BuildContext context) { this.properties = properties; this.directoryProviderName = directoryProviderName; sourceDir = DirectoryProviderHelper.getSourceDirectoryPath( directoryProviderName, properties, true ); log.debugf( "Source directory: %s", sourceDir ); indexDir = DirectoryHelper.getVerifiedIndexPath( directoryProviderName, properties, true ); log.debugf( "Index directory: %s", indexDir ); try { <START> indexName = indexDir.toString(); <END> directory = DirectoryProviderHelper.createFSIndex( indexDir, properties, context.getServiceManager() ); } catch (IOException e) { throw new SearchException( "Unable to initialize index: " + directoryProviderName, e ); } copyChunkSize = DirectoryProviderHelper.getCopyBufferSize( directoryProviderName, properties ); current = 0; }</code><technical_language>I remove indexName altogether indexDir logging. clearer in opinion. If worried performance, UnixPath.toString is cached internally, pretty other platforms. important, if feel it..</technical_language>

Target:
public void initialize(String directoryProviderName, Properties properties, BuildContext context) { this.properties = properties; this.directoryProviderName = directoryProviderName; sourceDir = DirectoryProviderHelper.getSourceDirectoryPath( directoryProviderName, properties, true ); log.debugf( "Source directory: %s", sourceDir ); indexDir = DirectoryHelper.getVerifiedIndexPath( directoryProviderName, properties, true ).normalize(); log.debugf( "Index directory: %s", indexDir ); try { directory = DirectoryProviderHelper.createFSIndex( indexDir, properties, context.getServiceManager() ); } catch (IOException e) { throw new SearchException( "Unable to initialize index: " + directoryProviderName, e ); } DirectoryProviderHelper.getCopyBufferSize( directoryProviderName, properties ); current = 0; }
Source:
<code>public boolean offer( PooledConnection pooledConnection ) { <START> boolean offer = queue.offer( pooledConnection ); <END> if ( offer ) { acquiredConnections.remove( pooledConnection ); } return offer; }</code><technical_language>order remove acquiredConn, put queue avid scenario happening: T1: queue.offer(connA) T2: acquire() -> get connA // connA = queue.poll, acquiredConn.Add(connA) T1: acquiredConn.remove(connA) NOTE: _Remove first, add back_. This rule applies acquire</technical_language>

Target:
public boolean offer( PooledConnection pooledConnection ) { acquiredConnections.remove( pooledConnection ); boolean offer = queue.offer( pooledConnection ); if (!offer) { pooledConnection.dispose(); } if (isTerminating.get()) { PooledConnection poll = queue.poll(); if (poll != null) { poll.dispose(); } } return offer; }
Source:
<code>private SimpleDigestPassword createSimpleDigestPasswordTable(String algorithm, String userName, String userPassword) throws Exception { Connection connection = null; Statement statement = null; PreparedStatement preparedStatement = null; try { <START> connection = this.dataSource.getConnection(); <END> statement = connection.createStatement(); statement.executeUpdate("DROP TABLE IF EXISTS user_simple_digest_password"); statement.executeUpdate("CREATE TABLE user_simple_digest_password ( id INTEGER IDENTITY, name VARCHAR(100), digest OTHER)"); EncryptablePasswordSpec eps = new EncryptablePasswordSpec(userPassword.toCharArray(), null); PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm); SimpleDigestPassword tsdp = (SimpleDigestPassword) passwordFactory.generatePassword(eps); preparedStatement = connection.prepareStatement("INSERT INTO user_simple_digest_password (name, digest) VALUES (?, ?)"); preparedStatement.setString(1, userName); preparedStatement.setBytes(2, tsdp.getDigest()); preparedStatement.execute(); return tsdp; } finally { safeClose(preparedStatement); safeClose(statement); safeClose(connection); } }</code><technical_language>I general this kind of try-with-resources</technical_language>

Target:
private SimpleDigestPassword createSimpleDigestPasswordTable(String algorithm, String userName, String userPassword) throws Exception { try ( Connection connection = this.dataSource.getConnection(); Statement statement = connection.createStatement(); ) { statement.executeUpdate("DROP TABLE IF EXISTS user_simple_digest_password"); statement.executeUpdate("CREATE TABLE user_simple_digest_password ( id INTEGER IDENTITY, name VARCHAR(100), digest OTHER)"); } try ( Connection connection = this.dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO user_simple_digest_password (name, digest) VALUES (?, ?)"); ) { EncryptablePasswordSpec eps = new EncryptablePasswordSpec(userPassword.toCharArray(), null); PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm); SimpleDigestPassword tsdp = (SimpleDigestPassword) passwordFactory.generatePassword(eps); preparedStatement.setString(1, userName); preparedStatement.setBytes(2, tsdp.getDigest()); preparedStatement.execute(); return tsdp; } }
Source:
<code>public void returnsAnEmptyResponseBody() throws IOException { new FtRemote( new TkEmpty() ).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .body().set("returnsAnEmptyResponseBody").back() .fetch() .as(RestResponse.class) <START> .assertBody(new IsEqual<>("HTTP/1.1 200 OK\r\n\r\n")) <END> .assertStatus(HttpURLConnection.HTTP_OK); } } ); }</code><technical_language>@paulodamaso a head of response, body. test method name response body empty</technical_language>

Target:
public void returnsAnEmptyResponseBody() throws IOException { new FtRemote( new TkEmpty() ).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .body().set("returnsAnEmptyResponseBody").back() .fetch() .as(RestResponse.class) .assertBody(new IsEqual<>("")) .assertStatus(HttpURLConnection.HTTP_OK); } } ); }
Source:
<code>public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); if (processingRole == null) { processingRole = processRoleStack.peek(); } processRoleStack.push(processingRole); final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); <START> final DitaClass cls = atts.getValue(ATTRIBUTE_NAME_CLASS) != null ? new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS)) : null; <END> classes.addFirst(cls); if (chunkLevel > 0) { chunkLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if (MAP_TOPICREF.matches(classValue)) { parseAttribute(atts); } getContentHandler().startElement(uri, localName, qName, atts); }</code><technical_language>This DitaClass.isValid method DitaClass constructor perform validation return a null</technical_language>

Target:
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); if (processingRole == null) { processingRole = processRoleStack.peek(); } processRoleStack.push(processingRole); final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); final DitaClass cls = atts.getValue(ATTRIBUTE_NAME_CLASS) != null ? new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS)) : new DitaClass(""); if (cls.isValid()) { classes.addFirst(cls); }else { classes.addFirst(null); } if (chunkLevel > 0) { chunkLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if (MAP_TOPICREF.matches(classValue)) { parseAttribute(atts); } getContentHandler().startElement(uri, localName, qName, atts); }
Source:
<code>public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { Any23Parser parser = null; try { String htmlContent = new String(content.getContent(), Charset.forName("UTF-8")); parser = new Any23Parser(content.getUrl(), htmlContent); } catch (TripleHandlerException e) { throw new RuntimeException("Error running Any23 parser: " + e.getMessage()); } Set<String> triples = parser.getTriples(); StringBuilder sb = new StringBuilder(); Parse parse = parseResult.get(content.getUrl()); Metadata metadata = parse.getData().getParseMeta(); for (String triple : triples) { <START> sb.append(triple); <END> sb.append("\t"); } metadata.add(ANY23_TRIPLES, sb.toString()); return parseResult; }</code><technical_language>Previously discussed agreed this optional solution for associating triples Metadata. I agree that. need of a more efficient manner for persisting triples</technical_language>

Target:
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { String[] extractorNames = conf.getStrings(ANY_23_EXTRACTORS_CONF,"html-head-meta"); Any23Parser parser; try { String htmlContent = new String(content.getContent(), Charset.forName("UTF-8")); parser = new Any23Parser(content.getUrl(), htmlContent, extractorNames); } catch (TripleHandlerException e) { throw new RuntimeException("Error running Any23 parser: " + e.getMessage()); } Set<String> triples = parser.getTriples(); Parse parse = parseResult.get(content.getUrl()); Metadata metadata = parse.getData().getParseMeta(); for (String triple : triples) { metadata.add(ANY23_TRIPLES, triple); } return parseResult; }
Source:
<code>public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { if (DISABLE) { return; <START> } <END> String imageId = record.getImageId(); Fingerprint f = forImage(run, imageId); synchronized (f) { Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); DockerFingerprintAction.addToRun(f, imageId, run); bc.commit(); } finally { bc.abort(); } } }</code><technical_language>sense add logging FINE INFO levels</technical_language>

Target:
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { if (DISABLE) { LOGGER.info("Recording of fingerprints is disabled, no RUN fingerprint record will be made."); return; } String imageId = record.getImageId(); Fingerprint f = forImage(run, imageId); synchronized (f) { Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); DockerFingerprintAction.addToRun(f, imageId, run); bc.commit(); } finally { bc.abort(); } } }
Source:
<code>public void myDiffPreferences(AsyncCallback<AccountDiffPreference> callback) { run(callback, new Action<AccountDiffPreference>() { @Override public AccountDiffPreference run(ReviewDb db) throws OrmException, Failure, <START> NoSuchProjectException, NoSuchGroupException { <END> return db.accountDiffPreferences().get(currentUser.get().getAccountId()); } }); }</code><technical_language>exceptions throw here. Copy paste error</technical_language>

Target:
public void myDiffPreferences(AsyncCallback<AccountDiffPreference> callback) { run(callback, new Action<AccountDiffPreference>() { @Override public AccountDiffPreference run(ReviewDb db) throws OrmException { return currentUser.get().getAccountDiffPreference(); } }); }
Source:
<code>protected PropertyValue getSplitTaskExecutorPropertyValue(BeanDefinitionRegistry beanDefinitionRegistry) { PropertyValue propertyValue; if (hasBeanDefinition(beanDefinitionRegistry, JSR_352_SPLIT_TASK_EXECUTOR_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new RuntimeBeanReference(JSR_352_SPLIT_TASK_EXECUTOR_NAME)); } else if (hasBeanDefinition(beanDefinitionRegistry, TASK_EXECUTOR_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new RuntimeBeanReference(TASK_EXECUTOR_NAME)); } else { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new SimpleAsyncTaskExecutor()); } <START> <END> return propertyValue; }</code><technical_language>bean names for this</technical_language>

Target:
protected PropertyValue getSplitTaskExecutorPropertyValue(BeanDefinitionRegistry beanDefinitionRegistry) { PropertyValue propertyValue; if (hasBeanDefinition(beanDefinitionRegistry, JSR_352_SPLIT_TASK_EXECUTOR_BEAN_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_PROPERTY_NAME, new RuntimeBeanReference(JSR_352_SPLIT_TASK_EXECUTOR_BEAN_NAME)); } else { propertyValue = new PropertyValue(TASK_EXECUTOR_PROPERTY_NAME, new SimpleAsyncTaskExecutor()); } return propertyValue; }
Source:
<code>void subscribersOf() { ImmutableSet<SubscriberMethod> methods = subscriberClass.subscribersOf( EventClass.from(SpeakerJoined.class), EmptyClass.instance()); assertThat(methods).hasSize(1); <START> SubscriberMethod actual = methods.asList() <END> .get(0); assertThat(actual.rawMethod()) .isEqualTo(getMethod(ConferenceProgram.class, "addSpeaker")); }</code><technical_language>matter all, asList copies content of set creates a new array fly well. methods.iterator().next() for scenarios</technical_language>

Target:
void subscribersOf() { ImmutableSet<SubscriberMethod> methods = subscriberClass.subscribersOf( EventClass.from(SpeakerJoined.class), EmptyClass.instance()); assertThat(methods).hasSize(1); SubscriberMethod actual = getFirst(methods, null); assertThat(actual.rawMethod()) .isEqualTo(getMethod(ConferenceProgram.class, "addSpeaker")); }
Source:
<code>public List<InfoInsightCards> getGenericInsightCards( @Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("category") final String value) { try { final InsightCard.Category category = InsightCard.Category.fromString(value); final List<InfoInsightCards> cards = trendsInsightsDAO.getGenericInsightCardsByCategory(category.toString().toLowerCase()); <START> final DateTime readDate = DateTime.now(DateTimeZone.UTC).plusDays(1); <END> LOGGER.debug("action=insight_detail account_id={} category={} readdate={}", accessToken.accountId, category, readDate); return cards; } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }</code><technical_language>do need add day readDate</technical_language>

Target:
public List<InfoInsightCards> getGenericInsightCards( @Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("category") final String value) { try { final InsightCard.Category category = InsightCard.Category.fromString(value); final List<InfoInsightCards> cards = trendsInsightsDAO.getGenericInsightCardsByCategory(category.toString().toLowerCase()); final DateTime readDate = DateTime.now(DateTimeZone.UTC); LOGGER.debug("action=insight_detail account_id={} category={} readdate={}", accessToken.accountId, category, readDate); return cards; } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }
Source:
<code>private void runTestPreservePath(Boolean preservePathOnForward) throws Exception { setPreservePathOnForward(preservePathOnForward); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url.toString() + "/test?path="+ URLEncoder.encode(tempDir)); HttpResponse response = httpclient.execute(httpget); long end = System.currentTimeMillis() + TIMEOUT; File file = new File(tempDir + "/output.txt"); while (!file.exists() && System.currentTimeMillis() < end) { Thread.sleep(100); } <START> Assert.assertTrue(file + " was not created within the timeout", file.exists()); <END> final String expectedServletPath; final String expectedRequestURL; if (preservePathOnForward != null && preservePathOnForward) { expectedServletPath = "/test"; expectedRequestURL = url + "/test"; } else{ expectedServletPath = "/preserve-path.jsp"; expectedRequestURL = url + "preserve-path.jsp"; } final String expectedRequestURI = new URL(expectedRequestURL).getPath(); try (BufferedReader r = new BufferedReader(new FileReader(file))) { String servletPath = r.readLine(); Assert.assertEquals("servletPath: " + expectedServletPath, servletPath); String requestUrl = r.readLine(); Assert.assertEquals("requestUrl: " + expectedRequestURL, requestUrl); String requestUri = r.readLine(); Assert.assertEquals("requestUri: " + expectedRequestURI, requestUri); } }</code><technical_language>Based execution machine, enough time for server complete write 'output.txt' file content is checked - I enforce longer sleep (5sec), tests pass successfully for me</technical_language>

Target:
private void runTestPreservePath(Boolean preservePathOnForward) throws Exception { setPreservePathOnForward(preservePathOnForward); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url.toString() + "/test?path="+ URLEncoder.encode(tempDir)); HttpResponse response = httpclient.execute(httpget); long end = System.currentTimeMillis() + TIMEOUT; File file = new File(tempDir + "/output.txt"); while ((!file.exists() || file.length() == 0) && System.currentTimeMillis() < end) { Thread.sleep(100); } Assert.assertTrue(file + " was not created within the timeout", file.exists()); Assert.assertTrue(file + " is empty", file.length() > 0); final String expectedServletPath; final String expectedRequestURL; if (preservePathOnForward != null && preservePathOnForward) { expectedServletPath = "/test"; expectedRequestURL = url + "/test"; } else{ expectedServletPath = "/preserve-path.jsp"; expectedRequestURL = url + "preserve-path.jsp"; } final String expectedRequestURI = new URL(expectedRequestURL).getPath(); try (BufferedReader r = new BufferedReader(new FileReader(file))) { String servletPath = r.readLine(); Assert.assertEquals("servletPath: " + expectedServletPath, servletPath); String requestUrl = r.readLine(); Assert.assertEquals("requestUrl: " + expectedRequestURL, requestUrl); String requestUri = r.readLine(); Assert.assertEquals("requestUri: " + expectedRequestURI, requestUri); } }
Source:
<code><START> public void stop() throws InterruptedException { <END> if (containerId.isPresent()) { try { docker.stopContainer(containerId.get(), SECONDS_TO_WAIT_BEFORE_KILL); } catch (DockerException e) { log.warn("Stopping image failed", containerId.get(), e); } } }</code><technical_language>rename this shutDown called covers stopAsync.awaitTerminated</technical_language>

Target:
public void stop() throws InterruptedException { if (containerId.isPresent()) { final String container = containerId.get(); stopAsync().awaitTerminated(); try { docker.stopContainer(container, SECONDS_TO_WAIT_BEFORE_KILL); } catch (DockerException e) { log.warn("Stopping container failed", container, e); } } }
Source:
<code>public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { <START> final BucketResult result = resultsIterator.next(); <END> DoubleType.DOUBLE.writeDouble( entryBuilder, result.threshold); } out.closeEntry(); }</code><technical_language>Same, remove final</technical_language>

Target:
public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { BucketResult result = resultsIterator.next(); DoubleType.DOUBLE.writeDouble( entryBuilder, result.getThreshold()); } out.closeEntry(); }
Source:
<code>public Optional<? extends Style> loadStyle(final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, final String styleString) { if (styleString != null) { for (StyleParserPlugin plugin : this.plugins) { try { Optional<? extends Style> style = plugin.parseStyle( configuration, clientHttpRequestFactory, styleString); if (style.isPresent()) { if (LOGGER.isDebugEnabled()) { try { final SLDTransformer transformer = new SLDTransformer(); final StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); final UserLayer userLayer = styleFactory.createUserLayer(); userLayer.addUserStyle(style.get()); final StyledLayerDescriptor sld = styleFactory.createStyledLayerDescriptor(); sld.addStyledLayer(userLayer); LOGGER.debug("Loaded style from: \n\n '{}': \n\n{}", <START> styleString, transformer.transform(sld)); <END> } catch (Exception e) { LOGGER.debug(String.format("Loaded style from: \n\n '%s' \n\n<Unable to " + "transform it to xml>: %s", styleString, e), e); } } return style; } } catch (Throwable t) { throw ExceptionUtils.getRuntimeException(t); } } } return Optional.absent(); }</code><technical_language>I guess transformer.transform is costly. I remove if in case..</technical_language>

Target:
public Optional<? extends Style> loadStyle(final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, final String styleString) { if (styleString != null) { for (StyleParserPlugin plugin : this.plugins) { try { Optional<? extends Style> style = plugin.parseStyle( configuration, clientHttpRequestFactory, styleString); if (style.isPresent()) { if (LOGGER.isDebugEnabled()) { try { final SLDTransformer transformer = new SLDTransformer(); final StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); final UserLayer userLayer = styleFactory.createUserLayer(); userLayer.addUserStyle(style.get()); final StyledLayerDescriptor sld = styleFactory.createStyledLayerDescriptor(); sld.addStyledLayer(userLayer); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Loaded style from: \n\n '{}': \n\n{}", styleString, transformer.transform(sld)); } } catch (Exception e) { LOGGER.debug(String.format("Loaded style from: \n\n '%s' \n\n<Unable to " + "transform it to xml>: %s", styleString, e), e); } } return style; } } catch (Throwable t) { throw ExceptionUtils.getRuntimeException(t); } } } return Optional.absent(); }
Source:
<code>private String getMissingInherritNamespaces(final String text) { if (text == null) { return ""; } final String namespaces = getNamespacesFromNamespaceToken(text); final String[] containedNamespaces = namespaces == null ? new String[0] : namespaces.split(" "); <START> final StringBuilder sb = new StringBuilder(); <END> boolean first = true; for (String rn : rootTokenNamespaces) { boolean nsExists = false; for (String cn : containedNamespaces) { if (rn.equals(cn)) { nsExists = true; first = false; break; } } if (!nsExists) { sb.append(first ? rn : " " + rn); first = false; } } return sb.toString(); }</code><technical_language>CollectionStringBuilder Camel add a bunch of stuff a separator deals "first" issue etc</technical_language>

Target:
private String getMissingInherritNamespaces(final String text) { final StringBuilder sb = new StringBuilder(); if (text != null) { boolean first = true; final String[] containedNamespaces = getNamespacesFromNamespaceTokenSplitter(text); for (final String rn : rootTokenNamespaces) { boolean nsExists = false; for (final String cn : containedNamespaces) { if (rn.equals(cn)) { nsExists = true; if (first) { first = false; } break; } } if (!nsExists) { sb.append(first ? rn : NAMESPACE_SEPERATOR + rn); if (first) { first = false; } } } } return sb.toString(); }
Source:
<code>public KeyValuePairValidation() { <START> this.allowAlsoKey = false; <END> }</code><technical_language>Nit-pick: more consistent constructor behavior, prefer do this(false)</technical_language>

Target:
public KeyValuePairValidation() { this(false); }
Source:
<code><START> public void setActive(boolean isActive) { <END> if (!isActive) { logger.debug(Thread.currentThread().getStackTrace().toString()); } this.isActive = isActive; }</code><technical_language>If isActive() returns true, setActive() a noop. (even *private* property isActive removed)</technical_language>

Target:
public void setActive(boolean isActive)
Source:
<code>public void testCacheUsesCacheManagerClassLoaderForDefaultURI() { CachingProvider cachingProvider = Caching.getCachingProvider(); LimitedClassLoader limitedClassLoader = new LimitedClassLoader(cachingProvider.getDefaultClassLoader()); CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), limitedClassLoader); <START> MutableConfiguration<Object, Object> configuration = new MutableConfiguration<Object, Object>().setStoreByValue(true); <END> Cache<Object, Object> cache = cacheManager.createCache("test", configuration); cache.put(1L, new Customer(1L)); try { cache.get(1L); fail("Expected AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), is("No com.pany here")); } }</code><technical_language>This change brings matches default. get rid of it</technical_language>

Target:
public void testCacheUsesCacheManagerClassLoaderForDefaultURI() { CachingProvider cachingProvider = Caching.getCachingProvider(); LimitedClassLoader limitedClassLoader = new LimitedClassLoader(cachingProvider.getDefaultClassLoader()); CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), limitedClassLoader); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<Object, Object>(); Cache<Object, Object> cache = cacheManager.createCache("test", configuration); cache.put(1L, new Customer(1L)); try { cache.get(1L); fail("Expected AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), is("No com.pany here")); } }
Source:
<code>public CompletableFuture<Void> unlock() { log.tracef("unlock called from %s", originator); CompletableFuture<Void> unlockRequest = new CompletableFuture<>(); if (isChangeViewUnlockInProgress()) { <START> pendingUnlocks.offer(new UnlockRequestHolder(originator, unlockRequest)); <END> } else { readWriteMap.eval(lockKey, new UnlockFunction(originator)).whenComplete((unlockResult, ex) -> { if (ex == null) { log.tracef("Unlock result for %s is %b", originator, unlockResult); unlockRequest.complete(null); } else { unlockRequest.completeExceptionally(handleException(ex)); } }); } return unlockRequest; }</code><technical_language>if forceUnlockForLeavingMembers decrements viewChangeUnlockHappening *and* calls retryPendingUnlocks() lines 407 408</technical_language>

Target:
public CompletableFuture<Void> unlock() { log.tracef("unlock called from %s", originator); CompletableFuture<Void> unlockRequest = new CompletableFuture<>(); readWriteMap.eval(lockKey, new UnlockFunction(originator)).whenComplete((unlockResult, ex) -> { if (ex == null) { log.tracef("Unlock result for %s is %b", originator, unlockResult); unlockRequest.complete(null); } else { unlockRequest.completeExceptionally(handleException(ex)); } }); return unlockRequest; }
Source:
<code>public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this.provider = <START> new RemotableSVNAuthenticationBuilderProvider(credentials, Collections.<String, Credentials>emptyMap(), TaskListener.NULL); <END> }</code><technical_language>this() invocation of constructor</technical_language>

Target:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this(credentials, null, TaskListener.NULL); }
Source:
<code>public void incorrectBackupDirectory() throws IOException { <START> Path backupDirectoryResolved = new File( "." ).toPath().toRealPath().resolve( "non_existing_dir" ); <END> String output = runBackup( "--backup-dir=non_existing_dir", "--name=mybackup" ); String reason = String.format( "command failed: Directory '%s' does not exist.\n", backupDirectoryResolved.toFile().toString() ); assertEquals( reason, output ); }</code><technical_language>new File( "." ).toPath() Paths.get(".")? in #runBackup() method</technical_language>

Target:
public void incorrectBackupDirectory() throws IOException { Path backupDirectoryResolved = HERE.toRealPath().resolve( "non_existing_dir" ); String output = runBackup( "--backup-dir=non_existing_dir", "--name=mybackup" ); String reason = String.format( "command failed: Directory '%s' does not exist.\n", backupDirectoryResolved ); assertThat( output, containsString( reason ) ); }
Source:
<code>@Test public void setsCustomName() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { ctx.log().addListener(log::set, RequestLogAvailability.COMPLETE); return client.execute(ctx, req); }) .build()); http.newCall(REQUEST, BodyConverters.NULL, "custom-name").execute(); <START> await().untilAsserted(() -> assertThat(log).doesNotHaveValue(null)); <END> assertThat(log.get().requestContent()).isInstanceOfSatisfying(RpcRequest.class, req -> assertThat(req.method().endsWith("custom-name"))); }</code><technical_language>I suspect I broke this test :P</technical_language>

Target:
@Test public void setsCustomName() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { ctx.log().addListener(log::set, RequestLogAvailability.COMPLETE); return client.execute(ctx, req); }) .build()); http.newCall(REQUEST, BodyConverters.NULL, "custom-name").execute(); await().untilAsserted(() -> assertThat(log).doesNotHaveValue(null)); assertThat(log.get().context().attr(HttpCall.NAME).get()) .isEqualTo("custom-name"); }
Source:
<code>private String calcExternalNetworkName(int index) { boolean multiple = clustersByProvider.keySet().size() > 1; String indexSuffix = multiple ? MessageFormat.format(MULTIPLE_PROVIDERS, index + 1) : ""; String externalNetworkName = getNetwork().getName(); int newNetworkNameLength = getNetwork().getName().length() + EXTERNAL_PREFIX.length() + indexSuffix.length(); if (newNetworkNameLength > BusinessEntitiesDefinitions.NETWORK_NAME_SIZE) { externalNetworkName = externalNetworkName.substring(0, <START> 2 * BusinessEntitiesDefinitions.NETWORK_NAME_SIZE - newNetworkNameLength); <END> } return MessageFormat.format(EXTERNAL_NAME, EXTERNAL_PREFIX, externalNetworkName, indexSuffix); }</code><technical_language>I understand this calculation. For example - NETWORK_NAME_SIZE = 256, externalNetworkName = 250 => newNetworkNameLength = 250 + 9 + 2 = 261 externalNetworkName = externalNetworkName.substring(0, 251); Adding prefix suffix externalNetworkName get a name 262 characters is bigger max size. IMO, calculation externalNetworkName = externalNetworkName.substring(0, BusinessEntitiesDefinitions.NETWORK_NAME_SIZE - EXTERNAL_PREFIX.length() - indexSuffix.length()); => externalNetworkName = externalNetworkName.substring(0, 245);</technical_language>

Target:
private String calcExternalNetworkName(int index) { boolean multiple = clustersByProvider.keySet().size() > 1; String indexSuffix = multiple ? MessageFormat.format(MULTIPLE_PROVIDERS, index + 1) : ""; String externalNetworkName = getNetwork().getName(); int newNetworkNameLength = getNetwork().getName().length() + EXTERNAL_PREFIX.length() + indexSuffix.length(); if (newNetworkNameLength > BusinessEntitiesDefinitions.NETWORK_NAME_SIZE) { externalNetworkName = externalNetworkName.substring(0, BusinessEntitiesDefinitions.NETWORK_NAME_SIZE - EXTERNAL_PREFIX.length() - indexSuffix.length()); } return MessageFormat.format(EXTERNAL_NAME, EXTERNAL_PREFIX, externalNetworkName, indexSuffix); }
Source:
<code>public List<DataPartition> findMatchingPartitions(FileFilter filter) { <START> if (dataPartitionRanges.size() == 0) <END> { return Arrays.asList(dataPartitions); } CompiledFileFilter compiledFileFilter = null; try { compiledFileFilter = new CompiledFileFilter(this.recordDef,filter); } catch (Exception e) { return Arrays.asList(dataPartitions); } ArrayList<DataPartition> matchingPartitions = new ArrayList<DataPartition>(); for (int i = 0; i < dataPartitionRanges.size(); i++) { DataPartitionRecordRange partitionRange = dataPartitionRanges.get(i); if (compiledFileFilter.partitionMatchesFilter(partitionRange)) { matchingPartitions.add(partitionRange.dataPartition); } } return matchingPartitions; }</code><technical_language>bail out if filter == null</technical_language>

Target:
public List<DataPartition> findMatchingPartitions(FileFilter filter) { if (dataPartitionRanges.size() == 0 || filter == null) { return Arrays.asList(dataPartitions); } CompiledFileFilter compiledFileFilter = null; try { compiledFileFilter = new CompiledFileFilter(this.recordDef,filter); } catch (Exception e) { return Arrays.asList(dataPartitions); } ArrayList<DataPartition> matchingPartitions = new ArrayList<DataPartition>(); for (int i = 0; i < dataPartitionRanges.size(); i++) { DataPartitionRecordRange partitionRange = dataPartitionRanges.get(i); if (compiledFileFilter.partitionMatchesFilter(partitionRange)) { matchingPartitions.add(partitionRange.dataPartition); } } return matchingPartitions; }
Source:
<code>public Iterable<Fork> iterate( @NotNull(message = "sort can't be NULL") final String sort) { return new RtPagination<Fork>( this.request.uri() .queryParam("sort", sort) .back(), <START> new RtPagination.Mapping<Fork>() { <END> @Override public Fork map(final JsonObject object) { return new Fork() { @Override public JsonObject json() throws IOException { return object; } }; } } ); }</code><technical_language>RtPagination changed. new RtPagination.Mapping<Fork, JsonObject>()</technical_language>

Target:
public Iterable<Fork> iterate( @NotNull(message = "sort can't be NULL") final String sort) { return new RtPagination<Fork>( this.request.uri() .queryParam("sort", sort).back(), new RtPagination.Mapping<Fork, JsonObject>() { @Override public Fork map(final JsonObject value) { return new Fork() { @Override public JsonObject json() throws IOException { return value; } @Override public int number() { throw new UnsupportedOperationException(""); } @Override public void patch( final JsonObject json) throws IOException { throw new UnsupportedOperationException(""); } }; } } ); }
Source:
<code>private int getPlaylistId(Resources res) { Uri uri = MediaStore.Audio.Playlists.getContentUri("external"); final String[] ids = new String[] { MediaStore.Audio.Playlists._ID }; final String where = MediaStore.Audio.Playlists.NAME + "=?"; final String[] args = new String[] { res.getString(R.string.audio_db_playlist_name) }; Cursor cursor = query(uri, ids, where, args, null); if (cursor == null) { Log.v(TAG, "query returns null"); } int id = -1; if (cursor != null) { try { cursor.moveToFirst(); <START> if (!cursor.isAfterLast()) { <END> id = cursor.getInt(0); } } finally { cursor.close(); } } return id; }</code><technical_language>lines collapsed 'if (cursor.moveToFirst())'</technical_language>

Target:
private int getPlaylistId(Resources res) { Uri uri = MediaStore.Audio.Playlists.getContentUri("external"); final String[] ids = new String[] { MediaStore.Audio.Playlists._ID }; final String where = MediaStore.Audio.Playlists.NAME + "=?"; final String[] args = new String[] { res.getString(R.string.audio_db_playlist_name) }; Cursor cursor = query(uri, ids, where, args, null); if (cursor == null) { Log.v(TAG, "query returns null"); } int id = -1; if (cursor != null) { try { if (cursor.moveToFirst()) { id = cursor.getInt(0); } } finally { cursor.close(); } } return id; }
Source:
<code>public int getPreferredWidth() { <START> return ComponentConstants.VIDEOPLAYER_PREFERRED_WIDTH; <END> }</code><technical_language>separate constants in case decide change default video player width/height, want components tightly coupled</technical_language>

Target:
public int getPreferredWidth() { return ComponentConstants.CHART_PREFERRED_WIDTH; }
Source:
<code>public EncryptionKey getEncryptionKey() { EncryptionKey key = null; if (this.manager.keyExists()) { key = this.manager.loadKeyUsingPassword(this.password); } else { key = this.manager.generateAndSaveKeyProtectedByPassword(this.password); } return key; <START> } <END></code><technical_language>I suggest synchronising this method class thread-safe. @indisoluble do need do iOS too</technical_language>

Target:
public synchronized EncryptionKey getEncryptionKey() { EncryptionKey key = null; if (this.manager.keyExists()) { key = this.manager.loadKeyUsingPassword(this.password); } else { key = this.manager.generateAndSaveKeyProtectedByPassword(this.password); } return key; }
Source:
<code>private void loadAwards() { File dir = new File(AWARDS_XML_ROOT_PATH); File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); if(files == null) { return; } for(File file : files) { try{ <START> InputStream inputStream = new FileInputStream(file); <END> loadAwardsFromStream(inputStream, file.getName()); inputStream.close(); } catch (IOException e){ MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", e); } } }</code><technical_language>try-with-resources</technical_language>

Target:
private void loadAwards() { File dir = new File(AWARDS_XML_ROOT_PATH); File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); if (files == null) { return; } for (File file : files) { try (InputStream inputStream = new FileInputStream(file)) { loadAwardsFromStream(inputStream, file.getName()); } catch (IOException e){ MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", e); } } }