auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getConceptNameTagByName_shouldReturnTheMatchingConceptNameTagObjectIfFound() { ConceptNameTag c = new ConceptNameTag(); c.setTag("tag"); c.setDescription("some description"); assertNull(c.getId()); ConceptNameTag savedC = conceptService.saveConceptNameTag(c); assertNotNull(savedC.getId()); <START> assertEquals(savedC.getDescription(), conceptService.getConceptNameTagByName("tag").getDescription()); <END> }</code><technical_language>conceptNameTags description right? assert of objects equal</technical_language>

Target:
public void getConceptNameTagByName_shouldReturnTheMatchingConceptNameTagObjectIfFound() { ConceptNameTag conceptNameTag = conceptService.getConceptNameTag(1); assertNotNull(conceptNameTag); assertEquals(conceptNameTag, conceptService.getConceptNameTagByName(conceptNameTag.getTag())); }
Source:
<code>private String readEndpoint(final String endpoint) { try { final URL url = new URL(new URL(this.baseUrl), endpoint); LOGGER.debug(url.toString()); String response = client.get(url, IHttpConstants.DEFAULT_READ_TIMEOUT); LOGGER.debug(response); return response; } catch (MalformedURLException | SocketTimeoutException e) { <START> LOGGER.error("Exception", e); <END> throw new OpenShiftException(e,""); } catch (HttpClientException e) { if(e instanceof NotFoundException) { throw new com.openshift.restclient.NotFoundException(e); } LOGGER.error("Unauthorized exception. Can system:anonymous get the API endpoint", e); throw e; } }</code><technical_language>Logging throw is imho anti-pattern caller log exception catches</technical_language>

Target:
private String readEndpoint(final String endpoint) { try { final URL url = new URL(new URL(this.baseUrl), endpoint); LOGGER.debug(url.toString()); String response = client.get(url, IHttpConstants.DEFAULT_READ_TIMEOUT); LOGGER.debug(response); return response; } catch (MalformedURLException | SocketTimeoutException e) { throw new OpenShiftException(e,""); } catch (HttpClientException e) { if(e instanceof NotFoundException) { throw new com.openshift.restclient.NotFoundException(e); } LOGGER.error("Unauthorized exception. Can system:anonymous get the API endpoint", e); throw e; } }
Source:
<code>public void testCorruptMessageError() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1, fetcher.sendFetches()); assertFalse(fetcher.hasCompletedFetches()); client.prepareResponse(fullFetchResponse( tp0, buildRecords(1L, 1, 1), Errors.CORRUPT_MESSAGE, 100L, 0)); consumerClient.poll(time.timer(0)); assertTrue(fetcher.hasCompletedFetches()); assertThrows(KafkaException.class, () -> { Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> partitionRecords = <START> fetchedRecords(); <END> }); }</code><technical_language>nit: calling fetchedRecords() work here, is compiler liking forcing return assignment</technical_language>

Target:
public void testCorruptMessageError() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1, fetcher.sendFetches()); assertFalse(fetcher.hasCompletedFetches()); client.prepareResponse(fullFetchResponse( tp0, buildRecords(1L, 1, 1), Errors.CORRUPT_MESSAGE, 100L, 0)); consumerClient.poll(time.timer(0)); assertTrue(fetcher.hasCompletedFetches()); assertThrows(KafkaException.class, () -> { fetchedRecords(); }); }
Source:
<code>protected void paintBorder(Graphics graphics) { super.paintBorder(graphics); graphics.setLineStyle(Graphics.LINE_SOLID); graphics.setLineWidth(getBorderWidth()); graphics.setForegroundColor(geBorderColor()); boolean hasLabel = true; if (viewNode instanceof DDiagramElement) { if (new DDiagramElementQuery((DDiagramElement) viewNode).isLabelHidden()) { hasLabel = false; } } if (hasLabel) { Iterable<ViewNodeContainerFigureDesc> filter = Iterables.filter(getChildren(), ViewNodeContainerFigureDesc.class); if (Iterables.size(filter) == 1) { ViewNodeContainerFigureDesc child = filter.iterator().next(); SiriusWrapLabel <START> containerLabelFigure = <END> child.getLabelFigure(); if (containerLabelFigure != null && LabelBorderStyleIds.getLabelBorderStyleWithBeveledCornersIds().equals(labelBorderStyleDescription.getId())) { Rectangle containerLabelFigureBounds = containerLabelFigure.getBounds(); paintTitleBlockOnLabel(graphics, containerLabelFigureBounds); } } } }</code><technical_language>I if contianerLabelFigure null label is hidden calling isVisible label figure return false. configure visibility of labels figure visibility of notation label view visibility state (which is updated NotationVisibilityUpdater)</technical_language>

Target:
protected void paintBorder(Graphics graphics) { super.paintBorder(graphics); graphics.setLineStyle(Graphics.LINE_SOLID); graphics.setLineWidth(1); graphics.setForegroundColor(geBorderColor()); Iterable<ViewNodeContainerFigureDesc> filter = Iterables.filter(getChildren(), ViewNodeContainerFigureDesc.class); if (Iterables.size(filter) == 1) { ViewNodeContainerFigureDesc child = filter.iterator().next(); SiriusWrapLabel containerLabelFigure = child.getLabelFigure(); if (containerLabelFigure != null && containerLabelFigure.isVisible() && LabelBorderStyleIds.getLabelBorderStyleWithBeveledCornersIds().equals(labelBorderStyleDescription.getId())) { Rectangle containerLabelFigureBounds = containerLabelFigure.getBounds(); paintTitleBlockOnLabel(graphics, containerLabelFigureBounds); } } }
Source:
<code>private void hide(final LNode lNode, final LEdge lEdge) { <START> boolean outgoing = lEdge.getSource().getNode() == lNode; <END> LPort oppositePort = outgoing ? lEdge.getTarget() : lEdge.getSource(); if (outgoing) { lEdge.setTarget(null); } else { lEdge.setSource(null); } lEdge.setProperty(InternalProperties.ORIGINAL_OPPOSITE_PORT, oppositePort); updateOppositeNodeLayerConstraints(lNode, oppositePort.getNode()); }</code><technical_language>isOutgoing more Java-style</technical_language>

Target:
private void hide(final LNode lNode, final LEdge lEdge) { boolean isOutgoing = lEdge.getSource().getNode() == lNode; LPort oppositePort = isOutgoing ? lEdge.getTarget() : lEdge.getSource(); if (isOutgoing) { lEdge.setTarget(null); } else { lEdge.setSource(null); } lEdge.setProperty(InternalProperties.ORIGINAL_OPPOSITE_PORT, oppositePort); updateOppositeNodeLayerConstraints(lNode, oppositePort.getNode()); }
Source:
<code><START> public HttpHeaders getAuthHeaders() { <END> String plainCreds = String.format("%s:%s", config.getUsername(), config.getPassword()); byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); return headers; }</code><technical_language>this need public</technical_language>

Target:
private HttpHeaders getAuthHeaders() { String plainCreds = String.format("%s:%s", config.getUsername(), config.getPassword()); byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); return headers; }
Source:
<code>public void testOrcColumnName() throws Exception { String tablePath = getExternalResourceDirectory()+"orc_colname"; methodWatcher.execute(String.format("create external table t_orc (col1 int, col2 varchar(5))" + <START> " STORED AS PARQUET LOCATION '%s'", tablePath)); <END> methodWatcher.execute("insert into t_orc values (3, 'C')"); SparkSession spark = SparkSession.builder() .master("local") .appName("ExternaltableIT") .getOrCreate(); Dataset dataset = spark .read() .parquet(tablePath); String actual = dataset.schema().toString(); String expected = "StructType(StructField(COL1,IntegerType,true), StructField(COL2,StringType,true))"; Assert.assertEquals(actual, expected, actual); }</code><technical_language>change? If this is deliberate need change test name</technical_language>

Target:
public void testOrcColumnName() throws Exception { String tablePath = getExternalResourceDirectory()+"orc_colname"; methodWatcher.execute(String.format("create external table t_orc (col1 int, col2 varchar(5))" + " STORED AS ORC LOCATION '%s'", tablePath)); methodWatcher.execute("insert into t_orc values (3, 'C')"); SparkSession spark = SparkSession.builder() .master("local") .appName("ExternaltableIT") .getOrCreate(); Dataset dataset = spark .read() .parquet(tablePath); String actual = dataset.schema().toString(); String expected = "StructType(StructField(COL1,IntegerType,true), StructField(COL2,StringType,true))"; Assert.assertEquals(actual, expected, actual); }
Source:
<code>public String toHex(DiscreteElement<?> element) { <START> return ""; <END> }</code><technical_language>return returned called toHex</technical_language>

Target:
public String toHex(DiscreteElement<?> element) { return element.getValue().toString(); }
Source:
<code>public void rollback_successful_when_prepare_step_throws_exception_when_two_phase() { String mapName = "map"; String queueName = "queue"; long maxWbqCapacity = 100; Config config = getConfig(mapName, maxWbqCapacity); HazelcastInstance node = createHazelcastInstance(config); TransactionContext context = newTransactionContext(node, TWO_PHASE); try { context.beginTransaction(); TransactionalQueue queue = context.getQueue(queueName); queue.offer(1); queue.offer(2); queue.offer(3); TransactionalMap map = context.getMap(mapName); for (int i = 0; i < 1000; i++) { map.put("item-" + i, "value"); } context.commitTransaction(); <START> } catch (Exception e) { <END> context.rollbackTransaction(); } assertEquals(0, node.getQueue(queueName).size()); assertEquals(0, node.getMap(mapName).size()); }</code><technical_language>catch more specific exception</technical_language>

Target:
public void rollback_successful_when_prepare_step_throws_exception_when_two_phase() { String mapName = "map"; String queueName = "queue"; long maxWbqCapacity = 100; Config config = getConfig(mapName, maxWbqCapacity); HazelcastInstance node = createHazelcastInstance(config); TransactionContext context = newTransactionContext(node, TWO_PHASE); try { context.beginTransaction(); TransactionalQueue queue = context.getQueue(queueName); queue.offer(1); queue.offer(2); queue.offer(3); TransactionalMap map = context.getMap(mapName); for (int i = 0; i < 1000; i++) { map.put("item-" + i, "value"); } context.commitTransaction(); } catch (TransactionException e) { context.rollbackTransaction(); } assertEquals(0, node.getQueue(queueName).size()); assertEquals(0, node.getMap(mapName).size()); }
Source:
<code>public void showPictures() { setLoadPictures(true); <START> displayHtmlContentWithInlineAttachments(mText, null); <END> }</code><technical_language>Passing null argument feels wrong. setting text, AttachmentResolver</technical_language>

Target:
public void showPictures() { setLoadPictures(true); refreshDisplayedContent(); }
Source:
<code>private void resetAction() { edfname.setText(""); edmname.setText(""); edlname.setText(""); eddob.setText(""); edyr.setText(""); edmonth.setText(""); edaddr1.setText(""); edaddr2.setText(""); mCountryCodePicker.resetToDefaultCountry(); edcity.setText(""); edstate.setText(""); edpostal.setText(""); gen.clearCheck(); fnameerror.setText(""); lnameerror.setText(""); doberror.setText(""); gendererror.setText(""); <START> addrerror.setText(""); <END> firstNameTIL.setError(""); middleNameTIL.setError(""); lastNameTIL.setError(""); address1TIL.setError(""); patientImageView.setImageResource(R.drawable.ic_person_grey_500_48dp); patientPhoto = null; patientName = null; isUpdatePatient = false; updatedPatient = null; output = null; }</code><technical_language>variables this in camelCase</technical_language>

Target:
private void resetAction() { edfName.setText(""); edmName.setText(""); edlName.setText(""); edDob.setText(""); edYear.setText(""); edMonth.setText(""); edAddr1.setText(""); edAddr2.setText(""); mCountryCodePicker.resetToDefaultCountry(); edCity.setText(""); edState.setText(""); edPostal.setText(""); gen.clearCheck(); fNameError.setText(""); lNameError.setText(""); dobError.setText(""); genderError.setText(""); addrError.setText(""); firstNameTIL.setError(""); middleNameTIL.setError(""); lastNameTIL.setError(""); address1TIL.setError(""); patientImageView.setImageResource(R.drawable.ic_person_grey_500_48dp); patientPhoto = null; patientName = null; isUpdatePatient = false; updatedPatient = null; output = null; }
Source:
<code>public StringDimensionIndexer(MultiValueHandling multiValueHandling) { this.dimLookup = new DimensionDictionary(); <START> this.multiValueHandling = multiValueHandling == null ? MultiValueHandling.SORTED_ARRAY : multiValueHandling; <END> }</code><technical_language>for this MultiValueHandling.ofDefault()</technical_language>

Target:
public StringDimensionIndexer(MultiValueHandling multiValueHandling) { this.dimLookup = new DimensionDictionary(); this.multiValueHandling = multiValueHandling == null ? MultiValueHandling.ofDefault() : multiValueHandling; }
Source:
<code>public void testGetDecertifiedDevelopers() { <START> SecurityContextHolder.getContext().setAuthentication(adminUser); <END> List<DeveloperDecertifiedDTO> dtoList = developerManager.getDecertifiedDevelopers(); assertTrue("DeveloperDecertificationResponse should have size == 2 but has size " + dtoList.size(), dtoList.size() == 2); }</code><technical_language>this line suggest authenticated user? "Given" "any user". authenticate? security this /decertifications call, right</technical_language>

Target:
public void testGetDecertifiedDevelopers() { List<DecertifiedDeveloperDTO> dtoList = developerManager.getDecertifiedDevelopers(); assertTrue("DeveloperDecertificationResponse should have size == 2 but has size " + dtoList.size(), dtoList.size() == 2); }
Source:
<code>private static TextRange getLocation(TslintError tslintError, InputFile inputFile) { if (samePosition(tslintError.startPosition, tslintError.endPosition)) { <START> return inputFile.selectLine(tslintError.startPosition.line + 1); <END> } else { return inputFile.newRange( tslintError.startPosition.line + 1, tslintError.startPosition.character, tslintError.endPosition.line + 1, tslintError.endPosition.character); } }</code><technical_language>I a simple method in TslintPosition this line+1 logic, need duplicate 3 times</technical_language>

Target:
private static TextRange getLocation(TslintError tslintError, InputFile inputFile) { if (tslintError.startPosition.equals(tslintError.endPosition)) { return inputFile.selectLine(tslintError.startPosition.getOneBasedLine()); } else { return inputFile.newRange( tslintError.startPosition.getOneBasedLine(), tslintError.startPosition.character, tslintError.endPosition.getOneBasedLine(), tslintError.endPosition.character); } }
Source:
<code>public String getRandomImageUrl() { List<String> hrefs = new ArrayList<String>(); for (WebElement elem:imagesNewFiles) { hrefs.add(elem.findElement(By.xpath("./..")).getAttribute("href")); } Random r = new Random(); <START> return hrefs.get((r.nextInt(hrefs.size()-1))+1); <END> }</code><technical_language>log() log.html viewer image chosen</technical_language>

Target:
public String getRandomImageUrl() { List<String> hrefs = new ArrayList<String>(); for (WebElement elem:imagesNewFiles) { hrefs.add(elem.findElement(By.xpath("./..")).getAttribute("href")); } Random r = new Random(); String href = hrefs.get((r.nextInt(hrefs.size()-1))+1); PageObjectLogging.log("getRandomImageUrl", href + " image is selected", true); return href; }
Source:
<code>public SVMainUI() { super(); createNewUnit(Entity.ETYPE_SUPPORT_TANK, false, false); setTitle(getEntity().getChassis() + " " + getEntity().getModel() + ".blk"); finishSetup(); <START> MechSummaryCache.getInstance(); <END> }</code><technical_language>I reason for it. I paid close attention code I copying</technical_language>

Target:
public SVMainUI() { super(); createNewUnit(Entity.ETYPE_SUPPORT_TANK, false, false); setTitle(getEntity().getChassis() + " " + getEntity().getModel() + ".blk"); finishSetup(); }
Source:
<code>void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i, WorkingTreeIterator f) { if (m != null) { <START> if (f == null || !m.idEqual(f) || i == null || !m.idEqual(i)) { <END> update(m.getEntryPathString(), m.getEntryObjectId(), m.getEntryFileMode()); } else keep(i.getDirCacheEntry()); } else { if (f != null) { if (walk.isDirectoryFileConflict()) { conflicts.add(walk.getPathString()); } else { if (i != null) { remove(i.getEntryPathString()); conflicts.remove(i.getEntryPathString()); } } } else keep(i.getDirCacheEntry()); } }</code><technical_language>right, improve performance here. in a bit suggested. This a small change bad performance. change force read single bit of file in working tree. problem is "m.idEqual(f)" triggers computation of sha-1 content of file in working tree. I avoid computing id if is necessary. E.g. if last-modification time of file is in index file is in index for this id. WorkingTreeIterator.isModified() is end of processEntry(AbstractTreeIterator h, AbstractTreeIterator m, DirCacheBuildIterator i, WorkingTreeIterator f) decide overwrite file not</technical_language>

Target:
void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i, WorkingTreeIterator f) { if (m != null) { if (i == null || f == null || !m.idEqual(i) || f.isModified(i.getDirCacheEntry(), true, config_filemode(), repo.getFS())) { update(m.getEntryPathString(), m.getEntryObjectId(), m.getEntryFileMode()); } else keep(i.getDirCacheEntry()); } else { if (f != null) { if (walk.isDirectoryFileConflict()) { conflicts.add(walk.getPathString()); } else { if (i != null) { remove(i.getEntryPathString()); conflicts.remove(i.getEntryPathString()); } } } else keep(i.getDirCacheEntry()); } }
Source:
<code>public void generatedInterfaceDoesNotHaveStaticMethods() { Set<String> generatedMethods = TestingUtils.extractMethods(AutoDelegate_TestInterface.class); Set<String> originalStaticMethods = TestingUtils.extractMethodsSatisfyingPredicate(TestInterface.class, method -> Modifier.isStatic(method.getModifiers())); <START> <END> originalStaticMethods.forEach(staticMethod -> assertThat(generatedMethods, not(contains(staticMethod)))); }</code><technical_language>assertThat(Sets.intersection(generatedMethods, originalMethods)).isEmpty()</technical_language>

Target:
public void generatedInterfaceDoesNotHaveStaticMethods() { Set<String> generatedMethods = TestingUtils.extractMethods(AutoDelegate_TestInterface.class); Set<String> originalStaticMethods = TestingUtils.extractMethodsSatisfyingPredicate(TestInterface.class, method -> Modifier.isStatic(method.getModifiers())); assertThat(Sets.intersection(generatedMethods, originalStaticMethods), empty()); }
Source:
<code>default String getGroup() { <START> return "Forestry"; <END> }</code><technical_language>recipes groups uppercase</technical_language>

Target:
default String getGroup() { return "forestry"; }
Source:
<code><START> private Map<String, Map<String, Long>> getValidSizeByContainer(long deleteAndExpirationRefTimeInMs) { <END> Map<String, Map<String, Long>> containerValidSizeMap = new HashMap<>(); for (Map.Entry<Offset, TreeMap<MockId, IndexValue>> segmentEntry : state.referenceIndex.entrySet()) { for (Map.Entry<MockId, IndexValue> indexEntry : segmentEntry.getValue().entrySet()) { MockId key = indexEntry.getKey(); IndexValue value = indexEntry.getValue(); if (value.isFlagSet(IndexValue.Flags.Delete_Index)) { if (!state.isDeletedAt(key, deleteAndExpirationRefTimeInMs) && !state.isExpiredAt(key, deleteAndExpirationRefTimeInMs) && value.getOriginalMessageOffset() != -1 && value.getOriginalMessageOffset() >= segmentEntry.getKey().getOffset()) { updateNestedMapHelper(containerValidSizeMap, String.valueOf(value.getServiceId()), String.valueOf(value.getContainerId()), state.allKeys.get(key).getFirst().getSize()); } } else if (!state.isExpiredAt(key, deleteAndExpirationRefTimeInMs) && !state.isDeletedAt(key, deleteAndExpirationRefTimeInMs)) { updateNestedMapHelper(containerValidSizeMap, String.valueOf(value.getServiceId()), String.valueOf(value.getContainerId()), value.getSize()); } } } return containerValidSizeMap; }</code><technical_language>move this CuratedLogIndexState if useful</technical_language>

Target:
private Map<String, Map<String, Long>> getValidSizeByContainer(long deleteAndExpirationRefTimeInMs) { Map<String, Map<String, Long>> containerValidSizeMap = new HashMap<>(); for (Map.Entry<Offset, TreeMap<MockId, IndexValue>> segmentEntry : state.referenceIndex.entrySet()) { List<IndexEntry> validEntries = state.getValidIndexEntriesForIndexSegment(segmentEntry.getKey(), deleteAndExpirationRefTimeInMs, deleteAndExpirationRefTimeInMs); for (IndexEntry indexEntry : validEntries) { IndexValue indexValue = indexEntry.getValue(); if (!indexValue.isFlagSet(IndexValue.Flags.Delete_Index)) { updateNestedMapHelper(containerValidSizeMap, String.valueOf(indexValue.getServiceId()), String.valueOf(indexValue.getContainerId()), indexValue.getSize()); } } } return containerValidSizeMap; }
Source:
<code>public void update(Budget b, final ApiCallback<Object> callback) { <START> if (failOnNoInternet(callback)) <END> return; RequestParams params = new RequestParams(); String startDate = b.getStartDate().toString(DATE_FORMAT); params.put("id", "" + b.getId()); params.put("budget_name", b.getName()); params.put("amount", "" + b.getBudgetAmount()); params.put("recur", "" + b.isRecurring()); params.put("start_date", startDate); params.put("recurrence_duration", b.getDuration().toString()); client.put(budgetsUrl, params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject obj) { callback.onSuccess(null); } @Override public void onFailure(Throwable t) { callback.onFailure(t.getMessage()); } @Override public void onFailure(Throwable e, String message) { if (e instanceof SocketTimeoutException) { callback.onFailure("Network Timeout"); } else { callback.onFailure(message); } } }); }</code><technical_language>Need braces (for style), of other places</technical_language>

Target:
public void update(Budget b, final ApiCallback<Object> callback) { if (failOnNoInternet(callback)) { return; } RequestParams params = new RequestParams(); String startDate = b.getStartDate().toString(DATE_FORMAT); params.put("id", "" + b.getId()); params.put("budget_name", b.getName()); params.put("amount", "" + b.getBudgetAmount()); params.put("recur", "" + b.isRecurring()); params.put("start_date", startDate); params.put("recurrence_duration", b.getDuration().toString()); client.put(budgetsUrl, params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject obj) { callback.onSuccess(null); } @Override public void onFailure(Throwable t) { callback.onFailure(t.getMessage()); } @Override public void onFailure(Throwable e, String message) { if (e instanceof SocketTimeoutException) { callback.onFailure("Network Timeout"); } else { callback.onFailure(message); } } }); }
Source:
<code>private ConsumerRecords<K, V> poll(final Timer timer, final boolean includeMetadataInTimeout) { acquireAndEnsureOpen(); try { if (this.subscriptions.hasNoSubscriptionOrUserAssignment()) { throw new IllegalStateException("Consumer is not subscribed to any topics or assigned any partitions"); } <START> this.kafkaConsumerMetrics.recordPollStart(time.milliseconds()); <END> do { client.maybeTriggerWakeup(); if (includeMetadataInTimeout) { if (!updateAssignmentMetadataIfNeeded(timer)) { this.kafkaConsumerMetrics.recordPollEnd(time.milliseconds()); return ConsumerRecords.empty(); } } else { while (!updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE))) { log.warn("Still waiting for metadata"); } } final Map<TopicPartition, List<ConsumerRecord<K, V>>> records = pollForFetches(timer); if (!records.isEmpty()) { if (fetcher.sendFetches() > 0 || client.hasPendingRequests()) { client.pollNoWakeup(); } this.kafkaConsumerMetrics.recordPollEnd(time.milliseconds()); return this.interceptors.onConsume(new ConsumerRecords<>(records)); } } while (timer.notExpired()); this.kafkaConsumerMetrics.recordPollEnd(time.milliseconds()); return ConsumerRecords.empty(); } finally { release(); } }</code><technical_language>I change calls timer.currentTimeMs() do add additional calls system time. a performance issue in past</technical_language>

Target:
private ConsumerRecords<K, V> poll(final Timer timer, final boolean includeMetadataInTimeout) { acquireAndEnsureOpen(); try { this.kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs()); if (this.subscriptions.hasNoSubscriptionOrUserAssignment()) { throw new IllegalStateException("Consumer is not subscribed to any topics or assigned any partitions"); } do { client.maybeTriggerWakeup(); if (includeMetadataInTimeout) { if (!updateAssignmentMetadataIfNeeded(timer)) { return ConsumerRecords.empty(); } } else { while (!updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE))) { log.warn("Still waiting for metadata"); } } final Map<TopicPartition, List<ConsumerRecord<K, V>>> records = pollForFetches(timer); if (!records.isEmpty()) { if (fetcher.sendFetches() > 0 || client.hasPendingRequests()) { client.pollNoWakeup(); } return this.interceptors.onConsume(new ConsumerRecords<>(records)); } } while (timer.notExpired()); return ConsumerRecords.empty(); } finally { release(); this.kafkaConsumerMetrics.recordPollEnd(timer.currentTimeMs()); } }
Source:
<code>public SubfieldPath(@JsonProperty("path") List<PathElement> path) { requireNonNull(path, "path is null"); <START> if (path.size() <= 1) { <END> throw new IllegalArgumentException("path must include at least 2 elements"); } if (!(path.get(0) instanceof NestedField)) { throw new IllegalArgumentException("path must start with a name"); } this.name = ((NestedField) path.get(0)).getName(); this.path = path; }</code><technical_language>I create a private static checkArgument method for checks</technical_language>

Target:
public SubfieldPath(@JsonProperty("path") List<PathElement> path) { requireNonNull(path, "path is null"); checkArgument(path.size() > 1, "path must include at least 2 elements"); checkArgument(path.get(0) instanceof NestedField, "path must start with a name"); this.name = ((NestedField) path.get(0)).getName(); this.path = path; }
Source:
<code>void onError(Throwable throwable) throws Exception { <START> if (throwable == RESULT_EXCEPTION) return; <END> try { context.onError(castToException(throwable)); } catch (Throwable throwable1) { throw castToException(throwable); } }</code><technical_language>replace throwable instanceof RetryDueToResultException</technical_language>

Target:
void onError(Throwable throwable) throws Exception { if (throwable instanceof RetryDueToResultException) return; try { context.onError(castToException(throwable)); } catch (Throwable throwable1) { throw castToException(throwable); } }
Source:
<code>public static void registerTags() { <START> PropertyParser.<TownyChatPlayerProperties>registerTag("townychat", (attribute, object) -> { <END> if (attribute.startsWith("channel")) { ListTag channels = new ListTag(); for (Channel channel : TownyChatBridge.channelsHolder.getAllChannels().values()) { channels.addObject(new ElementTag(channel.getName())); } return channels; } else if (attribute.startsWith("muted_in")) { if (attribute.hasContext(1)) { Channel channel = TownyChatBridge.channelsHolder.getChannel(attribute.getContext(1)); if (channel != null) { return new ElementTag(channel.isMuted(object.player.getName())); } Debug.echoError("Unable to match '" + attribute.getContext(1) + "' to a valid chat channel!"); return null; } Debug.echoError("A channel must be specified for <PlayerTag.townychat.muted_in[<channel>]>!"); return null; } else if (attribute.startsWith("has_permission")) { if (attribute.hasContext(1)) { Channel channel = TownyChatBridge.channelsHolder.getChannel(attribute.getContext(1)); if (channel != null) { return new ElementTag(channel.getPermission() != null && TownyUniverse.getInstance().getPermissionSource().has(object.player.getPlayerEntity(), channel.getPermission())); } } else { Debug.echoError("You must specify a channel for tag <PlayerTag.townychat.has_permission[<channel>]>!"); return null; } } return null; }); }</code><technical_language>This tested, it? of tags work</technical_language>

Target:
public static void registerTags() { PropertyParser.<TownyChatPlayerProperties>registerTag("townychat", (attribute, object) -> { attribute = attribute.fulfill(1); if (attribute.startsWith("channels")) { ListTag channels = new ListTag(); for (Channel channel : TownyChatBridge.channelsHolder.getAllChannels().values()) { channels.addObject(new ElementTag(channel.getName())); } return channels; } else if (attribute.startsWith("muted_in")) { if (attribute.hasContext(1)) { Channel channel = TownyChatBridge.channelsHolder.getChannel(attribute.getContext(1)); if (channel != null) { return new ElementTag(channel.isMuted(object.player.getName())); } Debug.echoError("Unable to match '" + attribute.getContext(1) + "' to a valid chat channel!"); return null; } Debug.echoError("A channel must be specified for <PlayerTag.townychat.muted_in[<channel>]>!"); return null; } else if (attribute.startsWith("has_permission")) { if (attribute.hasContext(1)) { Channel channel = TownyChatBridge.channelsHolder.getChannel(attribute.getContext(1)); if (channel != null) { return new ElementTag(channel.getPermission() != null && TownyUniverse.getInstance().getPermissionSource().has(object.player.getPlayerEntity(), channel.getPermission())); } } else { Debug.echoError("You must specify a channel for tag <PlayerTag.townychat.has_permission[<channel>]>!"); return null; } } return null; }); }
Source:
<code>public Schema createSchema(String schemaName) { final MutableSchema schema = new MutableSchema(schemaName); final Workbook wb = ExcelUtils.readWorkbook(_resource, true); try { for (int i = 0; i < wb.getNumberOfSheets(); i++) { final Sheet currentSheet = wb.getSheetAt(i); <START> final MutableTable table = createTable(wb, currentSheet, _configuration.isValidateColumnTypes()); <END> table.setSchema(schema); schema.addTable(table); } return schema; } finally { FileHelper.safeClose(wb); } }</code><technical_language>_configuration is a field of this class, pass internal (non-static) class method? line 156, do _configuration.isValidateColumnTypes()</technical_language>

Target:
public Schema createSchema(String schemaName) throws Exception { final MutableSchema schema = new MutableSchema(schemaName); final Workbook wb = ExcelUtils.readWorkbook(_resource, true); try { for (int i = 0; i < wb.getNumberOfSheets(); i++) { final Sheet currentSheet = wb.getSheetAt(i); final MutableTable table = createTable(wb, currentSheet); table.setSchema(schema); schema.addTable(table); } return schema; } finally { FileHelper.safeClose(wb); } }
Source:
<code>public static VDSGroup map(SchedulingPolicy model, VDSGroup template) { VDSGroup entity = template != null ? template : new VDSGroup(); if (model.isSetPolicy()) { SchedulingPolicyType policyType = SchedulingPolicyType.fromValue(model.getPolicy()); if (policyType != null) { entity.setClusterPolicyId(null); entity.setClusterPolicyName(policyType.name().toLowerCase()); } } if (model.isSetThresholds()) { SchedulingPolicyThresholds thresholds = model.getThresholds(); <START> entity.setClusterPolicyProperties(new LinkedHashMap<String, String>()); <END> if (thresholds.getLow() != null) { entity.getClusterPolicyProperties().put(LOW_UTILIZATION, thresholds.getLow().toString()); } if (thresholds.getHigh() != null) { entity.getClusterPolicyProperties().put(HIGH_UTILIZATION, thresholds.getHigh().toString()); } if (thresholds.getDuration() != null) { int round = Math.round(thresholds.getDuration() / 60.0f); entity.getClusterPolicyProperties().put(CPU_OVER_COMMIT_DURATION_MINUTES, Integer.toString(round)); } } return entity; }</code><technical_language>user update a scheduling policy? If so, this mapping in context of update result in a bug: properties map is re-created scratch values disappear</technical_language>

Target:
public static VDSGroup map(SchedulingPolicy model, VDSGroup template) { VDSGroup entity = template != null ? template : new VDSGroup(); if (model.isSetPolicy()) { SchedulingPolicyType policyType = SchedulingPolicyType.fromValue(model.getPolicy()); if (policyType != null) { entity.setClusterPolicyId(null); entity.setClusterPolicyName(policyType.name().toLowerCase()); } } if (model.isSetThresholds()) { SchedulingPolicyThresholds thresholds = model.getThresholds(); if (entity.getClusterPolicyProperties() == null) { entity.setClusterPolicyProperties(new LinkedHashMap<String, String>()); } if (thresholds.getLow() != null) { entity.getClusterPolicyProperties().put(LOW_UTILIZATION, thresholds.getLow().toString()); } if (thresholds.getHigh() != null) { entity.getClusterPolicyProperties().put(HIGH_UTILIZATION, thresholds.getHigh().toString()); } if (thresholds.getDuration() != null) { int round = Math.round(thresholds.getDuration() / 60.0f); entity.getClusterPolicyProperties().put(CPU_OVER_COMMIT_DURATION_MINUTES, Integer.toString(round)); } } return entity; }
Source:
<code>@Override public ParameterizedTypeName annotated(List<AnnotationSpec> annotations) { <START> return new ParameterizedTypeName( <END> rawType, enclosingTypeOrRawType, nestedClassName, typeArguments, concatAnnotations(annotations)); }</code><technical_language>nit: collapse of lines</technical_language>

Target:
@Override public ParameterizedTypeName annotated(List<AnnotationSpec> annotations) { return new ParameterizedTypeName( rawType, enclosingType, typeArguments, concatAnnotations(annotations)); }
Source:
<code>protected static void showTables(Statement stmt, String sql) throws SQLException{ ResultSet res; System.out.println("Running: " + sql +"\n"); res = stmt.executeQuery(sql); ResultSetMetaData rsmd = res.getMetaData(); int columnsNumber = rsmd.getColumnCount(); while (res.next()) { <START> <END> for (int i = 1; i <= columnsNumber; i++) { String columnValue = res.getString(i); System.out.print(columnValue); System.out.println(""); } } System.out.println(""); }</code><technical_language>need for blank lines body of a loop line</technical_language>

Target:
static void showTables(Statement stmt, String sql) throws SQLException { ResultSet res; System.out.println("Running: " + sql + "\n"); res = stmt.executeQuery(sql); ResultSetMetaData rsmd = res.getMetaData(); int columnsNumber = rsmd.getColumnCount(); while (res.next()) { for (int i = 1; i <= columnsNumber; i++) { String columnValue = res.getString(i); System.out.println(columnValue); } } System.out.println(""); }
Source:
<code>protected void processValidationSet(PageDescription processedDescription, PageDescription currentDescription, TransformationCache cache) { if (currentDescription.eIsSet(VALIDATIONSET_FEATURE)) { <START> if (processedDescription.getValidationSet() == null) { PageValidationSetDescription validationSet = PropertiesFactory.eINSTANCE.createPageValidationSetDescription(); processedDescription.setValidationSet(validationSet); } <END> List<SemanticValidationRule> newValue = new ArrayList<>(); for (SemanticValidationRule rule : currentDescription.getValidationSet().getSemanticValidationRules()) { newValue.add(EcoreUtil.copy(rule)); } newValue.addAll(processedDescription.getValidationSet().getSemanticValidationRules()); processedDescription.getValidationSet().getSemanticValidationRules().clear(); processedDescription.getValidationSet().getSemanticValidationRules().addAll(newValue); } }</code><technical_language>java8-isation [optional][orElseGet][methodReference]</technical_language>

Target:
private void processValidationSet(PageDescription processedDescription, PageDescription currentDescription, TransformationCache cache) { if (currentDescription.eIsSet(VALIDATIONSET_FEATURE)) { PageValidationSetDescription validationSet = Optional.ofNullable(processedDescription.getValidationSet()).orElse(PropertiesFactory.eINSTANCE.createPageValidationSetDescription()); processedDescription.setValidationSet(validationSet); List<SemanticValidationRule> newValue = new ArrayList<>(); currentDescription.getValidationSet().getSemanticValidationRules().forEach(rule -> newValue.add(EcoreUtil.copy(rule))); newValue.addAll(processedDescription.getValidationSet().getSemanticValidationRules()); processedDescription.getValidationSet().getSemanticValidationRules().clear(); processedDescription.getValidationSet().getSemanticValidationRules().addAll(newValue); } }
Source:
<code>public String toString() { <START> String prefix = (TotalMilliseconds < 0) ? "-" : ""; <END> return String.format("%s%d.%02d:%02d:%02d.%03d", prefix, Days, Hours, Minutes, Seconds, Milliseconds); }</code><technical_language>If ternary operator, drop right return below, intermediate variable</technical_language>

Target:
public String toString() { return String.format("%s%d.%02d:%02d:%02d.%03d", (TotalMilliseconds < 0) ? "-" : "", Days, Hours, Minutes, Seconds, Milliseconds); }
Source:
<code>public boolean containsAgentRemotely(String uuid) { if (this.isLocal()) <START> return false; <END> if (!this.hasAgent(uuid)) return false; return true; }</code><technical_language>this if clause a block {...}? Supposing enters a new line accidentally, this method end returning false always</technical_language>

Target:
public boolean containsAgentRemotely(String uuid) { if (this.isLocal()) { return false; } if (!this.hasAgent(uuid)) { return false; } return true; }
Source:
<code>public MystromDevice getDeviceInfo(String deviceId){ Reader reader = null; <START> this.logger.debug("get device info..."); <END> try { HttpURLConnection httpURLConnection; httpURLConnection = (HttpURLConnection) new URL(API_URL + "device" + "?authToken=" + this.authToken + "&id=" + deviceId) .openConnection(); httpURLConnection.connect(); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { this.logger.error("Get device info http code: '{}'", responseCode); return null; } InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if(!status.equals("ok")){ this.logger.error("Error while getting device info id: '{}' status '{}'", deviceId, status); return null; } GetDeviceInfoResult result = gson.fromJson(jsonObject, GetDeviceInfoResult.class); return result.device; } catch(Exception ex){ this.logger.error("Error getting device info with id: '{}', detail '{}'", deviceId, ex.toString()); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }</code><technical_language>"this." is necessary</technical_language>

Target:
public MystromDevice getDeviceInfo(String deviceId) { Reader reader = null; logger.debug("get device info..."); try { String url = API_URL + "device" + "?authToken=" + this.authToken + "&id=" + deviceId; HttpURLConnection httpURLConnection; httpURLConnection = (HttpURLConnection) new URL(url) .openConnection(); httpURLConnection.connect(); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { logger.error("Get device info http code: '{}'", responseCode); return null; } InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if (!status.equals("ok")) { logger.error( "Error while getting device info id: '{}' status '{}'", deviceId, status); return null; } GetDeviceInfoResult result = gson.fromJson(jsonObject, GetDeviceInfoResult.class); return result.device; } catch (Exception ex) { logger.error( "Error getting device info with id: '{}', detail '{}'", deviceId, ex.toString()); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }
Source:
<code>private List<StudentAttributes> createStudentList(String... studentData) { List<StudentAttributes> students = new ArrayList<>(); for (int i = 0; i < studentData.length; i += 2) { StudentAttributes student = StudentAttributes .builder("", studentData[i + 1]) .withName(studentData[i]) .withTeamName(studentData[i]) <START> .withSectionName(studentData[i] + "'s Section") <END> .build(); students.add(student); } return students; }</code><technical_language>is a test class, I is good name element in pair for loop for understanding. studentTeam = studentData[i], studentEmail = studentData[i + 1]</technical_language>

Target:
private List<StudentAttributes> createStudentList(String... studentData) { List<StudentAttributes> students = new ArrayList<>(); for (int i = 0; i < studentData.length; i += 2) { String studentEmail = studentData[i + 1]; String studentName = studentData[i]; StudentAttributes student = StudentAttributes .builder("", studentEmail) .withName(studentName) .withTeamName(studentName) .withSectionName(studentName + "'s Section") .build(); students.add(student); } return students; }
Source:
<code>public synchronized boolean waitState(TajoProtos.QueryState expect, long timeout) throws InterruptedException { long prev = System.currentTimeMillis(); while (timeout > 0 && expect != queryState && !isTerminalState()) { <START> wait(timeout); <END> long current = System.currentTimeMillis(); timeout -= (current - prev); prev = current; } return expect == queryState; }</code><technical_language>I this approach a potential problem of process hang. wait() is called, wake setQueryState() is called. query processing, setQueryState() is called TajoMaster receives heartbeats workers. means, if some heartbeats lost, this process wake waiting time exceeds timeout. This a big problem expect receive heartbeat a lot of workers. However, I is a problem process's work intention. do think</technical_language>

Target:
public synchronized boolean waitState(TajoProtos.QueryState expect, long timeout) throws InterruptedException { RpcUtils.Timer timer = new RpcUtils.Timer(timeout); for (;!timer.isTimedOut() && expect != queryState && !isTerminalState(); timer.elapsed()) { wait(timeout); } return expect == queryState; }
Source:
<code>public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logger.entering(new Object[] { method, testResult }); try { if (ListenerManager.isCurrentMethodSkipped(this)) { logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG); return; } if (!method.isTestMethod()) { return; } Class<?> cls = method.getTestMethod().getInstance().getClass(); boolean isWebTestClass = cls.getAnnotation(WebTest.class) != null; boolean isMobileTestClass = cls.getAnnotation(MobileTest.class) != null; if ((isWebTestClass || isMobileTestClass)) { if (isLowPriority(method)) { testSessionSharingRules(method); } else { return; } } AbstractTestSession testSession = TestSessionFactory.newInstance(method); Grid.getThreadLocalTestSession().set(testSession); InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult); testSession.initializeTestSession(methodInfo); if (!(testSession instanceof BasicTestSession)) { try { LocalGridManager.spawnLocalHub(testSession); } catch (NoClassDefFoundError e) { logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have " + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e); System.exit(1); } } } catch (Exception e) { logger.log(Level.WARNING, "An error occurred while processing beforeInvocation: " + e.getMessage(), e); <START> Assert.fail(e.getMessage(), e); <END> } logger.exiting(); }</code><technical_language>@sundaramrajendran IMO, Asserts in tests a framework</technical_language>

Target:
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logger.entering(new Object[] { method, testResult }); try { if (ListenerManager.isCurrentMethodSkipped(this)) { logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG); return; } if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) { return; } if (isSeLionAnnotatedTestClass(method)) { if (!isValidBeforeCondition(method)) { return; } if (method.isTestMethod()) { if (isLowPriority(method)) { testSessionSharingRules(method); } else { return; } } } if (Grid.getTestSession() != null) { return; } AbstractTestSession testSession = TestSessionFactory.newInstance(method); Grid.getThreadLocalTestSession().set(testSession); InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult); testSession.initializeTestSession(methodInfo); if (!(testSession instanceof BasicTestSession)) { try { LocalGridManager.spawnLocalHub(testSession); } catch (NoClassDefFoundError e) { logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have " + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e); System.exit(1); } } } catch (RuntimeException e) { Grid.getThreadLocalException().set(e); } catch (Exception e) { Grid.getThreadLocalException().set(new RuntimeException(e.getMessage(), e)); } logger.exiting(); }
Source:
<code><START> protected void activateCellBroadcastSms(int activate, Message response) { <END> Log.e(TAG, "Error! The functionality cell broadcast sms is not implemented for GSM."); }</code><technical_language>Consider promoting base class default behavior? -- abstract base class is expected default implementations. If a radio technology added this reconsidered</technical_language>

Target:
protected void activateCellBroadcastSms(int activate, Message response) { Log.e(TAG, "Error! The functionality cell broadcast sms is not implemented for GSM."); response.recycle(); }
Source:
<code>public void selectUser(String username) { driver.findElement(By.id("select2-chosen-1")).click(); <START> String subContainerClass = "#select2-drop:not([style*='display: none'])"; driver.findElement(By.cssSelector( subContainerClass + " .select2-input")).sendKeys(username); driver.findElements(By.cssSelector(subContainerClass + " .select2-results li.select2-result-selectable")).get(0).click(); <END> }</code><technical_language>try similar approach [this](<LINK_0> point is copy-paste code Page Objects put ugly selectors methods</technical_language>

Target:
public void selectUser(String username) { clientsInput.select(username); }
Source:
<code>public void testParameterCollectionParenthesesAndPositional() { <START> final Item item = new Item( "Mouse", "Micro$oft mouse" ); <END> final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in (?1) and item.descr = ?2" ); q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); List params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( 1, params ); q.setParameter( 2, item2.getDescr() ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); } catch (Exception e){ if ( em.getTransaction() != null && em.getTransaction().isActive() ) { em.getTransaction().rollback(); } throw e; } finally { em.close(); } }</code><technical_language>remark neutrality</technical_language>

Target:
public void testParameterCollectionParenthesesAndPositional() { final Item item = new Item( "Mouse", "Microsoft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in (?1) and item.descr = ?2" ); List params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( 1, params ); q.setParameter( 2, item2.getDescr() ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); } catch (Exception e){ if ( em.getTransaction() != null && em.getTransaction().isActive() ) { em.getTransaction().rollback(); } throw e; } finally { em.close(); } }